summaryrefslogtreecommitdiff
path: root/chromium/third_party/nearby
diff options
context:
space:
mode:
authorAllan Sandfeld Jensen <allan.jensen@qt.io>2022-05-12 15:59:20 +0200
committerAllan Sandfeld Jensen <allan.jensen@qt.io>2022-05-25 06:57:22 +0000
commitf7eaed5286974984ba5f9e3189d8f49d03e99f81 (patch)
treecaed19b2af2024f35449fb0b781d0a25e09d4f8f /chromium/third_party/nearby
parent9729c4479fe23554eae6e6dd1f30ff488f470c84 (diff)
downloadqtwebengine-chromium-f7eaed5286974984ba5f9e3189d8f49d03e99f81.tar.gz
BASELINE: Update Chromium to 100.0.4896.167
Change-Id: I98cbeb5d7543d966ffe04d8cefded0c493a11333 Reviewed-by: Allan Sandfeld Jensen <allan.jensen@qt.io>
Diffstat (limited to 'chromium/third_party/nearby')
-rw-r--r--chromium/third_party/nearby/BUILD.gn662
-rw-r--r--chromium/third_party/nearby/OWNERS3
-rw-r--r--chromium/third_party/nearby/README.chromium2
-rw-r--r--chromium/third_party/nearby/src/CONTRIBUTING.md4
-rw-r--r--chromium/third_party/nearby/src/README.md52
-rw-r--r--chromium/third_party/nearby/src/connections/BUILD121
-rw-r--r--chromium/third_party/nearby/src/connections/advertising_options.cc52
-rw-r--r--chromium/third_party/nearby/src/connections/advertising_options.h53
-rw-r--r--chromium/third_party/nearby/src/connections/clients/windows/BUILD61
-rw-r--r--chromium/third_party/nearby/src/connections/clients/windows/core_adapter.cc153
-rw-r--r--chromium/third_party/nearby/src/connections/clients/windows/core_adapter.h267
-rw-r--r--chromium/third_party/nearby/src/connections/clients/windows/dart/core_adapter_dart.cc584
-rw-r--r--chromium/third_party/nearby/src/connections/clients/windows/dart/core_adapter_dart.h216
-rw-r--r--chromium/third_party/nearby/src/connections/connection_options.cc29
-rw-r--r--chromium/third_party/nearby/src/connections/connection_options.h55
-rw-r--r--chromium/third_party/nearby/src/connections/core.cc160
-rw-r--r--chromium/third_party/nearby/src/connections/core.h249
-rw-r--r--chromium/third_party/nearby/src/connections/core_test.cc53
-rw-r--r--chromium/third_party/nearby/src/connections/discovery_options.cc52
-rw-r--r--chromium/third_party/nearby/src/connections/discovery_options.h55
-rw-r--r--chromium/third_party/nearby/src/connections/event_logger.h39
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/BUILD214
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/BUILD.bazel216
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/base_bwu_handler.h58
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/base_endpoint_channel.cc401
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/base_endpoint_channel.h179
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/base_endpoint_channel_test.cc410
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/base_pcp_handler.cc1579
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/base_pcp_handler.h538
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/base_pcp_handler_test.cc796
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/ble_advertisement.cc278
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/ble_advertisement.h126
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/ble_advertisement_test.cc436
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/ble_endpoint_channel.cc65
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/ble_endpoint_channel.h46
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/bluetooth_bwu_handler.cc165
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/bluetooth_bwu_handler.h95
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/bluetooth_device_name.cc212
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/bluetooth_device_name.h93
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/bluetooth_device_name_test.cc207
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/bluetooth_endpoint_channel.cc65
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/bluetooth_endpoint_channel.h49
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/bwu_handler.h89
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/bwu_manager.cc1221
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/bwu_manager.h202
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/bwu_manager_test.cc111
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/client_proxy.cc773
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/client_proxy.h326
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/client_proxy_test.cc673
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/encryption_runner.cc389
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/encryption_runner.h86
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/encryption_runner_test.cc160
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/endpoint_channel.h119
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/endpoint_channel_manager.cc187
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/endpoint_channel_manager.h172
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/endpoint_channel_manager_test.cc32
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/endpoint_manager.cc674
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/endpoint_manager.h284
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/endpoint_manager_test.cc289
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/injected_bluetooth_device_store.cc90
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/injected_bluetooth_device_store.h69
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/injected_bluetooth_device_store_test.cc123
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/internal_payload.cc33
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/internal_payload.h106
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/internal_payload_factory.cc350
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/internal_payload_factory.h37
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/internal_payload_factory_test.cc183
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/BUILD112
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/BUILD.bazel113
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/ble.cc361
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/ble.h188
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/ble_test.cc264
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/BUILD72
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/advertisement_read_result.cc139
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/advertisement_read_result.h104
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/advertisement_read_result_test.cc143
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_advertisement.cc245
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_advertisement.h139
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_advertisement_header.cc138
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_advertisement_header.h101
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_advertisement_header_test.cc208
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_advertisement_test.cc455
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_packet.cc73
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_packet.h64
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_packet_test.cc111
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_peripheral.h49
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_peripheral_test.cc47
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/bloom_filter.cc105
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/bloom_filter.h101
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/bloom_filter_test.cc207
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/discovered_peripheral_callback.h45
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/bluetooth_classic.cc434
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/bluetooth_classic.h210
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/bluetooth_classic_test.cc291
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/bluetooth_radio.cc120
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/bluetooth_radio.h90
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/bluetooth_radio_test.cc60
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/lost_entity_tracker.h94
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/lost_entity_tracker_test.cc137
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/mediums.cc33
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/mediums.h73
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/utils.cc94
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/utils.h42
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/uuid.cc87
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/uuid.h (renamed from chromium/third_party/nearby/src/cpp/core/internal/mediums/uuid.h)0
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/uuid_test.cc71
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/webrtc.cc744
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/webrtc.h265
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/BUILD98
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/connection_flow.cc556
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/connection_flow.h233
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/connection_flow_test.cc408
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/data_channel_listener.h43
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/local_ice_candidate_listener.h39
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/session_description_wrapper.h (renamed from chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/session_description_wrapper.h)0
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/signaling_frames.cc134
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/signaling_frames.h58
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/signaling_frames_test.cc197
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/webrtc_socket_impl.cc190
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/webrtc_socket_impl.h123
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/webrtc_socket_impl_test.cc235
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_peer_id.cc54
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_peer_id.h52
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_peer_id_test.cc57
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_socket.h55
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_socket_stub.h69
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_stub.cc61
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_stub.h82
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_test.cc406
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/wifi_lan.cc429
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/wifi_lan.h198
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mediums/wifi_lan_test.cc348
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/message_lite.h (renamed from chromium/third_party/nearby/src/cpp/core/internal/message_lite.h)0
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mock_service_controller.h92
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/mock_service_controller_router.h101
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/offline_frames.cc502
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/offline_frames.h105
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/offline_frames_test.cc394
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/offline_frames_validator.cc381
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/offline_frames_validator.h33
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/offline_frames_validator_test.cc569
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/offline_service_controller.cc147
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/offline_service_controller.h100
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/offline_service_controller_test.cc389
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/offline_simulation_user.cc202
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/offline_simulation_user.h207
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/p2p_cluster_pcp_handler.cc1366
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/p2p_cluster_pcp_handler.h210
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/p2p_cluster_pcp_handler_test.cc273
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/p2p_point_to_point_pcp_handler.cc64
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/p2p_point_to_point_pcp_handler.h55
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/p2p_star_pcp_handler.cc69
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/p2p_star_pcp_handler.h59
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/payload_manager.cc1318
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/payload_manager.h322
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/payload_manager_test.cc374
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/pcp.h (renamed from chromium/third_party/nearby/src/cpp/core/internal/pcp.h)0
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/pcp_handler.h122
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/pcp_manager.cc148
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/pcp_manager.h87
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/pcp_manager_test.cc177
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/proto/BUILD48
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/proto/CMakeLists.txt (renamed from chromium/third_party/nearby/src/proto/connections/CMakeLists.txt)0
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/proto/offline_wire_formats.proto364
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/proto/offline_wire_formats_proto_config.asciipb (renamed from chromium/third_party/nearby/src/proto/connections/offline_wire_formats_proto_config.asciipb)0
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/service_controller.h104
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/service_controller_router.cc383
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/service_controller_router.h129
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/service_controller_router_test.cc450
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/simulation_user.cc181
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/simulation_user.h180
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/webrtc_bwu_handler.cc166
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/webrtc_bwu_handler.h99
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/webrtc_endpoint_channel.cc35
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/webrtc_endpoint_channel.h46
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/wifi_lan_bwu_handler.cc166
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/wifi_lan_bwu_handler.h80
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/wifi_lan_endpoint_channel.cc47
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/wifi_lan_endpoint_channel.h42
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/wifi_lan_service_info.cc205
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/wifi_lan_service_info.h97
-rw-r--r--chromium/third_party/nearby/src/connections/implementation/wifi_lan_service_info_test.cc171
-rw-r--r--chromium/third_party/nearby/src/connections/listeners.h198
-rw-r--r--chromium/third_party/nearby/src/connections/listeners_test.cc60
-rw-r--r--chromium/third_party/nearby/src/connections/medium_selector.h78
-rw-r--r--chromium/third_party/nearby/src/connections/options_base.h39
-rw-r--r--chromium/third_party/nearby/src/connections/out_of_band_connection_metadata.h60
-rw-r--r--chromium/third_party/nearby/src/connections/params.h43
-rw-r--r--chromium/third_party/nearby/src/connections/payload.cc101
-rw-r--r--chromium/third_party/nearby/src/connections/payload.h104
-rw-r--r--chromium/third_party/nearby/src/connections/payload_test.cc108
-rw-r--r--chromium/third_party/nearby/src/connections/power_level.h31
-rw-r--r--chromium/third_party/nearby/src/connections/status.h (renamed from chromium/third_party/nearby/src/cpp/core/status.h)0
-rw-r--r--chromium/third_party/nearby/src/connections/status_test.cc59
-rw-r--r--chromium/third_party/nearby/src/connections/strategy.cc59
-rw-r--r--chromium/third_party/nearby/src/connections/strategy.h72
-rw-r--r--chromium/third_party/nearby/src/connections/strategy_test.cc55
-rw-r--r--chromium/third_party/nearby/src/cpp/analytics/BUILD64
-rw-r--r--chromium/third_party/nearby/src/cpp/analytics/analytics_recorder.cc1113
-rw-r--r--chromium/third_party/nearby/src/cpp/analytics/analytics_recorder.h347
-rw-r--r--chromium/third_party/nearby/src/cpp/analytics/analytics_recorder_test.cc770
-rw-r--r--chromium/third_party/nearby/src/cpp/cal/api/BUILD11
-rw-r--r--chromium/third_party/nearby/src/cpp/cal/api/ble.h2
-rw-r--r--chromium/third_party/nearby/src/cpp/cal/base/BUILD5
-rw-r--r--chromium/third_party/nearby/src/cpp/cal/base/ble_types.h24
-rw-r--r--chromium/third_party/nearby/src/cpp/cal/public/BUILD16
-rw-r--r--chromium/third_party/nearby/src/cpp/cal/public/ble.cc6
-rw-r--r--chromium/third_party/nearby/src/cpp/cal/public/ble.h4
-rw-r--r--chromium/third_party/nearby/src/cpp/cal/public/ble_test.cc7
-rw-r--r--chromium/third_party/nearby/src/cpp/core/BUILD114
-rw-r--r--chromium/third_party/nearby/src/cpp/core/core.cc156
-rw-r--r--chromium/third_party/nearby/src/cpp/core/core.h247
-rw-r--r--chromium/third_party/nearby/src/cpp/core/core_test.cc52
-rw-r--r--chromium/third_party/nearby/src/cpp/core/event_logger.h39
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/BUILD214
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/base_bwu_handler.h58
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/base_endpoint_channel.cc364
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/base_endpoint_channel.h156
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/base_endpoint_channel_test.cc409
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/base_pcp_handler.cc1533
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/base_pcp_handler.h524
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/base_pcp_handler_test.cc785
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/ble_advertisement.cc278
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/ble_advertisement.h126
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/ble_advertisement_test.cc436
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/ble_endpoint_channel.cc65
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/ble_endpoint_channel.h46
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/bluetooth_bwu_handler.cc165
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/bluetooth_bwu_handler.h95
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/bluetooth_device_name.cc212
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/bluetooth_device_name.h93
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/bluetooth_device_name_test.cc207
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/bluetooth_endpoint_channel.cc65
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/bluetooth_endpoint_channel.h49
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/bwu_handler.h89
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/bwu_manager.cc1201
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/bwu_manager.h203
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/bwu_manager_test.cc110
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/client_proxy.cc774
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/client_proxy.h323
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/client_proxy_test.cc622
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/encryption_runner.cc389
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/encryption_runner.h86
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/encryption_runner_test.cc150
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/endpoint_channel.h107
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/endpoint_channel_manager.cc187
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/endpoint_channel_manager.h172
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/endpoint_channel_manager_test.cc31
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/endpoint_manager.cc675
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/endpoint_manager.h284
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/endpoint_manager_test.cc282
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/injected_bluetooth_device_store.cc90
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/injected_bluetooth_device_store.h69
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/injected_bluetooth_device_store_test.cc123
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/internal_payload.cc33
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/internal_payload.h106
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/internal_payload_factory.cc350
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/internal_payload_factory.h37
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/internal_payload_factory_test.cc182
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/BUILD142
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/ble.cc361
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/ble.h188
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_test.cc263
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/BUILD67
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/advertisement_read_result.cc139
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/advertisement_read_result.h104
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/advertisement_read_result_test.cc143
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_advertisement.cc245
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_advertisement.h139
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_advertisement_header.cc131
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_advertisement_header.h97
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_advertisement_header_test.cc202
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_advertisement_test.cc455
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_packet.cc73
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_packet.h64
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_packet_test.cc111
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_peripheral.h49
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_peripheral_test.cc47
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/discovered_peripheral_callback.h45
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/bloom_filter.cc105
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/bloom_filter.h101
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/bloom_filter_test.cc207
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/bluetooth_classic.cc434
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/bluetooth_classic.h210
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/bluetooth_classic_test.cc290
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/bluetooth_radio.cc120
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/bluetooth_radio.h90
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/bluetooth_radio_test.cc59
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/lost_entity_tracker.h94
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/lost_entity_tracker_test.cc137
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/mediums.cc33
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/mediums.h69
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/utils.cc94
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/utils.h42
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/uuid.cc87
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/uuid_test.cc70
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc.cc744
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc.h265
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/BUILD99
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/connection_flow.cc556
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/connection_flow.h233
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/connection_flow_test.cc407
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/data_channel_listener.h43
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/local_ice_candidate_listener.h39
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/signaling_frames.cc134
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/signaling_frames.h58
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/signaling_frames_test.cc196
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/webrtc_socket.cc190
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/webrtc_socket.h123
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/webrtc_socket_test.cc234
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc_peer_id.cc54
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc_peer_id.h52
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc_peer_id_test.cc56
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc_socket_wrapper.h55
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc_test.cc405
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/wifi_lan.cc409
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/wifi_lan.h194
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mediums/wifi_lan_test.cc347
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mock_service_controller.h92
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/mock_service_controller_router.h101
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/offline_frames.cc502
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/offline_frames.h105
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/offline_frames_test.cc393
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/offline_frames_validator.cc381
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/offline_frames_validator.h33
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/offline_frames_validator_test.cc568
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/offline_service_controller.cc141
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/offline_service_controller.h99
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/offline_service_controller_test.cc388
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/offline_simulation_user.cc202
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/offline_simulation_user.h202
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/p2p_cluster_pcp_handler.cc1364
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/p2p_cluster_pcp_handler.h205
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/p2p_cluster_pcp_handler_test.cc259
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/p2p_point_to_point_pcp_handler.cc64
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/p2p_point_to_point_pcp_handler.h55
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/p2p_star_pcp_handler.cc69
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/p2p_star_pcp_handler.h59
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/payload_manager.cc1318
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/payload_manager.h322
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/payload_manager_test.cc373
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/pcp_handler.h122
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/pcp_manager.cc146
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/pcp_manager.h88
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/pcp_manager_test.cc177
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/service_controller.h102
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/service_controller_router.cc384
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/service_controller_router.h130
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/service_controller_router_test.cc421
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/simulation_user.cc181
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/simulation_user.h172
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/webrtc_bwu_handler.cc167
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/webrtc_bwu_handler.h95
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/webrtc_endpoint_channel.cc35
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/webrtc_endpoint_channel.h42
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_bwu_handler.cc166
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_bwu_handler.h80
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_endpoint_channel.cc47
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_endpoint_channel.h42
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_service_info.cc205
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_service_info.h97
-rw-r--r--chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_service_info_test.cc171
-rw-r--r--chromium/third_party/nearby/src/cpp/core/listeners.h198
-rw-r--r--chromium/third_party/nearby/src/cpp/core/listeners_test.cc59
-rw-r--r--chromium/third_party/nearby/src/cpp/core/options.cc89
-rw-r--r--chromium/third_party/nearby/src/cpp/core/options.h155
-rw-r--r--chromium/third_party/nearby/src/cpp/core/params.h43
-rw-r--r--chromium/third_party/nearby/src/cpp/core/payload.cc101
-rw-r--r--chromium/third_party/nearby/src/cpp/core/payload.h104
-rw-r--r--chromium/third_party/nearby/src/cpp/core/payload_test.cc107
-rw-r--r--chromium/third_party/nearby/src/cpp/core/status_test.cc58
-rw-r--r--chromium/third_party/nearby/src/cpp/core/strategy.cc59
-rw-r--r--chromium/third_party/nearby/src/cpp/core/strategy.h72
-rw-r--r--chromium/third_party/nearby/src/cpp/core/strategy_test.cc55
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/api/BUILD100
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/api/ble.h125
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/api/ble_v2.h406
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/api/bluetooth_classic.h162
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/api/condition_variable.h51
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/api/count_down_latch.h45
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/api/crypto.h38
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/api/executor.h44
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/api/future.h46
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/api/input_file.h40
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/api/listenable_future.h45
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/api/output_file.h36
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/api/platform.h111
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/api/scheduled_executor.h50
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/api/server_sync.h76
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/api/settable_future.h49
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/api/submittable_executor.h47
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/api/system_clock.h37
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/api/webrtc.h73
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/api/wifi_lan.h153
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/BUILD243
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/base64_utils.cc41
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/base64_utils.h33
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/base_input_stream.cc99
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/base_input_stream.h63
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/base_mutex_lock.h40
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/base_pipe.cc109
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/base_pipe.h138
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/bluetooth_utils.cc75
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/bluetooth_utils.h46
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/bluetooth_utils_test.cc89
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/byte_array_test.cc90
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/byte_utils.cc39
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/byte_utils.h38
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/byte_utils_test.cc44
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/callable.h37
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/cancellation_flag.cc80
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/cancellation_flag_listener.h43
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/cancellation_flag_test.cc212
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/error_code_params.h64
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/error_code_recorder.cc116
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/error_code_recorder.h86
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/error_code_recorder_test.cc136
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/exception_test.cc120
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/feature_flags_test.cc46
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/input_stream.cc44
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/input_stream.h46
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/logging.h84
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/medium_environment.cc676
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/medium_environment.h321
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/nsd_service_info.cc23
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/output_stream.h39
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/prng.cc59
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/prng_test.cc87
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/base/socket.h39
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/g3/BUILD131
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/g3/atomic_boolean.h44
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/g3/atomic_reference.h43
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/g3/ble.cc378
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/g3/ble.h228
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/g3/bluetooth_adapter.cc135
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/g3/bluetooth_adapter.h142
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/g3/bluetooth_classic.cc278
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/g3/bluetooth_classic.h238
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/g3/condition_variable.h51
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/g3/crypto.cc53
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/g3/log_message.cc74
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/g3/log_message.h44
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/g3/multi_thread_executor.h66
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/g3/mutex.h61
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/g3/pipe.h44
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/g3/platform.cc172
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/g3/scheduled_executor.cc79
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/g3/scheduled_executor.h54
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/g3/single_thread_executor.h36
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/g3/system_clock.cc30
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/g3/webrtc.cc96
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/g3/webrtc.h81
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/g3/wifi_lan.cc371
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/g3/wifi_lan.h279
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/shared/BUILD90
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/shared/count_down_latch.cc54
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/shared/count_down_latch.h53
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/shared/file.cc96
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/shared/file.h67
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/shared/file_test.cc148
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/shared/posix_condition_variable.cc44
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/shared/posix_condition_variable.h45
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/shared/posix_mutex.cc40
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/shared/posix_mutex.h45
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/BUILD173
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/atomic_boolean.h45
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/atomic_boolean_test.cc32
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/atomic_reference.h45
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/atomic_reference_test.cc72
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/ble.h155
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_adapter.cc452
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_adapter.h99
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic.h23
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_device.cc65
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_device.h93
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_medium.cc443
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_medium.h191
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_medium_test.cc189
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_server_socket.cc191
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_server_socket.h129
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_socket.cc194
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_socket.h139
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/cancelable.h50
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/condition_variable.h55
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/condition_variable_test.cc104
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/count_down_latch_test.cc186
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/crypto.cc58
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/crypto_test.cc50
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/executor.cc80
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/executor.h60
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/executor_test.cc348
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/future.h50
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/BUILD42
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/input_file.h50
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/input_file_test.cc152
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/listenable_future.h41
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/log_message.cc73
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/log_message.h45
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/mutex.h69
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/mutex_test.cc109
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/output_file.h47
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/output_file_test.cc90
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/platform.cc174
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/runner.h42
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/scheduled_executor.cc149
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/scheduled_executor.h65
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/scheduled_executor_test.cc174
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/server_sync.h90
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/settable_future.h51
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/submittable_executor.cc65
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/submittable_executor.h55
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/submittable_executor_test.cc240
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/system_clock.cc43
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/test_utils.cc57
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/test_utils.h47
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/thread_pool.cc531
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/thread_pool.h106
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/utils.cc127
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/utils.h65
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/utils_test.cc31
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/webrtc.h78
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/wifi.h98
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/wifi_lan.h342
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/wifi_lan_medium.cc463
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/wifi_lan_server_socket.cc180
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/impl/windows/wifi_lan_socket.cc142
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/BUILD189
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/atomic_boolean.h50
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/atomic_boolean_test.cc49
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/atomic_reference.h87
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/atomic_reference_test.cc89
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/ble.cc138
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/ble.h166
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/ble_test.cc305
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/bluetooth_adapter.h126
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/bluetooth_adapter_test.cc68
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/bluetooth_classic.cc99
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/bluetooth_classic.h235
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/bluetooth_classic_test.cc293
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/cancelable.h60
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/cancelable_alarm.h71
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/cancelable_alarm_test.cc68
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/cancellable_task.h70
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/condition_variable.h49
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/condition_variable_test.cc82
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/count_down_latch.h54
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/count_down_latch_test.cc70
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/crypto.h20
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/crypto_test.cc48
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/file.cc92
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/file.h116
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/future.h56
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/future_test.cc116
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/logging.h20
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/logging_test.cc52
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/monitored_runnable.cc59
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/monitored_runnable.h48
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/multi_thread_executor.h43
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/multi_thread_executor_test.cc138
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/mutex.h78
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/mutex_lock.h45
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/mutex_test.cc117
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/pending_job_registry.cc91
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/pending_job_registry.h55
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/pipe.cc35
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/pipe.h36
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/pipe_test.cc346
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/scheduled_executor.h109
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/scheduled_executor_test.cc206
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/settable_future.h128
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/single_thread_executor.h41
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/single_thread_executor_test.cc139
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/submittable_executor.h130
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/system_clock.h20
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/thread_check_callable.h46
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/thread_check_nocompile.cc83
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/thread_check_nocompile_test.py26
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/thread_check_runnable.h47
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/webrtc.h99
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/wifi_lan.cc146
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/wifi_lan.h205
-rw-r--r--chromium/third_party/nearby/src/cpp/platform/public/wifi_lan_test.cc390
-rw-r--r--chromium/third_party/nearby/src/docs/ios_build.md3
-rw-r--r--chromium/third_party/nearby/src/internal/analytics/BUILD43
-rw-r--r--chromium/third_party/nearby/src/internal/analytics/analytics_recorder.cc1220
-rw-r--r--chromium/third_party/nearby/src/internal/analytics/analytics_recorder.h369
-rw-r--r--chromium/third_party/nearby/src/internal/analytics/analytics_recorder_test.cc941
-rw-r--r--chromium/third_party/nearby/src/internal/analytics/connection_attempt_metadata_params.h44
-rw-r--r--chromium/third_party/nearby/src/internal/platform/BUILD396
-rw-r--r--chromium/third_party/nearby/src/internal/platform/atomic_boolean.h50
-rw-r--r--chromium/third_party/nearby/src/internal/platform/atomic_boolean_test.cc50
-rw-r--r--chromium/third_party/nearby/src/internal/platform/atomic_reference.h87
-rw-r--r--chromium/third_party/nearby/src/internal/platform/atomic_reference_test.cc89
-rw-r--r--chromium/third_party/nearby/src/internal/platform/base64_utils.cc41
-rw-r--r--chromium/third_party/nearby/src/internal/platform/base64_utils.h33
-rw-r--r--chromium/third_party/nearby/src/internal/platform/base_input_stream.cc99
-rw-r--r--chromium/third_party/nearby/src/internal/platform/base_input_stream.h63
-rw-r--r--chromium/third_party/nearby/src/internal/platform/base_mutex_lock.h40
-rw-r--r--chromium/third_party/nearby/src/internal/platform/base_pipe.cc109
-rw-r--r--chromium/third_party/nearby/src/internal/platform/base_pipe.h138
-rw-r--r--chromium/third_party/nearby/src/internal/platform/ble.cc138
-rw-r--r--chromium/third_party/nearby/src/internal/platform/ble.h166
-rw-r--r--chromium/third_party/nearby/src/internal/platform/ble_test.cc306
-rw-r--r--chromium/third_party/nearby/src/internal/platform/bluetooth_adapter.h126
-rw-r--r--chromium/third_party/nearby/src/internal/platform/bluetooth_adapter_test.cc69
-rw-r--r--chromium/third_party/nearby/src/internal/platform/bluetooth_classic.cc99
-rw-r--r--chromium/third_party/nearby/src/internal/platform/bluetooth_classic.h235
-rw-r--r--chromium/third_party/nearby/src/internal/platform/bluetooth_classic_test.cc294
-rw-r--r--chromium/third_party/nearby/src/internal/platform/bluetooth_utils.cc75
-rw-r--r--chromium/third_party/nearby/src/internal/platform/bluetooth_utils.h46
-rw-r--r--chromium/third_party/nearby/src/internal/platform/bluetooth_utils_test.cc89
-rw-r--r--chromium/third_party/nearby/src/internal/platform/byte_array.h (renamed from chromium/third_party/nearby/src/cpp/platform/base/byte_array.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/byte_array_test.cc90
-rw-r--r--chromium/third_party/nearby/src/internal/platform/byte_utils.cc39
-rw-r--r--chromium/third_party/nearby/src/internal/platform/byte_utils.h38
-rw-r--r--chromium/third_party/nearby/src/internal/platform/byte_utils_test.cc44
-rw-r--r--chromium/third_party/nearby/src/internal/platform/callable.h37
-rw-r--r--chromium/third_party/nearby/src/internal/platform/cancelable.h60
-rw-r--r--chromium/third_party/nearby/src/internal/platform/cancelable_alarm.h71
-rw-r--r--chromium/third_party/nearby/src/internal/platform/cancelable_alarm_test.cc69
-rw-r--r--chromium/third_party/nearby/src/internal/platform/cancellable_task.h70
-rw-r--r--chromium/third_party/nearby/src/internal/platform/cancellation_flag.cc80
-rw-r--r--chromium/third_party/nearby/src/internal/platform/cancellation_flag.h (renamed from chromium/third_party/nearby/src/cpp/platform/base/cancellation_flag.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/cancellation_flag_listener.h43
-rw-r--r--chromium/third_party/nearby/src/internal/platform/cancellation_flag_test.cc213
-rw-r--r--chromium/third_party/nearby/src/internal/platform/condition_variable.h49
-rw-r--r--chromium/third_party/nearby/src/internal/platform/condition_variable_test.cc83
-rw-r--r--chromium/third_party/nearby/src/internal/platform/core_config.h (renamed from chromium/third_party/nearby/src/cpp/platform/public/core_config.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/count_down_latch.h54
-rw-r--r--chromium/third_party/nearby/src/internal/platform/count_down_latch_test.cc70
-rw-r--r--chromium/third_party/nearby/src/internal/platform/crypto.h20
-rw-r--r--chromium/third_party/nearby/src/internal/platform/crypto_test.cc49
-rw-r--r--chromium/third_party/nearby/src/internal/platform/error_code_params.h64
-rw-r--r--chromium/third_party/nearby/src/internal/platform/error_code_recorder.cc116
-rw-r--r--chromium/third_party/nearby/src/internal/platform/error_code_recorder.h86
-rw-r--r--chromium/third_party/nearby/src/internal/platform/error_code_recorder_test.cc137
-rw-r--r--chromium/third_party/nearby/src/internal/platform/exception.h (renamed from chromium/third_party/nearby/src/cpp/platform/base/exception.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/exception_test.cc121
-rw-r--r--chromium/third_party/nearby/src/internal/platform/feature_flags.h (renamed from chromium/third_party/nearby/src/cpp/platform/base/feature_flags.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/feature_flags_test.cc46
-rw-r--r--chromium/third_party/nearby/src/internal/platform/file.cc92
-rw-r--r--chromium/third_party/nearby/src/internal/platform/file.h116
-rw-r--r--chromium/third_party/nearby/src/internal/platform/future.h56
-rw-r--r--chromium/third_party/nearby/src/internal/platform/future_test.cc116
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/BUILD94
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/atomic_boolean.h (renamed from chromium/third_party/nearby/src/cpp/platform/api/atomic_boolean.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/atomic_reference.h (renamed from chromium/third_party/nearby/src/cpp/platform/api/atomic_reference.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ble.h125
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ble_v2.h406
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/bluetooth_adapter.h (renamed from chromium/third_party/nearby/src/cpp/platform/api/bluetooth_adapter.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/bluetooth_classic.h162
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/cancelable.h (renamed from chromium/third_party/nearby/src/cpp/platform/api/cancelable.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/condition_variable.h51
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/count_down_latch.h45
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/crypto.h38
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/executor.h44
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/future.h46
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/g3/BUILD128
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/g3/atomic_boolean.h44
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/g3/atomic_reference.h43
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/g3/ble.cc378
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/g3/ble.h228
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/g3/bluetooth_adapter.cc135
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/g3/bluetooth_adapter.h142
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/g3/bluetooth_classic.cc278
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/g3/bluetooth_classic.h238
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/g3/condition_variable.h51
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/g3/crypto.cc53
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/g3/log_message.cc86
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/g3/log_message.h44
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/g3/multi_thread_executor.h66
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/g3/mutex.h61
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/g3/pipe.h44
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/g3/platform.cc176
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/g3/scheduled_executor.cc79
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/g3/scheduled_executor.h54
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/g3/single_thread_executor.h36
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/g3/system_clock.cc30
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/g3/webrtc.cc97
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/g3/webrtc.h81
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/g3/wifi_lan.cc371
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/g3/wifi_lan.h285
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/input_file.h40
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/BUILD72
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample.pngbin0 -> 78999 bytes
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample.xcodeproj/project.pbxproj355
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/AppDelegate.h34
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/AppDelegate.m23
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/Assets.xcassets/AppIcon.appiconset/Contents.json98
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/Assets.xcassets/Contents.json6
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/Base.lproj/LaunchScreen.storyboard25
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/Base.lproj/Main.storyboard46
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/Info.plist51
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/ViewController.h24
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/ViewController.m291
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/main.m27
-rwxr-xr-xchromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/README.md198
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/XcodeSetup.pngbin0 -> 714590 bytes
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/GNCAdvertiser.h84
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/GNCConnection.h167
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/GNCConnections.h20
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/GNCDiscoverer.h95
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/GNCPayload.h64
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCAdvertiser.mm317
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCCore.h55
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCCore.mm94
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCCoreConnection.h44
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCCoreConnection.mm188
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCDiscoverer.mm401
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCPayload+Internal.h36
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCPayload.mm94
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCPayloadListener.h55
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCPayloadListener.mm218
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCUtils.h42
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCUtils.mm77
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/platform.mm151
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/BUILD56
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/GNCLeaks.h18
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/GNCLeaks.m27
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/GNCMConnection.h101
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/GNCMConnection.m31
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourBrowser.h42
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourBrowser.m176
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourConnection.h38
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourConnection.m224
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourService.h48
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourService.m88
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourUtils.h18
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourUtils.m17
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/BUILD94
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/atomic_boolean.h46
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/atomic_boolean_test.cc78
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/atomic_uint32.h47
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/atomic_uint32_test.cc64
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/condition_variable.cc37
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/condition_variable.h48
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/condition_variable_test.cc84
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/count_down_latch.cc40
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/count_down_latch.h49
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/count_down_latch_test.cc83
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/crypto.mm39
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/input_file.h48
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/input_file.mm69
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/log_message.h47
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/log_message.mm87
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/multi_thread_executor.h47
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/multi_thread_executor.mm40
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/mutex.h84
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/mutex_test.cc92
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/scheduled_executor.h68
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/scheduled_executor.mm144
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/single_thread_executor.h35
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/system_clock.cc33
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/utils.h74
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/utils.mm104
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/wifi_lan.h202
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/wifi_lan.mm497
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Shared/BUILD30
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Shared/GNCUtils.h50
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Shared/GNCUtils.m65
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/BUILD63
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/Platform/GNCCryptoTest.mm52
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/Platform/GNCInputFileTest.mm56
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/Platform/GNCMultiThreadExecutorTest.mm114
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/Platform/GNCScheduledExecutorTest.mm139
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/Platform/GNCSingleThreadExecutorTest.mm95
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/Shared/GNCUtilsTest.mm46
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/listenable_future.h45
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/log_message.h (renamed from chromium/third_party/nearby/src/cpp/platform/api/log_message.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/mutex.h (renamed from chromium/third_party/nearby/src/cpp/platform/api/mutex.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/output_file.h36
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/platform.h115
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/scheduled_executor.h50
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/server_sync.h76
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/settable_future.h49
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/shared/BUILD87
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/shared/count_down_latch.cc54
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/shared/count_down_latch.h53
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/shared/file.cc101
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/shared/file.h58
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/shared/file_test.cc149
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/shared/posix_condition_variable.cc44
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/shared/posix_condition_variable.h45
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/shared/posix_mutex.cc40
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/shared/posix_mutex.h45
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/submittable_executor.h47
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/system_clock.h37
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/webrtc.h73
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/wifi.h (renamed from chromium/third_party/nearby/src/cpp/platform/api/wifi.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/wifi_lan.h157
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/BUILD172
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/atomic_boolean.h45
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/atomic_boolean_test.cc32
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/atomic_reference.h45
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/atomic_reference_test.cc72
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/ble.h155
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_adapter.cc456
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_adapter.h99
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic.h23
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_device.cc65
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_device.h93
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_medium.cc475
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_medium.h192
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_medium_test.cc189
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_server_socket.cc196
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_server_socket.h129
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_socket.cc194
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_socket.h139
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/cancelable.h50
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/condition_variable.h55
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/condition_variable_test.cc104
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/count_down_latch_test.cc186
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/crypto.cc58
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/crypto_test.cc50
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/executor.cc80
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/executor.h60
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/executor_test.cc348
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/future.h50
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/BUILD42
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.AI.MachineLearning.Preview.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.AI.MachineLearning.Preview.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.AI.MachineLearning.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.AI.MachineLearning.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Activation.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Activation.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.AppExtensions.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.AppExtensions.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.AppService.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.AppService.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Appointments.AppointmentsProvider.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Appointments.AppointmentsProvider.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Appointments.DataProvider.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Appointments.DataProvider.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Appointments.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Appointments.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Background.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Background.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Calls.Background.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Calls.Background.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Calls.Provider.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Calls.Provider.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Calls.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Calls.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Chat.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Chat.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.CommunicationBlocking.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.CommunicationBlocking.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Contacts.DataProvider.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Contacts.DataProvider.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Contacts.Provider.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Contacts.Provider.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Contacts.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Contacts.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.ConversationalAgent.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.ConversationalAgent.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Core.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Core.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.DataTransfer.DragDrop.Core.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.DataTransfer.DragDrop.Core.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.DataTransfer.DragDrop.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.DataTransfer.DragDrop.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.DataTransfer.ShareTarget.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.DataTransfer.ShareTarget.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.DataTransfer.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.DataTransfer.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Email.DataProvider.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Email.DataProvider.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Email.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Email.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.ExtendedExecution.Foreground.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.ExtendedExecution.Foreground.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.ExtendedExecution.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.ExtendedExecution.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Holographic.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Holographic.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.LockScreen.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.LockScreen.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Payments.Provider.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Payments.Provider.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Payments.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Payments.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Preview.Holographic.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Preview.Holographic.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Preview.InkWorkspace.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Preview.InkWorkspace.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Preview.Notes.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Preview.Notes.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Resources.Core.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Resources.Core.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Resources.Management.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Resources.Management.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Resources.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Resources.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Search.Core.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Search.Core.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Search.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Search.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.SocialInfo.Provider.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.SocialInfo.Provider.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.SocialInfo.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.SocialInfo.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Store.LicenseManagement.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Store.LicenseManagement.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Store.Preview.InstallControl.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Store.Preview.InstallControl.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Store.Preview.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Store.Preview.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Store.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Store.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.UserActivities.Core.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.UserActivities.Core.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.UserActivities.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.UserActivities.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.UserDataAccounts.Provider.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.UserDataAccounts.Provider.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.UserDataAccounts.SystemAccess.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.UserDataAccounts.SystemAccess.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.UserDataAccounts.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.UserDataAccounts.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.UserDataTasks.DataProvider.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.UserDataTasks.DataProvider.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.UserDataTasks.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.UserDataTasks.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.VoiceCommands.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.VoiceCommands.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Wallet.System.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Wallet.System.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Wallet.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Wallet.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Data.Html.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Data.Html.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Data.Json.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Data.Json.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Data.Pdf.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Data.Pdf.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Data.Text.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Data.Text.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Data.Xml.Dom.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Data.Xml.Dom.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Data.Xml.Xsl.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Data.Xml.Xsl.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Adc.Provider.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Adc.Provider.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Adc.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Adc.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.AllJoyn.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.AllJoyn.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Background.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Background.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Bluetooth.Advertisement.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Bluetooth.Advertisement.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Bluetooth.Background.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Bluetooth.Background.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Bluetooth.GenericAttributeProfile.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Bluetooth.GenericAttributeProfile.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Bluetooth.Rfcomm.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Bluetooth.Rfcomm.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Bluetooth.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Bluetooth.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Custom.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Custom.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Display.Core.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Display.Core.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Display.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Display.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Enumeration.Pnp.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Enumeration.Pnp.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Enumeration.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Enumeration.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Geolocation.Geofencing.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Geolocation.Geofencing.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Geolocation.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Geolocation.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Gpio.Provider.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Gpio.Provider.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Gpio.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Gpio.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Haptics.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Haptics.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.HumanInterfaceDevice.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.HumanInterfaceDevice.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.I2c.Provider.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.I2c.Provider.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.I2c.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.I2c.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Input.Preview.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Input.Preview.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Input.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Input.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Lights.Effects.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Lights.Effects.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Lights.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Lights.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Midi.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Midi.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Perception.Provider.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Perception.Provider.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Perception.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Perception.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.PointOfService.Provider.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.PointOfService.Provider.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.PointOfService.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.PointOfService.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Portable.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Portable.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Power.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Power.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Printers.Extensions.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Printers.Extensions.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Printers.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Printers.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Pwm.Provider.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Pwm.Provider.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Pwm.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Pwm.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Radios.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Radios.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Scanners.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Scanners.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Sensors.Custom.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Sensors.Custom.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Sensors.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Sensors.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.SerialCommunication.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.SerialCommunication.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.SmartCards.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.SmartCards.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Sms.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Sms.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Spi.Provider.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Spi.Provider.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Spi.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Spi.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Usb.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Usb.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.WiFi.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.WiFi.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.WiFiDirect.Services.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.WiFiDirect.Services.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.WiFiDirect.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.WiFiDirect.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Embedded.DeviceLockdown.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Embedded.DeviceLockdown.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Foundation.Collections.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Foundation.Collections.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Foundation.Diagnostics.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Foundation.Diagnostics.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Foundation.Metadata.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Foundation.Metadata.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Foundation.Numerics.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Foundation.Numerics.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Foundation.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Foundation.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Gaming.Input.Custom.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Gaming.Input.Custom.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Gaming.Input.ForceFeedback.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Gaming.Input.ForceFeedback.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Gaming.Input.Preview.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Gaming.Input.Preview.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Gaming.Input.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Gaming.Input.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Gaming.Preview.GamesEnumeration.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Gaming.Preview.GamesEnumeration.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Gaming.UI.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Gaming.UI.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Gaming.XboxLive.Storage.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Gaming.XboxLive.Storage.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Globalization.Collation.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Globalization.Collation.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Globalization.DateTimeFormatting.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Globalization.DateTimeFormatting.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Globalization.Fonts.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Globalization.Fonts.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Globalization.NumberFormatting.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Globalization.NumberFormatting.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Globalization.PhoneNumberFormatting.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Globalization.PhoneNumberFormatting.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Globalization.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Globalization.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Capture.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Capture.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.DirectX.Direct3D11.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.DirectX.Direct3D11.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.DirectX.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.DirectX.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Display.Core.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Display.Core.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Display.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Display.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Effects.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Effects.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Holographic.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Holographic.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Imaging.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Imaging.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Printing.OptionDetails.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Printing.OptionDetails.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Printing.PrintTicket.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Printing.PrintTicket.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Printing.Workflow.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Printing.Workflow.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Printing.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Printing.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Printing3D.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Printing3D.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Management.Core.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Management.Core.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Management.Deployment.Preview.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Management.Deployment.Preview.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Management.Deployment.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Management.Deployment.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Management.Policies.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Management.Policies.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Management.Update.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Management.Update.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Management.Workplace.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Management.Workplace.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Management.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Management.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.AppBroadcasting.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.AppBroadcasting.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.AppRecording.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.AppRecording.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Audio.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Audio.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Capture.Core.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Capture.Core.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Capture.Frames.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Capture.Frames.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Capture.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Capture.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Casting.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Casting.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.ClosedCaptioning.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.ClosedCaptioning.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.ContentRestrictions.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.ContentRestrictions.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Control.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Control.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Core.Preview.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Core.Preview.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Core.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Core.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Devices.Core.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Devices.Core.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Devices.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Devices.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.DialProtocol.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.DialProtocol.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Editing.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Editing.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Effects.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Effects.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.FaceAnalysis.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.FaceAnalysis.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Import.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Import.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.MediaProperties.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.MediaProperties.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Miracast.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Miracast.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Ocr.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Ocr.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.PlayTo.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.PlayTo.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Playback.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Playback.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Playlists.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Playlists.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Protection.PlayReady.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Protection.PlayReady.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Protection.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Protection.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Render.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Render.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.SpeechRecognition.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.SpeechRecognition.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.SpeechSynthesis.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.SpeechSynthesis.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Streaming.Adaptive.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Streaming.Adaptive.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Transcoding.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Transcoding.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.BackgroundTransfer.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.BackgroundTransfer.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.Connectivity.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.Connectivity.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.NetworkOperators.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.NetworkOperators.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.Proximity.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.Proximity.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.PushNotifications.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.PushNotifications.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.ServiceDiscovery.Dnssd.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.ServiceDiscovery.Dnssd.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.Sockets.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.Sockets.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.Vpn.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.Vpn.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.XboxLive.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.XboxLive.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Perception.Automation.Core.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Perception.Automation.Core.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Perception.People.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Perception.People.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Perception.Spatial.Preview.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Perception.Spatial.Preview.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Perception.Spatial.Surfaces.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Perception.Spatial.Surfaces.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Perception.Spatial.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Perception.Spatial.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Perception.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Perception.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.ApplicationModel.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.ApplicationModel.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.Devices.Notification.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.Devices.Notification.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.Devices.Power.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.Devices.Power.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.Management.Deployment.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.Management.Deployment.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.Media.Devices.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.Media.Devices.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.Notification.Management.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.Notification.Management.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.PersonalInformation.Provisioning.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.PersonalInformation.Provisioning.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.PersonalInformation.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.PersonalInformation.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.Speech.Recognition.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.Speech.Recognition.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.StartScreen.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.StartScreen.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.System.Power.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.System.Power.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.System.Profile.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.System.Profile.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.System.UserProfile.GameServices.Core.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.System.UserProfile.GameServices.Core.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.System.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.System.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.UI.Input.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.UI.Input.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Authentication.Identity.Core.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Authentication.Identity.Core.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Authentication.Identity.Provider.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Authentication.Identity.Provider.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Authentication.Identity.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Authentication.Identity.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Authentication.OnlineId.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Authentication.OnlineId.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Authentication.Web.Core.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Authentication.Web.Core.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Authentication.Web.Provider.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Authentication.Web.Provider.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Authentication.Web.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Authentication.Web.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Authorization.AppCapabilityAccess.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Authorization.AppCapabilityAccess.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Credentials.UI.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Credentials.UI.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Credentials.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Credentials.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Cryptography.Certificates.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Cryptography.Certificates.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Cryptography.Core.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Cryptography.Core.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Cryptography.DataProtection.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Cryptography.DataProtection.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Cryptography.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Cryptography.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.DataProtection.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.DataProtection.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.EnterpriseData.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.EnterpriseData.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.ExchangeActiveSyncProvisioning.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.ExchangeActiveSyncProvisioning.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Isolation.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Isolation.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Services.Cortana.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Services.Cortana.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Services.Maps.Guidance.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Services.Maps.Guidance.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Services.Maps.LocalSearch.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Services.Maps.LocalSearch.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Services.Maps.OfflineMaps.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Services.Maps.OfflineMaps.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Services.Maps.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Services.Maps.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Services.Store.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Services.Store.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Services.TargetedContent.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Services.TargetedContent.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.AccessCache.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.AccessCache.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.BulkAccess.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.BulkAccess.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.Compression.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.Compression.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.FileProperties.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.FileProperties.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.Pickers.Provider.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.Pickers.Provider.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.Pickers.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.Pickers.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.Provider.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.Provider.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.Search.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.Search.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.Streams.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.Streams.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Diagnostics.DevicePortal.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Diagnostics.DevicePortal.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Diagnostics.Telemetry.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Diagnostics.Telemetry.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Diagnostics.TraceReporting.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Diagnostics.TraceReporting.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Diagnostics.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Diagnostics.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Display.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Display.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Implementation.FileExplorer.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Implementation.FileExplorer.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Inventory.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Inventory.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Power.Diagnostics.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Power.Diagnostics.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Power.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Power.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Preview.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Preview.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Profile.SystemManufacturers.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Profile.SystemManufacturers.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Profile.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Profile.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.RemoteDesktop.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.RemoteDesktop.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.RemoteSystems.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.RemoteSystems.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Threading.Core.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Threading.Core.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Threading.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Threading.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Update.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Update.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.UserProfile.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.UserProfile.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Accessibility.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Accessibility.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.ApplicationSettings.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.ApplicationSettings.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Composition.Core.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Composition.Core.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Composition.Desktop.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Composition.Desktop.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Composition.Diagnostics.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Composition.Diagnostics.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Composition.Effects.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Composition.Effects.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Composition.Interactions.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Composition.Interactions.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Composition.Scenes.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Composition.Scenes.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Composition.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Composition.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Core.AnimationMetrics.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Core.AnimationMetrics.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Core.Preview.Communications.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Core.Preview.Communications.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Core.Preview.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Core.Preview.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Core.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Core.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.Core.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.Core.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.Inking.Analysis.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.Inking.Analysis.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.Inking.Core.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.Inking.Core.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.Inking.Preview.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.Inking.Preview.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.Inking.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.Inking.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.Preview.Injection.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.Preview.Injection.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.Preview.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.Preview.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.Spatial.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.Spatial.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Notifications.Management.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Notifications.Management.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Notifications.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Notifications.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Popups.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Popups.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Shell.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Shell.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.StartScreen.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.StartScreen.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Text.Core.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Text.Core.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Text.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Text.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.UIAutomation.Core.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.UIAutomation.Core.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.UIAutomation.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.UIAutomation.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.ViewManagement.Core.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.ViewManagement.Core.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.ViewManagement.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.ViewManagement.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.WebUI.Core.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.WebUI.Core.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.WebUI.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.WebUI.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.WindowManagement.Preview.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.WindowManagement.Preview.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.WindowManagement.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.WindowManagement.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Automation.Peers.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Automation.Peers.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Automation.Provider.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Automation.Provider.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Automation.Text.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Automation.Text.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Automation.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Automation.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Controls.Maps.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Controls.Maps.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Controls.Primitives.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Controls.Primitives.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Controls.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Controls.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Core.Direct.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Core.Direct.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Data.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Data.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Documents.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Documents.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Hosting.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Hosting.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Input.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Input.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Interop.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Interop.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Markup.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Markup.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Media.Animation.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Media.Animation.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Media.Imaging.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Media.Imaging.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Media.Media3D.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Media.Media3D.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Media.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Media.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Navigation.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Navigation.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Printing.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Printing.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Resources.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Resources.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Shapes.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Shapes.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.AtomPub.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.AtomPub.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.Http.Diagnostics.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.Http.Diagnostics.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.Http.Filters.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.Http.Filters.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.Http.Headers.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.Http.Headers.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.Http.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.Http.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.Syndication.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.Syndication.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.UI.Interop.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.UI.Interop.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.UI.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.UI.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/base.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/base.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.AI.MachineLearning.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.AI.MachineLearning.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.AI.MachineLearning.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.AI.MachineLearning.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.AI.MachineLearning.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.AI.MachineLearning.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.AI.MachineLearning.Preview.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.AI.MachineLearning.Preview.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.AI.MachineLearning.Preview.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.AI.MachineLearning.Preview.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.AI.MachineLearning.Preview.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.AI.MachineLearning.Preview.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Activation.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Activation.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Activation.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Activation.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Activation.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Activation.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.AppExtensions.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.AppExtensions.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.AppExtensions.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.AppExtensions.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.AppExtensions.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.AppExtensions.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.AppService.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.AppService.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.AppService.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.AppService.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.AppService.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.AppService.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.AppointmentsProvider.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.AppointmentsProvider.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.AppointmentsProvider.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.AppointmentsProvider.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.AppointmentsProvider.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.AppointmentsProvider.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.DataProvider.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.DataProvider.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.DataProvider.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.DataProvider.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.DataProvider.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.DataProvider.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Background.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Background.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Background.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Background.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Background.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Background.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Background.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Background.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Background.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Background.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Background.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Background.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Provider.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Provider.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Provider.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Provider.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Provider.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Provider.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Chat.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Chat.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Chat.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Chat.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Chat.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Chat.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.CommunicationBlocking.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.CommunicationBlocking.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.CommunicationBlocking.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.CommunicationBlocking.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.CommunicationBlocking.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.CommunicationBlocking.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.DataProvider.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.DataProvider.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.DataProvider.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.DataProvider.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.DataProvider.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.DataProvider.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.Provider.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.Provider.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.Provider.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.Provider.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.Provider.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.Provider.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ConversationalAgent.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ConversationalAgent.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ConversationalAgent.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ConversationalAgent.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ConversationalAgent.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ConversationalAgent.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Core.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Core.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Core.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Core.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Core.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Core.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.Core.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.Core.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.Core.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.Core.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.Core.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.Core.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.ShareTarget.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.ShareTarget.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.ShareTarget.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.ShareTarget.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.ShareTarget.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.ShareTarget.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Email.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Email.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Email.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Email.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Email.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Email.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Email.DataProvider.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Email.DataProvider.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Email.DataProvider.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Email.DataProvider.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Email.DataProvider.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Email.DataProvider.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.Foreground.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.Foreground.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.Foreground.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.Foreground.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.Foreground.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.Foreground.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Holographic.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Holographic.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Holographic.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Holographic.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Holographic.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Holographic.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.LockScreen.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.LockScreen.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.LockScreen.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.LockScreen.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.LockScreen.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.LockScreen.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.Provider.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.Provider.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.Provider.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.Provider.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.Provider.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.Provider.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Holographic.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Holographic.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Holographic.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Holographic.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Holographic.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Holographic.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.InkWorkspace.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.InkWorkspace.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.InkWorkspace.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.InkWorkspace.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.InkWorkspace.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.InkWorkspace.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Notes.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Notes.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Notes.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Notes.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Notes.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Notes.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Core.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Core.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Core.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Core.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Core.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Core.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Management.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Management.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Management.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Management.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Management.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Management.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Search.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Search.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Search.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Search.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Search.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Search.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Search.Core.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Search.Core.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Search.Core.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Search.Core.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Search.Core.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Search.Core.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.Provider.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.Provider.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.Provider.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.Provider.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.Provider.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.Provider.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.LicenseManagement.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.LicenseManagement.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.LicenseManagement.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.LicenseManagement.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.LicenseManagement.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.LicenseManagement.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.InstallControl.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.InstallControl.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.InstallControl.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.InstallControl.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.InstallControl.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.InstallControl.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.Core.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.Core.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.Core.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.Core.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.Core.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.Core.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.Provider.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.Provider.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.Provider.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.Provider.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.Provider.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.Provider.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.SystemAccess.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.SystemAccess.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.SystemAccess.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.SystemAccess.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.SystemAccess.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.SystemAccess.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.DataProvider.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.DataProvider.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.DataProvider.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.DataProvider.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.DataProvider.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.DataProvider.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.VoiceCommands.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.VoiceCommands.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.VoiceCommands.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.VoiceCommands.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.VoiceCommands.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.VoiceCommands.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.System.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.System.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.System.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.System.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.System.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.System.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Html.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Html.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Html.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Html.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Html.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Html.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Json.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Json.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Json.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Json.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Json.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Json.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Pdf.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Pdf.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Pdf.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Pdf.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Pdf.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Pdf.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Text.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Text.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Text.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Text.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Text.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Text.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Xml.Dom.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Xml.Dom.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Xml.Dom.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Xml.Dom.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Xml.Dom.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Xml.Dom.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Xml.Xsl.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Xml.Xsl.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Xml.Xsl.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Xml.Xsl.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Xml.Xsl.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Xml.Xsl.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Adc.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Adc.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Adc.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Adc.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Adc.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Adc.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Adc.Provider.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Adc.Provider.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Adc.Provider.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Adc.Provider.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Adc.Provider.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Adc.Provider.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.AllJoyn.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.AllJoyn.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.AllJoyn.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.AllJoyn.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.AllJoyn.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.AllJoyn.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Background.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Background.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Background.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Background.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Background.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Background.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Advertisement.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Advertisement.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Advertisement.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Advertisement.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Advertisement.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Advertisement.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Background.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Background.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Background.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Background.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Background.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Background.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.GenericAttributeProfile.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.GenericAttributeProfile.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.GenericAttributeProfile.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.GenericAttributeProfile.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.GenericAttributeProfile.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.GenericAttributeProfile.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Rfcomm.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Rfcomm.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Rfcomm.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Rfcomm.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Rfcomm.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Rfcomm.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Custom.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Custom.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Custom.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Custom.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Custom.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Custom.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Display.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Display.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Display.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Display.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Display.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Display.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Display.Core.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Display.Core.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Display.Core.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Display.Core.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Display.Core.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Display.Core.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Enumeration.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Enumeration.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Enumeration.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Enumeration.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Enumeration.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Enumeration.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Enumeration.Pnp.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Enumeration.Pnp.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Enumeration.Pnp.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Enumeration.Pnp.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Enumeration.Pnp.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Enumeration.Pnp.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Geolocation.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Geolocation.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Geolocation.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Geolocation.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Geolocation.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Geolocation.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Geolocation.Geofencing.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Geolocation.Geofencing.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Geolocation.Geofencing.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Geolocation.Geofencing.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Geolocation.Geofencing.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Geolocation.Geofencing.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Gpio.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Gpio.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Gpio.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Gpio.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Gpio.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Gpio.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Gpio.Provider.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Gpio.Provider.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Gpio.Provider.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Gpio.Provider.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Gpio.Provider.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Gpio.Provider.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Haptics.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Haptics.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Haptics.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Haptics.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Haptics.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Haptics.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.HumanInterfaceDevice.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.HumanInterfaceDevice.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.HumanInterfaceDevice.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.HumanInterfaceDevice.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.HumanInterfaceDevice.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.HumanInterfaceDevice.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.I2c.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.I2c.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.I2c.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.I2c.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.I2c.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.I2c.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.I2c.Provider.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.I2c.Provider.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.I2c.Provider.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.I2c.Provider.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.I2c.Provider.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.I2c.Provider.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Input.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Input.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Input.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Input.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Input.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Input.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Input.Preview.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Input.Preview.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Input.Preview.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Input.Preview.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Input.Preview.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Input.Preview.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Lights.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Lights.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Lights.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Lights.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Lights.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Lights.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Lights.Effects.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Lights.Effects.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Lights.Effects.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Lights.Effects.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Lights.Effects.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Lights.Effects.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Midi.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Midi.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Midi.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Midi.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Midi.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Midi.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Perception.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Perception.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Perception.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Perception.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Perception.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Perception.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Perception.Provider.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Perception.Provider.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Perception.Provider.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Perception.Provider.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Perception.Provider.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Perception.Provider.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.PointOfService.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.PointOfService.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.PointOfService.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.PointOfService.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.PointOfService.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.PointOfService.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.PointOfService.Provider.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.PointOfService.Provider.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.PointOfService.Provider.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.PointOfService.Provider.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.PointOfService.Provider.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.PointOfService.Provider.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Portable.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Portable.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Portable.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Portable.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Portable.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Portable.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Power.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Power.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Power.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Power.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Power.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Power.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Printers.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Printers.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Printers.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Printers.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Printers.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Printers.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Printers.Extensions.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Printers.Extensions.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Printers.Extensions.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Printers.Extensions.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Printers.Extensions.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Printers.Extensions.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Pwm.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Pwm.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Pwm.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Pwm.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Pwm.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Pwm.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Pwm.Provider.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Pwm.Provider.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Pwm.Provider.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Pwm.Provider.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Pwm.Provider.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Pwm.Provider.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Radios.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Radios.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Radios.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Radios.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Radios.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Radios.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Scanners.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Scanners.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Scanners.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Scanners.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Scanners.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Scanners.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sensors.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sensors.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sensors.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sensors.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sensors.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sensors.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sensors.Custom.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sensors.Custom.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sensors.Custom.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sensors.Custom.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sensors.Custom.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sensors.Custom.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.SerialCommunication.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.SerialCommunication.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.SerialCommunication.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.SerialCommunication.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.SerialCommunication.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.SerialCommunication.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.SmartCards.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.SmartCards.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.SmartCards.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.SmartCards.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.SmartCards.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.SmartCards.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sms.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sms.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sms.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sms.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sms.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sms.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Spi.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Spi.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Spi.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Spi.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Spi.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Spi.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Spi.Provider.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Spi.Provider.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Spi.Provider.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Spi.Provider.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Spi.Provider.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Spi.Provider.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Usb.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Usb.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Usb.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Usb.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Usb.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Usb.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFi.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFi.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFi.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFi.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFi.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFi.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.Services.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.Services.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.Services.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.Services.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.Services.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.Services.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Embedded.DeviceLockdown.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Embedded.DeviceLockdown.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Embedded.DeviceLockdown.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Embedded.DeviceLockdown.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Embedded.DeviceLockdown.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Embedded.DeviceLockdown.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Collections.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Collections.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Collections.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Collections.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Collections.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Collections.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Diagnostics.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Diagnostics.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Diagnostics.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Diagnostics.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Diagnostics.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Diagnostics.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Metadata.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Metadata.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Metadata.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Metadata.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Metadata.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Metadata.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Numerics.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Numerics.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Numerics.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Numerics.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Numerics.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Numerics.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.Custom.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.Custom.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.Custom.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.Custom.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.Custom.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.Custom.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.ForceFeedback.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.ForceFeedback.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.ForceFeedback.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.ForceFeedback.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.ForceFeedback.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.ForceFeedback.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.Preview.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.Preview.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.Preview.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.Preview.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.Preview.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.Preview.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Preview.GamesEnumeration.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Preview.GamesEnumeration.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Preview.GamesEnumeration.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Preview.GamesEnumeration.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Preview.GamesEnumeration.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Preview.GamesEnumeration.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.UI.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.UI.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.UI.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.UI.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.UI.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.UI.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.XboxLive.Storage.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.XboxLive.Storage.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.XboxLive.Storage.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.XboxLive.Storage.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.XboxLive.Storage.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.XboxLive.Storage.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.Collation.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.Collation.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.Collation.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.Collation.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.Collation.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.Collation.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.DateTimeFormatting.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.DateTimeFormatting.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.DateTimeFormatting.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.DateTimeFormatting.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.DateTimeFormatting.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.DateTimeFormatting.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.Fonts.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.Fonts.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.Fonts.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.Fonts.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.Fonts.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.Fonts.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.NumberFormatting.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.NumberFormatting.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.NumberFormatting.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.NumberFormatting.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.NumberFormatting.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.NumberFormatting.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.PhoneNumberFormatting.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.PhoneNumberFormatting.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.PhoneNumberFormatting.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.PhoneNumberFormatting.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.PhoneNumberFormatting.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.PhoneNumberFormatting.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Capture.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Capture.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Capture.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Capture.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Capture.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Capture.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.DirectX.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.DirectX.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.DirectX.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.DirectX.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.DirectX.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.DirectX.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.DirectX.Direct3D11.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.DirectX.Direct3D11.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.DirectX.Direct3D11.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.DirectX.Direct3D11.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.DirectX.Direct3D11.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.DirectX.Direct3D11.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Display.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Display.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Display.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Display.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Display.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Display.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Display.Core.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Display.Core.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Display.Core.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Display.Core.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Display.Core.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Display.Core.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Effects.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Effects.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Effects.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Effects.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Effects.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Effects.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Holographic.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Holographic.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Holographic.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Holographic.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Holographic.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Holographic.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Imaging.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Imaging.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Imaging.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Imaging.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Imaging.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Imaging.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.OptionDetails.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.OptionDetails.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.OptionDetails.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.OptionDetails.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.OptionDetails.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.OptionDetails.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.PrintTicket.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.PrintTicket.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.PrintTicket.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.PrintTicket.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.PrintTicket.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.PrintTicket.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.Workflow.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.Workflow.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.Workflow.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.Workflow.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.Workflow.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.Workflow.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing3D.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing3D.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing3D.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing3D.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing3D.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing3D.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Core.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Core.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Core.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Core.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Core.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Core.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Deployment.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Deployment.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Deployment.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Deployment.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Deployment.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Deployment.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Deployment.Preview.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Deployment.Preview.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Deployment.Preview.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Deployment.Preview.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Deployment.Preview.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Deployment.Preview.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Policies.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Policies.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Policies.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Policies.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Policies.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Policies.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Update.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Update.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Update.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Update.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Update.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Update.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Workplace.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Workplace.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Workplace.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Workplace.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Workplace.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Workplace.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.AppBroadcasting.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.AppBroadcasting.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.AppBroadcasting.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.AppBroadcasting.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.AppBroadcasting.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.AppBroadcasting.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.AppRecording.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.AppRecording.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.AppRecording.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.AppRecording.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.AppRecording.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.AppRecording.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Audio.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Audio.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Audio.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Audio.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Audio.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Audio.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.Core.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.Core.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.Core.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.Core.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.Core.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.Core.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.Frames.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.Frames.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.Frames.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.Frames.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.Frames.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.Frames.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Casting.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Casting.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Casting.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Casting.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Casting.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Casting.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.ClosedCaptioning.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.ClosedCaptioning.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.ClosedCaptioning.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.ClosedCaptioning.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.ClosedCaptioning.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.ClosedCaptioning.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.ContentRestrictions.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.ContentRestrictions.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.ContentRestrictions.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.ContentRestrictions.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.ContentRestrictions.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.ContentRestrictions.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Control.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Control.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Control.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Control.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Control.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Control.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Core.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Core.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Core.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Core.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Core.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Core.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Core.Preview.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Core.Preview.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Core.Preview.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Core.Preview.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Core.Preview.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Core.Preview.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Devices.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Devices.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Devices.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Devices.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Devices.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Devices.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Devices.Core.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Devices.Core.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Devices.Core.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Devices.Core.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Devices.Core.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Devices.Core.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.DialProtocol.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.DialProtocol.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.DialProtocol.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.DialProtocol.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.DialProtocol.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.DialProtocol.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Editing.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Editing.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Editing.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Editing.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Editing.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Editing.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Effects.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Effects.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Effects.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Effects.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Effects.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Effects.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.FaceAnalysis.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.FaceAnalysis.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.FaceAnalysis.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.FaceAnalysis.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.FaceAnalysis.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.FaceAnalysis.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Import.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Import.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Import.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Import.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Import.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Import.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.MediaProperties.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.MediaProperties.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.MediaProperties.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.MediaProperties.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.MediaProperties.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.MediaProperties.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Miracast.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Miracast.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Miracast.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Miracast.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Miracast.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Miracast.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Ocr.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Ocr.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Ocr.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Ocr.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Ocr.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Ocr.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.PlayTo.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.PlayTo.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.PlayTo.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.PlayTo.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.PlayTo.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.PlayTo.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Playback.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Playback.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Playback.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Playback.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Playback.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Playback.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Playlists.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Playlists.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Playlists.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Playlists.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Playlists.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Playlists.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Protection.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Protection.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Protection.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Protection.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Protection.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Protection.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Protection.PlayReady.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Protection.PlayReady.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Protection.PlayReady.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Protection.PlayReady.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Protection.PlayReady.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Protection.PlayReady.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Render.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Render.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Render.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Render.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Render.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Render.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.SpeechRecognition.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.SpeechRecognition.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.SpeechRecognition.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.SpeechRecognition.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.SpeechRecognition.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.SpeechRecognition.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.SpeechSynthesis.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.SpeechSynthesis.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.SpeechSynthesis.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.SpeechSynthesis.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.SpeechSynthesis.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.SpeechSynthesis.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Streaming.Adaptive.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Streaming.Adaptive.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Streaming.Adaptive.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Streaming.Adaptive.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Streaming.Adaptive.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Streaming.Adaptive.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Transcoding.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Transcoding.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Transcoding.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Transcoding.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Transcoding.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Transcoding.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.BackgroundTransfer.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.BackgroundTransfer.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.BackgroundTransfer.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.BackgroundTransfer.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.BackgroundTransfer.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.BackgroundTransfer.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Connectivity.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Connectivity.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Connectivity.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Connectivity.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Connectivity.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Connectivity.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.NetworkOperators.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.NetworkOperators.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.NetworkOperators.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.NetworkOperators.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.NetworkOperators.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.NetworkOperators.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Proximity.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Proximity.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Proximity.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Proximity.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Proximity.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Proximity.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.PushNotifications.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.PushNotifications.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.PushNotifications.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.PushNotifications.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.PushNotifications.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.PushNotifications.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.ServiceDiscovery.Dnssd.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.ServiceDiscovery.Dnssd.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.ServiceDiscovery.Dnssd.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.ServiceDiscovery.Dnssd.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.ServiceDiscovery.Dnssd.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.ServiceDiscovery.Dnssd.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Sockets.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Sockets.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Sockets.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Sockets.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Sockets.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Sockets.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Vpn.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Vpn.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Vpn.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Vpn.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Vpn.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Vpn.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.XboxLive.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.XboxLive.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.XboxLive.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.XboxLive.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.XboxLive.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.XboxLive.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Automation.Core.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Automation.Core.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Automation.Core.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Automation.Core.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Automation.Core.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Automation.Core.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.People.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.People.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.People.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.People.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.People.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.People.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.Preview.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.Preview.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.Preview.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.Preview.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.Preview.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.Preview.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.Surfaces.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.Surfaces.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.Surfaces.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.Surfaces.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.Surfaces.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.Surfaces.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.ApplicationModel.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.ApplicationModel.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.ApplicationModel.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.ApplicationModel.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.ApplicationModel.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.ApplicationModel.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Devices.Notification.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Devices.Notification.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Devices.Notification.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Devices.Notification.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Devices.Notification.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Devices.Notification.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Devices.Power.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Devices.Power.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Devices.Power.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Devices.Power.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Devices.Power.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Devices.Power.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Management.Deployment.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Management.Deployment.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Management.Deployment.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Management.Deployment.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Management.Deployment.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Management.Deployment.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Media.Devices.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Media.Devices.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Media.Devices.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Media.Devices.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Media.Devices.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Media.Devices.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Notification.Management.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Notification.Management.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Notification.Management.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Notification.Management.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Notification.Management.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Notification.Management.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.Provisioning.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.Provisioning.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.Provisioning.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.Provisioning.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.Provisioning.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.Provisioning.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Speech.Recognition.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Speech.Recognition.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Speech.Recognition.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Speech.Recognition.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Speech.Recognition.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Speech.Recognition.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.StartScreen.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.StartScreen.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.StartScreen.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.StartScreen.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.StartScreen.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.StartScreen.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.Power.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.Power.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.Power.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.Power.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.Power.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.Power.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.Profile.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.Profile.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.Profile.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.Profile.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.Profile.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.Profile.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.UserProfile.GameServices.Core.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.UserProfile.GameServices.Core.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.UserProfile.GameServices.Core.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.UserProfile.GameServices.Core.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.UserProfile.GameServices.Core.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.UserProfile.GameServices.Core.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.UI.Input.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.UI.Input.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.UI.Input.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.UI.Input.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.UI.Input.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.UI.Input.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Core.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Core.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Core.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Core.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Core.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Core.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Provider.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Provider.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Provider.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Provider.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Provider.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Provider.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.OnlineId.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.OnlineId.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.OnlineId.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.OnlineId.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.OnlineId.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.OnlineId.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Core.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Core.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Core.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Core.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Core.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Core.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Provider.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Provider.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Provider.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Provider.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Provider.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Provider.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authorization.AppCapabilityAccess.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authorization.AppCapabilityAccess.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authorization.AppCapabilityAccess.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authorization.AppCapabilityAccess.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authorization.AppCapabilityAccess.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authorization.AppCapabilityAccess.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Credentials.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Credentials.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Credentials.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Credentials.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Credentials.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Credentials.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Credentials.UI.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Credentials.UI.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Credentials.UI.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Credentials.UI.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Credentials.UI.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Credentials.UI.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.Certificates.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.Certificates.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.Certificates.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.Certificates.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.Certificates.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.Certificates.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.Core.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.Core.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.Core.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.Core.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.Core.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.Core.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.DataProtection.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.DataProtection.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.DataProtection.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.DataProtection.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.DataProtection.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.DataProtection.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.DataProtection.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.DataProtection.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.DataProtection.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.DataProtection.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.DataProtection.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.DataProtection.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.EnterpriseData.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.EnterpriseData.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.EnterpriseData.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.EnterpriseData.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.EnterpriseData.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.EnterpriseData.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.ExchangeActiveSyncProvisioning.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.ExchangeActiveSyncProvisioning.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.ExchangeActiveSyncProvisioning.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.ExchangeActiveSyncProvisioning.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.ExchangeActiveSyncProvisioning.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.ExchangeActiveSyncProvisioning.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Isolation.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Isolation.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Isolation.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Isolation.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Isolation.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Isolation.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Cortana.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Cortana.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Cortana.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Cortana.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Cortana.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Cortana.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.Guidance.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.Guidance.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.Guidance.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.Guidance.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.Guidance.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.Guidance.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.LocalSearch.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.LocalSearch.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.LocalSearch.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.LocalSearch.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.LocalSearch.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.LocalSearch.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.OfflineMaps.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.OfflineMaps.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.OfflineMaps.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.OfflineMaps.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.OfflineMaps.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.OfflineMaps.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Store.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Store.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Store.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Store.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Store.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Store.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.TargetedContent.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.TargetedContent.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.TargetedContent.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.TargetedContent.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.TargetedContent.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.TargetedContent.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.AccessCache.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.AccessCache.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.AccessCache.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.AccessCache.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.AccessCache.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.AccessCache.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.BulkAccess.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.BulkAccess.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.BulkAccess.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.BulkAccess.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.BulkAccess.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.BulkAccess.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Compression.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Compression.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Compression.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Compression.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Compression.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Compression.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.FileProperties.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.FileProperties.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.FileProperties.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.FileProperties.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.FileProperties.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.FileProperties.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Pickers.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Pickers.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Pickers.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Pickers.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Pickers.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Pickers.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Pickers.Provider.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Pickers.Provider.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Pickers.Provider.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Pickers.Provider.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Pickers.Provider.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Pickers.Provider.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Provider.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Provider.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Provider.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Provider.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Provider.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Provider.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Search.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Search.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Search.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Search.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Search.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Search.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Streams.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Streams.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Streams.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Streams.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Streams.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Streams.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.DevicePortal.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.DevicePortal.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.DevicePortal.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.DevicePortal.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.DevicePortal.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.DevicePortal.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.Telemetry.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.Telemetry.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.Telemetry.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.Telemetry.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.Telemetry.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.Telemetry.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.TraceReporting.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.TraceReporting.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.TraceReporting.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.TraceReporting.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.TraceReporting.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.TraceReporting.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Display.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Display.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Display.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Display.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Display.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Display.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Implementation.FileExplorer.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Implementation.FileExplorer.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Implementation.FileExplorer.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Implementation.FileExplorer.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Implementation.FileExplorer.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Implementation.FileExplorer.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Inventory.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Inventory.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Inventory.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Inventory.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Inventory.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Inventory.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Power.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Power.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Power.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Power.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Power.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Power.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Power.Diagnostics.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Power.Diagnostics.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Power.Diagnostics.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Power.Diagnostics.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Power.Diagnostics.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Power.Diagnostics.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Preview.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Preview.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Preview.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Preview.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Preview.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Preview.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Profile.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Profile.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Profile.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Profile.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Profile.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Profile.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Profile.SystemManufacturers.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Profile.SystemManufacturers.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Profile.SystemManufacturers.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Profile.SystemManufacturers.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Profile.SystemManufacturers.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Profile.SystemManufacturers.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.RemoteDesktop.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.RemoteDesktop.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.RemoteDesktop.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.RemoteDesktop.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.RemoteDesktop.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.RemoteDesktop.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.RemoteSystems.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.RemoteSystems.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.RemoteSystems.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.RemoteSystems.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.RemoteSystems.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.RemoteSystems.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Threading.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Threading.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Threading.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Threading.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Threading.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Threading.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Threading.Core.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Threading.Core.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Threading.Core.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Threading.Core.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Threading.Core.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Threading.Core.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Update.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Update.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Update.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Update.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Update.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Update.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.UserProfile.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.UserProfile.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.UserProfile.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.UserProfile.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.UserProfile.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.UserProfile.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Accessibility.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Accessibility.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Accessibility.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Accessibility.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Accessibility.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Accessibility.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ApplicationSettings.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ApplicationSettings.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ApplicationSettings.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ApplicationSettings.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ApplicationSettings.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ApplicationSettings.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Core.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Core.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Core.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Core.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Core.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Core.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Desktop.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Desktop.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Desktop.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Desktop.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Desktop.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Desktop.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Diagnostics.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Diagnostics.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Diagnostics.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Diagnostics.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Diagnostics.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Diagnostics.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Effects.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Effects.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Effects.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Effects.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Effects.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Effects.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Interactions.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Interactions.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Interactions.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Interactions.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Interactions.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Interactions.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Scenes.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Scenes.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Scenes.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Scenes.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Scenes.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Scenes.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.AnimationMetrics.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.AnimationMetrics.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.AnimationMetrics.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.AnimationMetrics.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.AnimationMetrics.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.AnimationMetrics.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.Preview.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.Preview.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.Preview.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.Preview.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.Preview.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.Preview.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.Preview.Communications.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.Preview.Communications.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.Preview.Communications.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.Preview.Communications.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.Preview.Communications.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.Preview.Communications.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Core.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Core.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Core.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Core.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Core.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Core.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Analysis.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Analysis.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Analysis.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Analysis.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Analysis.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Analysis.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Core.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Core.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Core.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Core.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Core.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Core.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Preview.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Preview.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Preview.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Preview.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Preview.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Preview.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Preview.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Preview.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Preview.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Preview.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Preview.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Preview.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Preview.Injection.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Preview.Injection.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Preview.Injection.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Preview.Injection.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Preview.Injection.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Preview.Injection.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Spatial.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Spatial.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Spatial.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Spatial.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Spatial.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Spatial.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Notifications.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Notifications.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Notifications.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Notifications.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Notifications.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Notifications.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Notifications.Management.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Notifications.Management.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Notifications.Management.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Notifications.Management.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Notifications.Management.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Notifications.Management.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Popups.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Popups.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Popups.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Popups.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Popups.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Popups.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Shell.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Shell.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Shell.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Shell.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Shell.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Shell.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.StartScreen.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.StartScreen.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.StartScreen.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.StartScreen.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.StartScreen.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.StartScreen.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Text.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Text.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Text.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Text.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Text.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Text.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Text.Core.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Text.Core.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Text.Core.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Text.Core.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Text.Core.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Text.Core.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.UIAutomation.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.UIAutomation.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.UIAutomation.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.UIAutomation.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.UIAutomation.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.UIAutomation.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.UIAutomation.Core.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.UIAutomation.Core.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.UIAutomation.Core.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.UIAutomation.Core.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.UIAutomation.Core.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.UIAutomation.Core.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ViewManagement.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ViewManagement.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ViewManagement.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ViewManagement.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ViewManagement.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ViewManagement.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ViewManagement.Core.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ViewManagement.Core.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ViewManagement.Core.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ViewManagement.Core.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ViewManagement.Core.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ViewManagement.Core.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WebUI.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WebUI.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WebUI.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WebUI.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WebUI.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WebUI.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WebUI.Core.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WebUI.Core.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WebUI.Core.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WebUI.Core.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WebUI.Core.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WebUI.Core.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WindowManagement.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WindowManagement.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WindowManagement.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WindowManagement.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WindowManagement.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WindowManagement.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WindowManagement.Preview.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WindowManagement.Preview.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WindowManagement.Preview.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WindowManagement.Preview.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WindowManagement.Preview.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WindowManagement.Preview.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Peers.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Peers.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Peers.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Peers.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Peers.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Peers.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Provider.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Provider.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Provider.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Provider.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Provider.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Provider.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Text.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Text.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Text.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Text.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Text.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Text.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Maps.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Maps.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Maps.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Maps.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Maps.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Maps.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Primitives.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Primitives.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Primitives.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Primitives.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Primitives.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Primitives.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Core.Direct.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Core.Direct.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Core.Direct.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Core.Direct.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Core.Direct.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Core.Direct.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Data.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Data.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Data.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Data.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Data.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Data.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Documents.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Documents.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Documents.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Documents.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Documents.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Documents.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Hosting.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Hosting.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Hosting.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Hosting.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Hosting.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Hosting.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Input.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Input.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Input.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Input.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Input.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Input.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Interop.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Interop.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Interop.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Interop.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Interop.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Interop.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Markup.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Markup.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Markup.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Markup.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Markup.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Markup.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Animation.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Animation.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Animation.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Animation.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Animation.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Animation.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Imaging.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Imaging.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Imaging.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Imaging.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Imaging.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Imaging.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Media3D.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Media3D.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Media3D.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Media3D.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Media3D.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Media3D.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Navigation.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Navigation.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Navigation.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Navigation.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Navigation.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Navigation.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Printing.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Printing.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Printing.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Printing.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Printing.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Printing.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Resources.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Resources.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Resources.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Resources.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Resources.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Resources.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Shapes.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Shapes.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Shapes.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Shapes.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Shapes.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Shapes.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.AtomPub.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.AtomPub.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.AtomPub.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.AtomPub.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.AtomPub.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.AtomPub.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Diagnostics.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Diagnostics.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Diagnostics.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Diagnostics.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Diagnostics.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Diagnostics.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Filters.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Filters.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Filters.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Filters.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Filters.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Filters.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Headers.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Headers.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Headers.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Headers.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Headers.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Headers.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Syndication.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Syndication.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Syndication.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Syndication.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Syndication.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Syndication.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.UI.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.UI.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.UI.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.UI.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.UI.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.UI.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.UI.Interop.0.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.UI.Interop.0.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.UI.Interop.1.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.UI.Interop.1.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.UI.Interop.2.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.UI.Interop.2.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/winrt.ixx (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/winrt.ixx)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/input_file.h50
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/input_file_test.cc152
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/listenable_future.h41
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/log_message.cc74
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/log_message.h45
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/mutex.h72
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/mutex_test.cc108
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/output_file.h47
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/output_file_test.cc90
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/platform.cc177
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/runner.h42
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/scheduled_executor.cc149
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/scheduled_executor.h65
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/scheduled_executor_test.cc174
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/server_sync.h90
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/settable_future.h51
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/submittable_executor.cc65
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/submittable_executor.h55
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/submittable_executor_test.cc240
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/system_clock.cc43
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/test_data.h (renamed from chromium/third_party/nearby/src/cpp/platform/impl/windows/test_data.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/test_utils.cc61
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/test_utils.h43
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/thread_pool.cc531
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/thread_pool.h106
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/utils.cc127
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/utils.h65
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/utils_test.cc31
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/webrtc.h78
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/wifi.h98
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/wifi_lan.h348
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/wifi_lan_medium.cc487
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/wifi_lan_server_socket.cc180
-rw-r--r--chromium/third_party/nearby/src/internal/platform/implementation/windows/wifi_lan_socket.cc142
-rw-r--r--chromium/third_party/nearby/src/internal/platform/input_stream.cc44
-rw-r--r--chromium/third_party/nearby/src/internal/platform/input_stream.h46
-rw-r--r--chromium/third_party/nearby/src/internal/platform/listeners.h (renamed from chromium/third_party/nearby/src/cpp/platform/base/listeners.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/lockable.h (renamed from chromium/third_party/nearby/src/cpp/platform/public/lockable.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/logging.h88
-rw-r--r--chromium/third_party/nearby/src/internal/platform/logging2.h20
-rw-r--r--chromium/third_party/nearby/src/internal/platform/logging_test.cc53
-rw-r--r--chromium/third_party/nearby/src/internal/platform/medium_environment.cc678
-rw-r--r--chromium/third_party/nearby/src/internal/platform/medium_environment.h325
-rw-r--r--chromium/third_party/nearby/src/internal/platform/monitored_runnable.cc59
-rw-r--r--chromium/third_party/nearby/src/internal/platform/monitored_runnable.h48
-rw-r--r--chromium/third_party/nearby/src/internal/platform/multi_thread_executor.h43
-rw-r--r--chromium/third_party/nearby/src/internal/platform/multi_thread_executor_test.cc138
-rw-r--r--chromium/third_party/nearby/src/internal/platform/mutex.h78
-rw-r--r--chromium/third_party/nearby/src/internal/platform/mutex_lock.h45
-rw-r--r--chromium/third_party/nearby/src/internal/platform/mutex_test.cc117
-rw-r--r--chromium/third_party/nearby/src/internal/platform/nsd_service_info.cc23
-rw-r--r--chromium/third_party/nearby/src/internal/platform/nsd_service_info.h (renamed from chromium/third_party/nearby/src/cpp/platform/base/nsd_service_info.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/output_stream.h39
-rw-r--r--chromium/third_party/nearby/src/internal/platform/payload_id.h (renamed from chromium/third_party/nearby/src/cpp/platform/base/payload_id.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/pending_job_registry.cc91
-rw-r--r--chromium/third_party/nearby/src/internal/platform/pending_job_registry.h55
-rw-r--r--chromium/third_party/nearby/src/internal/platform/pipe.cc35
-rw-r--r--chromium/third_party/nearby/src/internal/platform/pipe.h36
-rw-r--r--chromium/third_party/nearby/src/internal/platform/pipe_test.cc346
-rw-r--r--chromium/third_party/nearby/src/internal/platform/prng.cc59
-rw-r--r--chromium/third_party/nearby/src/internal/platform/prng.h (renamed from chromium/third_party/nearby/src/cpp/platform/base/prng.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/prng_test.cc87
-rw-r--r--chromium/third_party/nearby/src/internal/platform/runnable.h (renamed from chromium/third_party/nearby/src/cpp/platform/base/runnable.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/scheduled_executor.h109
-rw-r--r--chromium/third_party/nearby/src/internal/platform/scheduled_executor_test.cc206
-rw-r--r--chromium/third_party/nearby/src/internal/platform/settable_future.h128
-rw-r--r--chromium/third_party/nearby/src/internal/platform/single_thread_executor.h41
-rw-r--r--chromium/third_party/nearby/src/internal/platform/single_thread_executor_test.cc139
-rw-r--r--chromium/third_party/nearby/src/internal/platform/socket.h39
-rw-r--r--chromium/third_party/nearby/src/internal/platform/submittable_executor.h130
-rw-r--r--chromium/third_party/nearby/src/internal/platform/system_clock.h20
-rw-r--r--chromium/third_party/nearby/src/internal/platform/thread_check_callable.h46
-rw-r--r--chromium/third_party/nearby/src/internal/platform/thread_check_nocompile.cc83
-rw-r--r--chromium/third_party/nearby/src/internal/platform/thread_check_nocompile_test.py26
-rw-r--r--chromium/third_party/nearby/src/internal/platform/thread_check_runnable.h47
-rw-r--r--chromium/third_party/nearby/src/internal/platform/types.h (renamed from chromium/third_party/nearby/src/cpp/platform/base/types.h)0
-rw-r--r--chromium/third_party/nearby/src/internal/platform/webrtc.h99
-rw-r--r--chromium/third_party/nearby/src/internal/platform/wifi_lan.cc146
-rw-r--r--chromium/third_party/nearby/src/internal/platform/wifi_lan.h210
-rw-r--r--chromium/third_party/nearby/src/internal/platform/wifi_lan_test.cc391
-rw-r--r--chromium/third_party/nearby/src/internal/proto/analytics/BUILD62
-rw-r--r--chromium/third_party/nearby/src/internal/proto/analytics/connections_log.proto445
-rw-r--r--chromium/third_party/nearby/src/internal/proto/analytics/connections_log_test.cc126
-rw-r--r--chromium/third_party/nearby/src/proto/BUILD35
-rw-r--r--chromium/third_party/nearby/src/proto/analytics/BUILD67
-rw-r--r--chromium/third_party/nearby/src/proto/analytics/connections_log.proto435
-rw-r--r--chromium/third_party/nearby/src/proto/analytics/connections_log_test.cc126
-rw-r--r--chromium/third_party/nearby/src/proto/connections/BUILD70
-rw-r--r--chromium/third_party/nearby/src/proto/connections/offline_wire_formats.proto364
-rw-r--r--chromium/third_party/nearby/src/proto/connections_enums.proto21
-rw-r--r--chromium/third_party/nearby/src/proto/errorcode/BUILD28
-rw-r--r--chromium/third_party/nearby/src/proto/errorcode/error_code_enums.proto1
-rw-r--r--chromium/third_party/nearby/src/proto/mediums/BUILD54
-rw-r--r--chromium/third_party/nearby/src/proto/sharing_enums.proto4
-rw-r--r--chromium/third_party/nearby/src/windows/BUILD57
-rw-r--r--chromium/third_party/nearby/src/windows/core_adapter.cc158
-rw-r--r--chromium/third_party/nearby/src/windows/core_adapter.h265
-rw-r--r--chromium/third_party/nearby/src/windows/dart/core_adapter_dart.cc456
-rw-r--r--chromium/third_party/nearby/src/windows/dart/core_adapter_dart.h174
2284 files changed, 71859 insertions, 62658 deletions
diff --git a/chromium/third_party/nearby/BUILD.gn b/chromium/third_party/nearby/BUILD.gn
index 0c3cc31afda..0ba8944687b 100644
--- a/chromium/third_party/nearby/BUILD.gn
+++ b/chromium/third_party/nearby/BUILD.gn
@@ -1,10 +1,8 @@
# Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
-
import("//build/util/process_version.gni")
import("//third_party/protobuf/proto_library.gni")
-
if (is_chromeos_device) {
import("//build/config/chromeos/rules.gni")
}
@@ -12,27 +10,37 @@ if (is_chromeos_device) {
# Nearby Config
config("nearby_include_config") {
include_dirs = [
- "src/cpp",
+ "src",
"$root_gen_dir/third_party/nearby",
# For WebRTC APIs.
"//third_party",
+
+ # For bloom filter.
+ "//third_party/smhasher",
]
}
+config("nearby_defines") {
+ defines = [ "NEARBY_CHROMIUM=1" ]
+}
+
###############################################################################
-# src/cpp/analytics
+# src/internal/analytics
###############################################################################
-# src/cpp/analytics
+# src/internal/analytics
source_set("analytics") {
- public_configs = [ ":nearby_include_config" ]
- sources = [ "src/cpp/analytics/analytics_recorder.cc" ]
- public = [ "src/cpp/analytics/analytics_recorder.h" ]
+ public_configs = [
+ ":nearby_include_config",
+ ":nearby_defines",
+ ]
+ sources = [ "src/internal/analytics/analytics_recorder.cc" ]
+ public = [ "src/internal/analytics/analytics_recorder.h" ]
public_deps = [
":connections_enums_proto",
+ ":connections_event_logger",
":connections_log_proto",
- ":core_event_logger",
- ":core_types",
+ ":connections_types",
":error_code_enums_proto",
":platform_base",
":platform_base_error_code_recorder",
@@ -45,18 +53,21 @@ source_set("analytics") {
}
###############################################################################
-# src/cpp/core
+# src/connections
###############################################################################
-# src/cpp/core
-source_set("core") {
- public_configs = [ ":nearby_include_config" ]
- sources = [ "src/cpp/core/core.cc" ]
- public = [ "src/cpp/core/core.h" ]
+# src/connections
+source_set("connections") {
+ public_configs = [
+ ":nearby_include_config",
+ ":nearby_defines",
+ ]
+ sources = [ "src/connections/core.cc" ]
+ public = [ "src/connections/core.h" ]
public_deps = [
":connections_enums_proto",
- ":core_event_logger",
- ":core_internal",
- ":core_types",
+ ":connections_event_logger",
+ ":connections_implementation",
+ ":connections_types",
":platform_public_comm",
":platform_public_logging",
":platform_public_types",
@@ -65,21 +76,30 @@ source_set("core") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
}
-
-source_set("core_types") {
- public_configs = [ ":nearby_include_config" ]
+source_set("connections_types") {
+ public_configs = [
+ ":nearby_include_config",
+ ":nearby_defines",
+ ]
sources = [
- "src/cpp/core/options.cc",
- "src/cpp/core/payload.cc",
- "src/cpp/core/strategy.cc",
+ "src/connections/advertising_options.cc",
+ "src/connections/connection_options.cc",
+ "src/connections/discovery_options.cc",
+ "src/connections/payload.cc",
+ "src/connections/strategy.cc",
]
public = [
- "src/cpp/core/listeners.h",
- "src/cpp/core/options.h",
- "src/cpp/core/params.h",
- "src/cpp/core/payload.h",
- "src/cpp/core/status.h",
- "src/cpp/core/strategy.h",
+ "src/connections/advertising_options.h",
+ "src/connections/connection_options.h",
+ "src/connections/discovery_options.h",
+ "src/connections/listeners.h",
+ "src/connections/options_base.h",
+ "src/connections/out_of_band_connection_metadata.h",
+ "src/connections/params.h",
+ "src/connections/payload.h",
+ "src/connections/power_level.h",
+ "src/connections/status.h",
+ "src/connections/strategy.h",
]
public_deps = [
":connections_enums_proto",
@@ -92,93 +112,98 @@ source_set("core_types") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
}
-
-source_set("core_event_logger") {
- public_configs = [ ":nearby_include_config" ]
- public = [ "src/cpp/core/event_logger.h" ]
+source_set("connections_event_logger") {
+ public_configs = [
+ ":nearby_include_config",
+ ":nearby_defines",
+ ]
+ public = [ "src/connections/event_logger.h" ]
public_deps = [ ":connections_log_proto" ]
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
}
-# src/cpp/core/internal
-source_set("core_internal") {
- public_configs = [ ":nearby_include_config" ]
+# src/connections/implementation
+source_set("connections_implementation") {
+ public_configs = [
+ ":nearby_include_config",
+ ":nearby_defines",
+ ]
sources = [
- "src/cpp/core/internal/base_endpoint_channel.cc",
- "src/cpp/core/internal/base_pcp_handler.cc",
- "src/cpp/core/internal/ble_advertisement.cc",
- "src/cpp/core/internal/ble_endpoint_channel.cc",
- "src/cpp/core/internal/bluetooth_bwu_handler.cc",
- "src/cpp/core/internal/bluetooth_device_name.cc",
- "src/cpp/core/internal/bluetooth_endpoint_channel.cc",
- "src/cpp/core/internal/bwu_manager.cc",
- "src/cpp/core/internal/client_proxy.cc",
- "src/cpp/core/internal/encryption_runner.cc",
- "src/cpp/core/internal/endpoint_channel_manager.cc",
- "src/cpp/core/internal/endpoint_manager.cc",
- "src/cpp/core/internal/injected_bluetooth_device_store.cc",
- "src/cpp/core/internal/internal_payload.cc",
- "src/cpp/core/internal/internal_payload_factory.cc",
- "src/cpp/core/internal/offline_frames.cc",
- "src/cpp/core/internal/offline_frames_validator.cc",
- "src/cpp/core/internal/offline_service_controller.cc",
- "src/cpp/core/internal/p2p_cluster_pcp_handler.cc",
- "src/cpp/core/internal/p2p_point_to_point_pcp_handler.cc",
- "src/cpp/core/internal/p2p_star_pcp_handler.cc",
- "src/cpp/core/internal/payload_manager.cc",
- "src/cpp/core/internal/pcp_manager.cc",
- "src/cpp/core/internal/service_controller_router.cc",
- "src/cpp/core/internal/webrtc_bwu_handler.cc",
- "src/cpp/core/internal/webrtc_endpoint_channel.cc",
- "src/cpp/core/internal/wifi_lan_bwu_handler.cc",
- "src/cpp/core/internal/wifi_lan_endpoint_channel.cc",
- "src/cpp/core/internal/wifi_lan_service_info.cc",
+ "src/connections/implementation/base_endpoint_channel.cc",
+ "src/connections/implementation/base_pcp_handler.cc",
+ "src/connections/implementation/ble_advertisement.cc",
+ "src/connections/implementation/ble_endpoint_channel.cc",
+ "src/connections/implementation/bluetooth_bwu_handler.cc",
+ "src/connections/implementation/bluetooth_device_name.cc",
+ "src/connections/implementation/bluetooth_endpoint_channel.cc",
+ "src/connections/implementation/bwu_manager.cc",
+ "src/connections/implementation/client_proxy.cc",
+ "src/connections/implementation/encryption_runner.cc",
+ "src/connections/implementation/endpoint_channel_manager.cc",
+ "src/connections/implementation/endpoint_manager.cc",
+ "src/connections/implementation/injected_bluetooth_device_store.cc",
+ "src/connections/implementation/internal_payload.cc",
+ "src/connections/implementation/internal_payload_factory.cc",
+ "src/connections/implementation/offline_frames.cc",
+ "src/connections/implementation/offline_frames_validator.cc",
+ "src/connections/implementation/offline_service_controller.cc",
+ "src/connections/implementation/p2p_cluster_pcp_handler.cc",
+ "src/connections/implementation/p2p_point_to_point_pcp_handler.cc",
+ "src/connections/implementation/p2p_star_pcp_handler.cc",
+ "src/connections/implementation/payload_manager.cc",
+ "src/connections/implementation/pcp_manager.cc",
+ "src/connections/implementation/service_controller_router.cc",
+ "src/connections/implementation/webrtc_bwu_handler.cc",
+ "src/connections/implementation/webrtc_endpoint_channel.cc",
+ "src/connections/implementation/wifi_lan_bwu_handler.cc",
+ "src/connections/implementation/wifi_lan_endpoint_channel.cc",
+ "src/connections/implementation/wifi_lan_service_info.cc",
]
public = [
- "src/cpp/core/internal/base_bwu_handler.h",
- "src/cpp/core/internal/base_endpoint_channel.h",
- "src/cpp/core/internal/base_pcp_handler.h",
- "src/cpp/core/internal/ble_advertisement.h",
- "src/cpp/core/internal/ble_endpoint_channel.h",
- "src/cpp/core/internal/bluetooth_bwu_handler.h",
- "src/cpp/core/internal/bluetooth_device_name.h",
- "src/cpp/core/internal/bluetooth_endpoint_channel.h",
- "src/cpp/core/internal/bwu_handler.h",
- "src/cpp/core/internal/bwu_manager.h",
- "src/cpp/core/internal/client_proxy.h",
- "src/cpp/core/internal/encryption_runner.h",
- "src/cpp/core/internal/endpoint_channel.h",
- "src/cpp/core/internal/endpoint_channel_manager.h",
- "src/cpp/core/internal/endpoint_manager.h",
- "src/cpp/core/internal/injected_bluetooth_device_store.h",
- "src/cpp/core/internal/internal_payload.h",
- "src/cpp/core/internal/internal_payload_factory.h",
- "src/cpp/core/internal/message_lite.h",
- "src/cpp/core/internal/offline_frames.h",
- "src/cpp/core/internal/offline_frames_validator.h",
- "src/cpp/core/internal/offline_service_controller.h",
- "src/cpp/core/internal/p2p_cluster_pcp_handler.h",
- "src/cpp/core/internal/p2p_point_to_point_pcp_handler.h",
- "src/cpp/core/internal/p2p_star_pcp_handler.h",
- "src/cpp/core/internal/payload_manager.h",
- "src/cpp/core/internal/pcp.h",
- "src/cpp/core/internal/pcp_handler.h",
- "src/cpp/core/internal/pcp_manager.h",
- "src/cpp/core/internal/service_controller.h",
- "src/cpp/core/internal/service_controller_router.h",
- "src/cpp/core/internal/webrtc_bwu_handler.h",
- "src/cpp/core/internal/webrtc_endpoint_channel.h",
- "src/cpp/core/internal/wifi_lan_bwu_handler.h",
- "src/cpp/core/internal/wifi_lan_endpoint_channel.h",
- "src/cpp/core/internal/wifi_lan_service_info.h",
+ "src/connections/implementation/base_bwu_handler.h",
+ "src/connections/implementation/base_endpoint_channel.h",
+ "src/connections/implementation/base_pcp_handler.h",
+ "src/connections/implementation/ble_advertisement.h",
+ "src/connections/implementation/ble_endpoint_channel.h",
+ "src/connections/implementation/bluetooth_bwu_handler.h",
+ "src/connections/implementation/bluetooth_device_name.h",
+ "src/connections/implementation/bluetooth_endpoint_channel.h",
+ "src/connections/implementation/bwu_handler.h",
+ "src/connections/implementation/bwu_manager.h",
+ "src/connections/implementation/client_proxy.h",
+ "src/connections/implementation/encryption_runner.h",
+ "src/connections/implementation/endpoint_channel.h",
+ "src/connections/implementation/endpoint_channel_manager.h",
+ "src/connections/implementation/endpoint_manager.h",
+ "src/connections/implementation/injected_bluetooth_device_store.h",
+ "src/connections/implementation/internal_payload.h",
+ "src/connections/implementation/internal_payload_factory.h",
+ "src/connections/implementation/message_lite.h",
+ "src/connections/implementation/offline_frames.h",
+ "src/connections/implementation/offline_frames_validator.h",
+ "src/connections/implementation/offline_service_controller.h",
+ "src/connections/implementation/p2p_cluster_pcp_handler.h",
+ "src/connections/implementation/p2p_point_to_point_pcp_handler.h",
+ "src/connections/implementation/p2p_star_pcp_handler.h",
+ "src/connections/implementation/payload_manager.h",
+ "src/connections/implementation/pcp.h",
+ "src/connections/implementation/pcp_handler.h",
+ "src/connections/implementation/pcp_manager.h",
+ "src/connections/implementation/service_controller.h",
+ "src/connections/implementation/service_controller_router.h",
+ "src/connections/implementation/webrtc_bwu_handler.h",
+ "src/connections/implementation/webrtc_endpoint_channel.h",
+ "src/connections/implementation/wifi_lan_bwu_handler.h",
+ "src/connections/implementation/wifi_lan_endpoint_channel.h",
+ "src/connections/implementation/wifi_lan_service_info.h",
]
public_deps = [
":analytics",
":connections_enums_proto",
- ":core_internal_mediums",
- ":core_internal_mediums_webrtc",
- ":core_types",
+ ":connections_implementation_mediums",
+ ":connections_implementation_mediums_webrtc",
+ ":connections_types",
":offline_wire_formats_proto",
":platform_base",
":platform_base_cancellation_flag",
@@ -194,53 +219,58 @@ source_set("core_internal") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
}
-
-source_set("core_internal_test") {
+source_set("connections_test_util") {
testonly = true
- public_configs = [ ":nearby_include_config" ]
- public = [ "src/cpp/core/internal/mock_service_controller_router.h" ]
+ public_configs = [
+ ":nearby_include_config",
+ ":nearby_defines",
+ ]
+ public = [ "src/connections/implementation/mock_service_controller_router.h" ]
deps = [
- ":core_internal",
+ ":connections_implementation",
"//third_party/googletest:gmock",
]
}
-# src/cpp/core/internal/mediums
-source_set("core_internal_mediums") {
- public_configs = [ ":nearby_include_config" ]
+# src/connections/implementation/mediums
+source_set("connections_implementation_mediums") {
+ public_configs = [
+ ":nearby_include_config",
+ ":nearby_defines",
+ ]
sources = [
- "src/cpp/core/internal/mediums/ble.cc",
- "src/cpp/core/internal/mediums/ble_v2/advertisement_read_result.cc",
- "src/cpp/core/internal/mediums/ble_v2/ble_advertisement.cc",
- "src/cpp/core/internal/mediums/ble_v2/ble_advertisement_header.cc",
- "src/cpp/core/internal/mediums/ble_v2/ble_packet.cc",
- "src/cpp/core/internal/mediums/bloom_filter.cc",
- "src/cpp/core/internal/mediums/bluetooth_classic.cc",
- "src/cpp/core/internal/mediums/bluetooth_radio.cc",
- "src/cpp/core/internal/mediums/mediums.cc",
- "src/cpp/core/internal/mediums/uuid.cc",
- "src/cpp/core/internal/mediums/webrtc.cc",
- "src/cpp/core/internal/mediums/wifi_lan.cc",
+ "src/connections/implementation/mediums/ble.cc",
+ "src/connections/implementation/mediums/ble_v2/advertisement_read_result.cc",
+ "src/connections/implementation/mediums/ble_v2/ble_advertisement.cc",
+ "src/connections/implementation/mediums/ble_v2/ble_advertisement_header.cc",
+ "src/connections/implementation/mediums/ble_v2/ble_packet.cc",
+ "src/connections/implementation/mediums/ble_v2/bloom_filter.cc",
+ "src/connections/implementation/mediums/bluetooth_classic.cc",
+ "src/connections/implementation/mediums/bluetooth_radio.cc",
+ "src/connections/implementation/mediums/mediums.cc",
+ "src/connections/implementation/mediums/uuid.cc",
+ "src/connections/implementation/mediums/webrtc.cc",
+ "src/connections/implementation/mediums/wifi_lan.cc",
]
public = [
- "src/cpp/core/internal/mediums/ble.h",
- "src/cpp/core/internal/mediums/ble_v2/advertisement_read_result.h",
- "src/cpp/core/internal/mediums/ble_v2/ble_advertisement.h",
- "src/cpp/core/internal/mediums/ble_v2/ble_advertisement_header.h",
- "src/cpp/core/internal/mediums/ble_v2/ble_packet.h",
- "src/cpp/core/internal/mediums/ble_v2/ble_peripheral.h",
- "src/cpp/core/internal/mediums/bloom_filter.h",
- "src/cpp/core/internal/mediums/bluetooth_classic.h",
- "src/cpp/core/internal/mediums/bluetooth_radio.h",
- "src/cpp/core/internal/mediums/lost_entity_tracker.h",
- "src/cpp/core/internal/mediums/mediums.h",
- "src/cpp/core/internal/mediums/uuid.h",
- "src/cpp/core/internal/mediums/webrtc.h",
- "src/cpp/core/internal/mediums/wifi_lan.h",
+ "src/connections/implementation/mediums/ble.h",
+ "src/connections/implementation/mediums/ble_v2/advertisement_read_result.h",
+ "src/connections/implementation/mediums/ble_v2/ble_advertisement.h",
+ "src/connections/implementation/mediums/ble_v2/ble_advertisement_header.h",
+ "src/connections/implementation/mediums/ble_v2/ble_packet.h",
+ "src/connections/implementation/mediums/ble_v2/ble_peripheral.h",
+ "src/connections/implementation/mediums/ble_v2/bloom_filter.h",
+ "src/connections/implementation/mediums/bluetooth_classic.h",
+ "src/connections/implementation/mediums/bluetooth_radio.h",
+ "src/connections/implementation/mediums/lost_entity_tracker.h",
+ "src/connections/implementation/mediums/mediums.h",
+ "src/connections/implementation/mediums/uuid.h",
+ "src/connections/implementation/mediums/webrtc.h",
+ "src/connections/implementation/mediums/wifi_lan.h",
]
public_deps = [
- ":core_internal_mediums_webrtc",
- ":core_types",
+ ":connections_implementation_mediums_webrtc",
+ ":connections_types",
":platform_base",
":platform_base_cancellation_flag",
":platform_base_util",
@@ -255,29 +285,68 @@ source_set("core_internal_mediums") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
}
-
-source_set("core_internal_mediums_webrtc") {
- public_configs = [ ":nearby_include_config" ]
+source_set("connections_implementation_mediums_utils") {
+ public_configs = [
+ ":nearby_include_config",
+ ":nearby_defines",
+ ]
sources = [
- "src/cpp/core/internal/mediums/utils.cc",
- "src/cpp/core/internal/mediums/webrtc/connection_flow.cc",
- "src/cpp/core/internal/mediums/webrtc/signaling_frames.cc",
- "src/cpp/core/internal/mediums/webrtc/webrtc_socket.cc",
- "src/cpp/core/internal/mediums/webrtc_peer_id.cc",
+ "src/connections/implementation/mediums/utils.cc",
+ "src/connections/implementation/mediums/webrtc_peer_id.cc",
]
public = [
- "src/cpp/core/internal/mediums/utils.h",
- "src/cpp/core/internal/mediums/webrtc/connection_flow.h",
- "src/cpp/core/internal/mediums/webrtc/data_channel_listener.h",
- "src/cpp/core/internal/mediums/webrtc/local_ice_candidate_listener.h",
- "src/cpp/core/internal/mediums/webrtc/session_description_wrapper.h",
- "src/cpp/core/internal/mediums/webrtc/signaling_frames.h",
- "src/cpp/core/internal/mediums/webrtc/webrtc_socket.h",
- "src/cpp/core/internal/mediums/webrtc_peer_id.h",
- "src/cpp/core/internal/mediums/webrtc_socket_wrapper.h",
+ "//third_party/abseil-cpp:absl",
+ "src/connections/implementation/mediums/utils.h",
+ "src/connections/implementation/mediums/webrtc_peer_id.h",
+ "src/connections/implementation/mediums/webrtc_socket.h",
]
public_deps = [
- ":core_types",
+ ":connections_implementation_mediums_webrtc_data_types",
+ ":offline_wire_formats_proto",
+ ":platform_base",
+ ":platform_public_types",
+ ]
+ configs -= [ "//build/config/compiler:chromium_code" ]
+ configs += [ "//build/config/compiler:no_chromium_code" ]
+}
+source_set("connections_implementation_mediums_webrtc_data_types") {
+ public_configs = [
+ ":nearby_include_config",
+ ":nearby_defines",
+ ]
+ sources =
+ [ "src/connections/implementation/mediums/webrtc/webrtc_socket_impl.cc" ]
+ public =
+ [ "src/connections/implementation/mediums/webrtc/webrtc_socket_impl.h" ]
+ public_deps = [
+ ":connections_types",
+ ":platform_base",
+ ":platform_public_types",
+ "//third_party/webrtc_overrides:webrtc_component",
+ ]
+ configs -= [ "//build/config/compiler:chromium_code" ]
+ configs += [ "//build/config/compiler:no_chromium_code" ]
+}
+source_set("connections_implementation_mediums_webrtc") {
+ public_configs = [
+ ":nearby_include_config",
+ ":nearby_defines",
+ ]
+ sources = [
+ "src/connections/implementation/mediums/webrtc/connection_flow.cc",
+ "src/connections/implementation/mediums/webrtc/signaling_frames.cc",
+ ]
+ public = [
+ "src/connections/implementation/mediums/webrtc/connection_flow.h",
+ "src/connections/implementation/mediums/webrtc/data_channel_listener.h",
+ "src/connections/implementation/mediums/webrtc/local_ice_candidate_listener.h",
+ "src/connections/implementation/mediums/webrtc/session_description_wrapper.h",
+ "src/connections/implementation/mediums/webrtc/signaling_frames.h",
+ ]
+ public_deps = [
+ ":connections_implementation_mediums_utils",
+ ":connections_implementation_mediums_webrtc_data_types",
+ ":connections_types",
":platform_base",
":platform_public_comm",
":platform_public_logging",
@@ -291,20 +360,23 @@ source_set("core_internal_mediums_webrtc") {
}
###############################################################################
-# src/cpp/platform
+# src/internal/platform
###############################################################################
-# src/cpp/platform/api
+# src/internal/platform/implementation
source_set("platform_api_comm") {
- public_configs = [ ":nearby_include_config" ]
+ public_configs = [
+ ":nearby_include_config",
+ ":nearby_defines",
+ ]
sources = [
- "src/cpp/platform/api/ble.h",
- "src/cpp/platform/api/ble_v2.h",
- "src/cpp/platform/api/bluetooth_adapter.h",
- "src/cpp/platform/api/bluetooth_classic.h",
- "src/cpp/platform/api/server_sync.h",
- "src/cpp/platform/api/webrtc.h",
- "src/cpp/platform/api/wifi.h",
- "src/cpp/platform/api/wifi_lan.h",
+ "src/internal/platform/implementation/ble.h",
+ "src/internal/platform/implementation/ble_v2.h",
+ "src/internal/platform/implementation/bluetooth_adapter.h",
+ "src/internal/platform/implementation/bluetooth_classic.h",
+ "src/internal/platform/implementation/server_sync.h",
+ "src/internal/platform/implementation/webrtc.h",
+ "src/internal/platform/implementation/wifi.h",
+ "src/internal/platform/implementation/wifi_lan.h",
]
public_deps = [
":offline_wire_formats_proto",
@@ -316,27 +388,29 @@ source_set("platform_api_comm") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
}
-
source_set("platform_api_types") {
- public_configs = [ ":nearby_include_config" ]
+ public_configs = [
+ ":nearby_include_config",
+ ":nearby_defines",
+ ]
sources = [
- "src/cpp/platform/api/atomic_boolean.h",
- "src/cpp/platform/api/atomic_reference.h",
- "src/cpp/platform/api/cancelable.h",
- "src/cpp/platform/api/condition_variable.h",
- "src/cpp/platform/api/count_down_latch.h",
- "src/cpp/platform/api/crypto.h",
- "src/cpp/platform/api/executor.h",
- "src/cpp/platform/api/future.h",
- "src/cpp/platform/api/input_file.h",
- "src/cpp/platform/api/listenable_future.h",
- "src/cpp/platform/api/log_message.h",
- "src/cpp/platform/api/mutex.h",
- "src/cpp/platform/api/output_file.h",
- "src/cpp/platform/api/scheduled_executor.h",
- "src/cpp/platform/api/settable_future.h",
- "src/cpp/platform/api/submittable_executor.h",
- "src/cpp/platform/api/system_clock.h",
+ "src/internal/platform/implementation/atomic_boolean.h",
+ "src/internal/platform/implementation/atomic_reference.h",
+ "src/internal/platform/implementation/cancelable.h",
+ "src/internal/platform/implementation/condition_variable.h",
+ "src/internal/platform/implementation/count_down_latch.h",
+ "src/internal/platform/implementation/crypto.h",
+ "src/internal/platform/implementation/executor.h",
+ "src/internal/platform/implementation/future.h",
+ "src/internal/platform/implementation/input_file.h",
+ "src/internal/platform/implementation/listenable_future.h",
+ "src/internal/platform/implementation/log_message.h",
+ "src/internal/platform/implementation/mutex.h",
+ "src/internal/platform/implementation/output_file.h",
+ "src/internal/platform/implementation/scheduled_executor.h",
+ "src/internal/platform/implementation/settable_future.h",
+ "src/internal/platform/implementation/submittable_executor.h",
+ "src/internal/platform/implementation/system_clock.h",
]
public_deps = [
":platform_base",
@@ -345,10 +419,12 @@ source_set("platform_api_types") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
}
-
source_set("platform_api_platform") {
- public_configs = [ ":nearby_include_config" ]
- public = [ "src/cpp/platform/api/platform.h" ]
+ public_configs = [
+ ":nearby_include_config",
+ ":nearby_defines",
+ ]
+ public = [ "src/internal/platform/implementation/platform.h" ]
public_deps = [
":platform_api_comm",
":platform_api_types",
@@ -359,44 +435,49 @@ source_set("platform_api_platform") {
configs += [ "//build/config/compiler:no_chromium_code" ]
}
-# src/cpp/platform/base
+# src/internal/platform
source_set("platform_base") {
- public_configs = [ ":nearby_include_config" ]
+ public_configs = [
+ ":nearby_include_config",
+ ":nearby_defines",
+ ]
sources = [
- "src/cpp/platform/base/base64_utils.cc",
- "src/cpp/platform/base/bluetooth_utils.cc",
- "src/cpp/platform/base/input_stream.cc",
- "src/cpp/platform/base/nsd_service_info.cc",
- "src/cpp/platform/base/prng.cc",
+ "src/internal/platform/base64_utils.cc",
+ "src/internal/platform/bluetooth_utils.cc",
+ "src/internal/platform/input_stream.cc",
+ "src/internal/platform/nsd_service_info.cc",
+ "src/internal/platform/prng.cc",
]
public = [
- "src/cpp/platform/base/base64_utils.h",
- "src/cpp/platform/base/bluetooth_utils.h",
- "src/cpp/platform/base/byte_array.h",
- "src/cpp/platform/base/callable.h",
- "src/cpp/platform/base/exception.h",
- "src/cpp/platform/base/feature_flags.h",
- "src/cpp/platform/base/input_stream.h",
- "src/cpp/platform/base/listeners.h",
- "src/cpp/platform/base/nsd_service_info.h",
- "src/cpp/platform/base/output_stream.h",
- "src/cpp/platform/base/payload_id.h",
- "src/cpp/platform/base/prng.h",
- "src/cpp/platform/base/runnable.h",
- "src/cpp/platform/base/socket.h",
- "src/cpp/platform/base/types.h",
+ "src/internal/platform/base64_utils.h",
+ "src/internal/platform/bluetooth_utils.h",
+ "src/internal/platform/byte_array.h",
+ "src/internal/platform/callable.h",
+ "src/internal/platform/exception.h",
+ "src/internal/platform/feature_flags.h",
+ "src/internal/platform/input_stream.h",
+ "src/internal/platform/listeners.h",
+ "src/internal/platform/nsd_service_info.h",
+ "src/internal/platform/output_stream.h",
+ "src/internal/platform/payload_id.h",
+ "src/internal/platform/prng.h",
+ "src/internal/platform/runnable.h",
+ "src/internal/platform/socket.h",
+ "src/internal/platform/types.h",
]
public_deps = [ "//third_party/abseil-cpp:absl" ]
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
}
-
source_set("platform_base_error_code_recorder") {
- public_configs = [ ":nearby_include_config" ]
- sources = [ "src/cpp/platform/base/error_code_recorder.cc" ]
+ public_configs = [
+ ":nearby_include_config",
+ ":nearby_defines",
+ ]
+ sources = [ "src/internal/platform/error_code_recorder.cc" ]
public = [
- "src/cpp/platform/base/error_code_params.h",
- "src/cpp/platform/base/error_code_recorder.h",
+ "src/internal/platform/error_code_params.h",
+ "src/internal/platform/error_code_recorder.h",
]
public_deps = [
":connections_enums_proto",
@@ -406,17 +487,19 @@ source_set("platform_base_error_code_recorder") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
}
-
source_set("platform_base_util") {
- public_configs = [ ":nearby_include_config" ]
+ public_configs = [
+ ":nearby_include_config",
+ ":nearby_defines",
+ ]
sources = [
- "src/cpp/platform/base/base_input_stream.cc",
- "src/cpp/platform/base/base_pipe.cc",
+ "src/internal/platform/base_input_stream.cc",
+ "src/internal/platform/base_pipe.cc",
]
public = [
- "src/cpp/platform/base/base_input_stream.h",
- "src/cpp/platform/base/base_mutex_lock.h",
- "src/cpp/platform/base/base_pipe.h",
+ "src/internal/platform/base_input_stream.h",
+ "src/internal/platform/base_mutex_lock.h",
+ "src/internal/platform/base_pipe.h",
]
public_deps = [
":platform_api_types",
@@ -426,10 +509,12 @@ source_set("platform_base_util") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
}
-
source_set("platform_base_logging") {
- public_configs = [ ":nearby_include_config" ]
- public = [ "src/cpp/platform/base/logging.h" ]
+ public_configs = [
+ ":nearby_include_config",
+ ":nearby_defines",
+ ]
+ public = [ "src/internal/platform/logging.h" ]
public_deps = [
":platform_api_platform",
":platform_api_types",
@@ -438,11 +523,13 @@ source_set("platform_base_logging") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
}
-
source_set("platform_base_cancellation_flag") {
- public_configs = [ ":nearby_include_config" ]
- sources = [ "src/cpp/platform/base/cancellation_flag.cc" ]
- public = [ "src/cpp/platform/base/cancellation_flag.h" ]
+ public_configs = [
+ ":nearby_include_config",
+ ":nearby_defines",
+ ]
+ sources = [ "src/internal/platform/cancellation_flag.cc" ]
+ public = [ "src/internal/platform/cancellation_flag.h" ]
public_deps = [
":platform_base",
":platform_base_util",
@@ -452,11 +539,14 @@ source_set("platform_base_cancellation_flag") {
configs += [ "//build/config/compiler:no_chromium_code" ]
}
-# src/cpp/platform/impl/shared
+# src/internal/platform/implementation/shared
source_set("platform_impl_shared_file") {
- public_configs = [ ":nearby_include_config" ]
- sources = [ "src/cpp/platform/impl/shared/file.cc" ]
- public = [ "src/cpp/platform/impl/shared/file.h" ]
+ public_configs = [
+ ":nearby_include_config",
+ ":nearby_defines",
+ ]
+ sources = [ "src/internal/platform/implementation/shared/file.cc" ]
+ public = [ "src/internal/platform/implementation/shared/file.h" ]
public_deps = [
":platform_api_platform",
":platform_public_types",
@@ -466,36 +556,39 @@ source_set("platform_impl_shared_file") {
configs += [ "//build/config/compiler:no_chromium_code" ]
}
-# src/cpp/platform/public
+# src/internal/platform
source_set("platform_public_types") {
- public_configs = [ ":nearby_include_config" ]
+ public_configs = [
+ ":nearby_include_config",
+ ":nearby_defines",
+ ]
sources = [
- "src/cpp/platform/public/monitored_runnable.cc",
- "src/cpp/platform/public/pending_job_registry.cc",
- "src/cpp/platform/public/pipe.cc",
+ "src/internal/platform/monitored_runnable.cc",
+ "src/internal/platform/pending_job_registry.cc",
+ "src/internal/platform/pipe.cc",
]
public = [
- "src/cpp/platform/public/atomic_boolean.h",
- "src/cpp/platform/public/atomic_reference.h",
- "src/cpp/platform/public/cancelable.h",
- "src/cpp/platform/public/cancelable_alarm.h",
- "src/cpp/platform/public/condition_variable.h",
- "src/cpp/platform/public/count_down_latch.h",
- "src/cpp/platform/public/crypto.h",
- "src/cpp/platform/public/file.h",
- "src/cpp/platform/public/future.h",
- "src/cpp/platform/public/logging.h",
- "src/cpp/platform/public/monitored_runnable.h",
- "src/cpp/platform/public/multi_thread_executor.h",
- "src/cpp/platform/public/mutex.h",
- "src/cpp/platform/public/mutex_lock.h",
- "src/cpp/platform/public/pending_job_registry.h",
- "src/cpp/platform/public/pipe.h",
- "src/cpp/platform/public/scheduled_executor.h",
- "src/cpp/platform/public/settable_future.h",
- "src/cpp/platform/public/single_thread_executor.h",
- "src/cpp/platform/public/submittable_executor.h",
- "src/cpp/platform/public/system_clock.h",
+ "src/internal/platform/atomic_boolean.h",
+ "src/internal/platform/atomic_reference.h",
+ "src/internal/platform/cancelable.h",
+ "src/internal/platform/cancelable_alarm.h",
+ "src/internal/platform/condition_variable.h",
+ "src/internal/platform/count_down_latch.h",
+ "src/internal/platform/crypto.h",
+ "src/internal/platform/file.h",
+ "src/internal/platform/future.h",
+ "src/internal/platform/logging.h",
+ "src/internal/platform/monitored_runnable.h",
+ "src/internal/platform/multi_thread_executor.h",
+ "src/internal/platform/mutex.h",
+ "src/internal/platform/mutex_lock.h",
+ "src/internal/platform/pending_job_registry.h",
+ "src/internal/platform/pipe.h",
+ "src/internal/platform/scheduled_executor.h",
+ "src/internal/platform/settable_future.h",
+ "src/internal/platform/single_thread_executor.h",
+ "src/internal/platform/submittable_executor.h",
+ "src/internal/platform/system_clock.h",
]
public_deps = [
":platform_api_platform",
@@ -510,21 +603,23 @@ source_set("platform_public_types") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
}
-
source_set("platform_public_comm") {
- public_configs = [ ":nearby_include_config" ]
+ public_configs = [
+ ":nearby_include_config",
+ ":nearby_defines",
+ ]
sources = [
- "src/cpp/platform/public/ble.cc",
- "src/cpp/platform/public/bluetooth_classic.cc",
- "src/cpp/platform/public/file.cc",
- "src/cpp/platform/public/wifi_lan.cc",
+ "src/internal/platform/ble.cc",
+ "src/internal/platform/bluetooth_classic.cc",
+ "src/internal/platform/file.cc",
+ "src/internal/platform/wifi_lan.cc",
]
public = [
- "src/cpp/platform/public/ble.h",
- "src/cpp/platform/public/bluetooth_adapter.h",
- "src/cpp/platform/public/bluetooth_classic.h",
- "src/cpp/platform/public/webrtc.h",
- "src/cpp/platform/public/wifi_lan.h",
+ "src/internal/platform/ble.h",
+ "src/internal/platform/bluetooth_adapter.h",
+ "src/internal/platform/bluetooth_classic.h",
+ "src/internal/platform/webrtc.h",
+ "src/internal/platform/wifi_lan.h",
]
public_deps = [
":platform_api_comm",
@@ -538,10 +633,12 @@ source_set("platform_public_comm") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
}
-
source_set("platform_public_logging") {
- public_configs = [ ":nearby_include_config" ]
- public = [ "src/cpp/platform/public/logging.h" ]
+ public_configs = [
+ ":nearby_include_config",
+ ":nearby_defines",
+ ]
+ public = [ "src/internal/platform/logging.h" ]
public_deps = [ ":platform_base_logging" ]
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
@@ -557,10 +654,10 @@ proto_library("connections_enums_proto") {
proto_out_dir = "third_party/nearby"
}
-# src/proto/analytics
+# src/internal/proto/analytics
proto_library("connections_log_proto") {
proto_in_dir = "src"
- sources = [ "${proto_in_dir}/proto/analytics/connections_log.proto" ]
+ sources = [ "${proto_in_dir}/internal/proto/analytics/connections_log.proto" ]
proto_out_dir = "third_party/nearby"
proto_deps = [
":connections_enums_proto",
@@ -572,10 +669,10 @@ proto_library("connections_log_proto") {
]
}
-# src/proto/connections
+# src/connections/implementation/proto
proto_library("offline_wire_formats_proto") {
proto_in_dir = "src"
- sources = [ "${proto_in_dir}/proto/connections/offline_wire_formats.proto" ]
+ sources = [ "${proto_in_dir}/connections/implementation/proto/offline_wire_formats.proto" ]
proto_out_dir = "third_party/nearby"
}
@@ -605,7 +702,6 @@ if (is_chromeos_device) {
# and artifacts to GCS.
process_version("nearby_lacros_version_metadata") {
sources = [ "//chrome/VERSION" ]
-
template_file = "metadata.json.in"
output = "$root_out_dir/metadata.json"
process_only = true
diff --git a/chromium/third_party/nearby/OWNERS b/chromium/third_party/nearby/OWNERS
index 84e9ecd23a0..c921117ce38 100644
--- a/chromium/third_party/nearby/OWNERS
+++ b/chromium/third_party/nearby/OWNERS
@@ -1,3 +1,6 @@
hansberry@chromium.org
file://chrome/browser/nearby_sharing/OWNERS
+
+# To ease autorolling.
+per-file README.chromium=*
diff --git a/chromium/third_party/nearby/README.chromium b/chromium/third_party/nearby/README.chromium
index abaff2495f3..ac5ecf374c9 100644
--- a/chromium/third_party/nearby/README.chromium
+++ b/chromium/third_party/nearby/README.chromium
@@ -1,7 +1,7 @@
Name: Nearby Connections Library
Short Name: Nearby
URL: https://github.com/google/nearby-connections
-Version: 8c2dd35eac5092fb74d5a673a564689aee790546
+Version: ae0337db3bac9b104a2b585be7312615bcc66262
License: Apache 2.0
License File: LICENSE
Security Critical: yes
diff --git a/chromium/third_party/nearby/src/CONTRIBUTING.md b/chromium/third_party/nearby/src/CONTRIBUTING.md
index 939e5341e74..73b5c4209d2 100644
--- a/chromium/third_party/nearby/src/CONTRIBUTING.md
+++ b/chromium/third_party/nearby/src/CONTRIBUTING.md
@@ -22,7 +22,11 @@ use GitHub pull requests for this purpose. Consult
[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
information on using pull requests.
+
## Community Guidelines
This project follows [Google's Open Source Community
Guidelines](https://opensource.google.com/conduct/).
+
+## Last Updated
+Jaunary 2022
diff --git a/chromium/third_party/nearby/src/README.md b/chromium/third_party/nearby/src/README.md
index 3d92666a3ff..9322d8a65ad 100644
--- a/chromium/third_party/nearby/src/README.md
+++ b/chromium/third_party/nearby/src/README.md
@@ -1,29 +1,11 @@
-# Nearby Connections Library
+# Nearby C++ Library
-This is not an officially supported Google product.
+The repository contains the Nearby project C++ library code. This is not an
+officially supported Google product.
-**Coathored by:**
-* (Java/C++) Varun Kapoor “reznor”
-* (Java) Maria-Ines Carrera “marianines”
-* (Java) Will Harmon “xlythe”
-* (Java/C++/ObjC) Alex Kang “alexanderkang”
-* (Java/C++) Amanda Lee “ahlee”
-* (C++) Tracy Zhou “tracyzhou”
-* (ObjC) Dan Webb “dwebb”
-* (C++) John Kaczor “johngk”
-* (C++/ObjC) Edwin Wu “edwinwu”
-* (C++) Alexey Polyudov “apolyudov”
-
-**Status:** Implemented in C++
-
-**Design reviewers:** TODO
-
-**Implementation reviewer**: TODO
-
-**Last Updated:** TODO
-
-# Overview
+# About the Nearby Project
+## Near Connection
Nearby Connections is a high level protocol on top of Bluetooth/WiFi that acts
as a medium-agnostic socket. Devices are able to advertise, scan, and connect
with one another over any shared medium (eg. BT <-> BT).
@@ -35,24 +17,22 @@ recombined on the receiving device.
See [Nearby Connections Overview](https://developers.google.com/nearby/connections/overview)
for more information.
-# Checkout, build, test instructions
-## Checkout
-pre-requisites: git
+# Checkout the source tree
```shell
-git clone https://github.com/google/nearby-connections
-cd nearby-connections
+git clone https://github.com/google/nearby
+cd nearby
git submodule update --init --recursive
```
-this is a "source root" directory of the project
-
-## Build
-pre-requisites:
-openssl, cmake, c++ toolchain (c++17-capable)
+# Building Nearby, Unit Testing and Sample Apps
+We support multiple platforms including Linux, iOS & Windows. The ultimate goal
+is to build from source (coming soon!). The offical build system we support is
+[bazel] (https://bazel.build). Before that is accomplished, we provide
+precompiled libraries as stop-gap solutions. See the following pages for
+platform specific instructions.
-TODO
+* [iOS](https://github.com/google/nearby/blob/master/docs/ios_build.md)
-## Running unit tests
-TODO
+**Last Updated:** Feb 2022
diff --git a/chromium/third_party/nearby/src/connections/BUILD b/chromium/third_party/nearby/src/connections/BUILD
new file mode 100644
index 00000000000..9ade787c7ed
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/BUILD
@@ -0,0 +1,121 @@
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+licenses(["notice"])
+
+cc_library(
+ name = "core",
+ srcs = [
+ "core.cc",
+ ],
+ hdrs = [
+ "core.h",
+ ],
+ copts = ["-DCORE_ADAPTER_DLL"],
+ visibility = [
+ "//connections/clients:__subpackages__",
+ "//internal/platform/implementation:__subpackages__",
+ ],
+ deps = [
+ ":core_types",
+ ":event_logger",
+ "//connections/implementation:internal",
+ "//internal/platform:base",
+ "//internal/platform:logging",
+ "//internal/platform:types",
+ "@com_google_absl//absl/strings",
+ "@com_google_absl//absl/time",
+ "@com_google_absl//absl/types:span",
+ ],
+)
+
+cc_library(
+ name = "core_types",
+ srcs = [
+ "advertising_options.cc",
+ "connection_options.cc",
+ "discovery_options.cc",
+ "payload.cc",
+ "strategy.cc",
+ ],
+ hdrs = [
+ "advertising_options.h",
+ "connection_options.h",
+ "discovery_options.h",
+ "listeners.h",
+ "medium_selector.h",
+ "options_base.h",
+ "out_of_band_connection_metadata.h",
+ "params.h",
+ "payload.h",
+ "power_level.h",
+ "status.h",
+ "strategy.h",
+ ],
+ copts = ["-DCORE_ADAPTER_DLL"],
+ visibility = [
+ "//connections:__subpackages__",
+ "//internal/analytics:__subpackages__",
+ "//internal/platform/implementation/ios:__subpackages__",
+ ],
+ deps = [
+ "//internal/platform:base",
+ "//internal/platform:types",
+ "//internal/platform:util",
+ "//proto:connections_enums_cc_proto",
+ "@com_google_absl//absl/strings",
+ "@com_google_absl//absl/types:variant",
+ "@com_google_glog//:glog",
+ ],
+)
+
+cc_library(
+ name = "event_logger",
+ hdrs = [
+ "event_logger.h",
+ ],
+ visibility = [
+ "//internal/analytics:__subpackages__",
+ ],
+ deps = [
+ "//internal/proto/analytics:connections_log_cc_proto",
+ ],
+)
+
+cc_test(
+ name = "core_test",
+ size = "small",
+ srcs = [
+ "core_test.cc",
+ "listeners_test.cc",
+ "payload_test.cc",
+ "status_test.cc",
+ "strategy_test.cc",
+ ],
+ shard_count = 16,
+ deps = [
+ ":core",
+ ":core_types",
+ "//connections/implementation:internal",
+ "//connections/implementation:internal_test",
+ "//internal/platform:base",
+ "//internal/platform:logging",
+ "//internal/platform:types",
+ "//internal/platform/implementation/g3", # build_cleaner: keep
+ "@com_github_protobuf_matchers//protobuf-matchers",
+ "@com_google_absl//absl/strings",
+ "@com_google_absl//absl/time",
+ "@com_google_absl//absl/types:variant",
+ "@com_google_googletest//:gtest_main",
+ ],
+)
diff --git a/chromium/third_party/nearby/src/connections/advertising_options.cc b/chromium/third_party/nearby/src/connections/advertising_options.cc
new file mode 100644
index 00000000000..c630e5fad76
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/advertising_options.cc
@@ -0,0 +1,52 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/advertising_options.h"
+
+#include <string>
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Returns a copy and normalizes allowed mediums:
+// (1) If is_out_of_band_connection is true, verifies that there is only one
+// medium allowed, defaulting to only Bluetooth if unspecified.
+// (2) If no mediums are allowed, allow all mediums.
+AdvertisingOptions AdvertisingOptions::CompatibleOptions() const {
+ AdvertisingOptions result = *this;
+
+ // Out-of-band connections initiate connections via an injected endpoint
+ // rather than through the normal discovery flow. These types of connections
+ // can only be injected via a single medium.
+ if (is_out_of_band_connection) {
+ int num_enabled = result.allowed.Count(true);
+
+ // Default to allow only Bluetooth if no single medium is specified.
+ if (num_enabled != 1) {
+ result.allowed.SetAll(false);
+ result.allowed.bluetooth = true;
+ }
+ return result;
+ }
+
+ // Normal connections (i.e., not out-of-band) connections can specify
+ // multiple mediums. If none are specified, default to allowing all mediums.
+ if (!allowed.Any(true)) result.allowed.SetAll(true);
+ return result;
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/advertising_options.h b/chromium/third_party/nearby/src/connections/advertising_options.h
new file mode 100644
index 00000000000..974dc1ba531
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/advertising_options.h
@@ -0,0 +1,53 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+#ifndef CORE_ADVERTISING_OPTIONS_H_
+#define CORE_ADVERTISING_OPTIONS_H_
+#include <string>
+
+#include "connections/medium_selector.h"
+#include "connections/options_base.h"
+#include "connections/power_level.h"
+#include "connections/strategy.h"
+#include "internal/platform/byte_array.h"
+#include "proto/connections_enums.pb.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Connection Options: used for both Advertising and Discovery.
+// All fields are mutable, to make the type copy-assignable.
+struct AdvertisingOptions : public OptionsBase {
+ bool auto_upgrade_bandwidth;
+ bool enforce_topology_constraints;
+ bool low_power;
+ bool enable_bluetooth_listening;
+ bool enable_webrtc_listening;
+
+ // Whether this is intended to be used in conjunction with InjectEndpoint().
+ bool is_out_of_band_connection = false;
+ std::string fast_advertisement_service_uuid;
+
+ // Returns a copy and normalizes allowed mediums:
+ // (1) If is_out_of_band_connection is true, verifies that there is only one
+ // medium allowed, defaulting to only Bluetooth if unspecified.
+ // (2) If no mediums are allowed, allow all mediums.
+ AdvertisingOptions CompatibleOptions() const;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_ADVERTISING_OPTIONS_H_
diff --git a/chromium/third_party/nearby/src/connections/clients/windows/BUILD b/chromium/third_party/nearby/src/connections/clients/windows/BUILD
new file mode 100644
index 00000000000..79969e6376b
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/clients/windows/BUILD
@@ -0,0 +1,61 @@
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+load("//third_party/msvc:build_windows.bzl", "cc_windows_dll")
+
+licenses(["notice"])
+
+# Build with --config=lexan
+cc_windows_dll(
+ name = "core_adapter",
+ srcs = [
+ "core_adapter.cc",
+ ],
+ hdrs = [
+ "core_adapter.h",
+ ],
+ copts = ["-DCORE_ADAPTER_BUILD_DLL -DCOMPILING_CORE"],
+ defines = ["CORE_ADAPTER_DLL"],
+ tags = ["windows-dll"],
+ deps = [
+ "//third_party/dart_lang/v2:dart_api_dl",
+ "//connections:core",
+ "//internal/platform/implementation/windows",
+ "//third_party/webrtc/files/stable/webrtc/api:create_peerconnection_factory",
+ "@com_google_absl//absl/strings",
+ ],
+)
+
+# Build with --config=lexan
+# TODO(b/203019344) Move this configuration under dart folder and create a BUILD there.
+cc_windows_dll(
+ name = "core_adapter_dart",
+ srcs = [
+ "core_adapter.cc",
+ "dart/core_adapter_dart.cc",
+ ],
+ hdrs = [
+ "core_adapter.h",
+ "dart/core_adapter_dart.h",
+ ],
+ copts = ["-DCORE_ADAPTER_DART_BUILD_DLL -DCORE_ADAPTER_DLL -DCOMPILING_CORE"],
+ defines = ["CORE_ADAPTER_DART_DLL"],
+ tags = ["windows-dll"],
+ deps = [
+ "//third_party/dart_lang/v2:dart_api_dl",
+ "//connections:core",
+ "//internal/platform/implementation/windows",
+ "//third_party/webrtc/files/stable/webrtc/api:create_peerconnection_factory",
+ "@com_google_absl//absl/strings",
+ ],
+)
diff --git a/chromium/third_party/nearby/src/connections/clients/windows/core_adapter.cc b/chromium/third_party/nearby/src/connections/clients/windows/core_adapter.cc
new file mode 100644
index 00000000000..04c024588ed
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/clients/windows/core_adapter.cc
@@ -0,0 +1,153 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+#include "connections/clients/windows/core_adapter.h"
+
+#include "absl/strings/str_format.h"
+#include "connections/core.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace windows {
+
+Core *InitCore(ServiceControllerRouter *router) { return new Core(router); }
+
+void CloseCore(Core *pCore) {
+ if (pCore) {
+ pCore->StopAllEndpoints(
+ {.result_cb = std::function<void(Status)>{[](Status) {}}});
+ delete pCore;
+ }
+}
+
+void StartAdvertising(Core *pCore, const char *service_id,
+ AdvertisingOptions advertising_options,
+ ConnectionRequestInfo info, ResultCallback callback) {
+ if (pCore) {
+ pCore->StartAdvertising(service_id, advertising_options, info, callback);
+ }
+}
+
+void StopAdvertising(Core *pCore, ResultCallback callback) {
+ if (pCore) {
+ pCore->StopAdvertising(callback);
+ }
+}
+
+void StartDiscovery(Core *pCore, const char *service_id,
+ DiscoveryOptions discovery_options,
+ DiscoveryListener listener, ResultCallback callback) {
+ if (pCore) {
+ pCore->StartDiscovery(service_id, discovery_options, listener, callback);
+ }
+}
+
+void StopDiscovery(Core *pCore, ResultCallback callback) {
+ if (pCore) {
+ pCore->StopDiscovery(callback);
+ }
+}
+
+void InjectEndpoint(Core *pCore, char *service_id,
+ OutOfBandConnectionMetadata metadata,
+ ResultCallback callback) {
+ if (pCore) {
+ pCore->InjectEndpoint(service_id, metadata, callback);
+ }
+}
+
+void RequestConnection(Core *pCore, const char *endpoint_id,
+ ConnectionRequestInfo info,
+ ConnectionOptions connection_options,
+ ResultCallback callback) {
+ if (pCore) {
+ pCore->RequestConnection(endpoint_id, info, connection_options, callback);
+ }
+}
+
+void AcceptConnection(Core *pCore, const char *endpoint_id,
+ PayloadListener listener, ResultCallback callback) {
+ if (pCore) {
+ pCore->AcceptConnection(endpoint_id, listener, callback);
+ }
+}
+
+void RejectConnection(Core *pCore, const char *endpoint_id,
+ ResultCallback callback) {
+ if (pCore) {
+ pCore->RejectConnection(endpoint_id, callback);
+ }
+}
+
+void SendPayload(Core *pCore,
+ // todo(jfcarroll) this is being exported, needs to be
+ // refactored to return a plain old c type
+ absl::Span<const std::string> endpoint_ids, Payload payload,
+ ResultCallback callback) {
+ if (pCore) {
+ pCore->SendPayload(endpoint_ids, std::move(payload), callback);
+ }
+}
+
+void CancelPayload(Core *pCore, std::int64_t payload_id,
+ ResultCallback callback) {
+ if (pCore) {
+ pCore->CancelPayload(payload_id, callback);
+ }
+}
+
+void DisconnectFromEndpoint(Core *pCore, char *endpoint_id,
+ ResultCallback callback) {
+ if (pCore) {
+ pCore->DisconnectFromEndpoint(endpoint_id, callback);
+ }
+}
+
+void StopAllEndpoints(Core *pCore, ResultCallback callback) {
+ if (pCore) {
+ pCore->StopAllEndpoints(callback);
+ }
+}
+
+void InitiateBandwidthUpgrade(Core *pCore, char *endpoint_id,
+ ResultCallback callback) {
+ if (pCore) {
+ pCore->InitiateBandwidthUpgrade(endpoint_id, callback);
+ }
+}
+
+const char *GetLocalEndpointId(Core *pCore) {
+ if (pCore) {
+ std::string endpoint_id = pCore->GetLocalEndpointId();
+ char *result = new char[endpoint_id.length() + 1];
+ absl::SNPrintF(result, endpoint_id.length() + 1, "%s", endpoint_id);
+ return result;
+ }
+ return "Null-Core";
+}
+
+ServiceControllerRouter *InitServiceControllerRouter() {
+ return new ServiceControllerRouter();
+}
+
+void CloseServiceControllerRouter(ServiceControllerRouter *pRouter) {
+ if (pRouter) {
+ delete pRouter;
+ }
+}
+
+} // namespace windows
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/clients/windows/core_adapter.h b/chromium/third_party/nearby/src/connections/clients/windows/core_adapter.h
new file mode 100644
index 00000000000..2f7b9f984c9
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/clients/windows/core_adapter.h
@@ -0,0 +1,267 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+#ifndef LOCATION_NEARBY_CONNECTIONS_WINDOWS_CORE_ADAPTER_H_
+#define LOCATION_NEARBY_CONNECTIONS_WINDOWS_CORE_ADAPTER_H_
+
+#include "absl/strings/string_view.h"
+#include "absl/types/span.h"
+
+// todo(jfcarroll) This cannot remain. It exposes stuff the client doesn't need.
+#include "connections/advertising_options.h"
+#include "connections/connection_options.h"
+#include "connections/discovery_options.h"
+#include "connections/implementation/offline_service_controller.h"
+
+#define DLL_EXPORT extern "C" __declspec(dllexport)
+
+namespace location {
+namespace nearby {
+namespace connections {
+class Core;
+class ServiceControllerRouter;
+
+namespace windows {
+
+// Initizlizes a Core instance, providing the ServiceController factory from
+// app side. If no factory is provided, it will initialize a new
+// factory creating OffilineServiceController.
+// Returns the instance handle to c# client.
+DLL_EXPORT connections::Core *__stdcall InitCoreWithServiceControllerFactory(
+ std::function<connections::ServiceController *()> factory = []() {
+ return new connections::OfflineServiceController;
+ });
+
+// Initializes a default Core instance.
+// Returns the instance handle to c# client.
+DLL_EXPORT Core *__stdcall InitCore(ServiceControllerRouter *router);
+
+// Closes the core with stopping all endpoints, then free the memory.
+DLL_EXPORT void __stdcall CloseCore(Core *pCore);
+
+// Starts advertising an endpoint for a local app.
+//
+// service_id - An identifier to advertise your app to other endpoints.
+// This can be an arbitrary string, so long as it uniquely
+// identifies your service. A good default is to use your
+// app's package name.
+// advertising_options - The options for advertising.
+// info - Connection parameters:
+// > name - A human readable name for this endpoint, to appear on
+// other devices.
+// > listener - A callback notified when remote endpoints request a
+// connection to this endpoint.
+// callback - to access the status of the operation when available.
+// Possible status codes include:
+// Status::STATUS_OK if advertising started successfully.
+// Status::STATUS_ALREADY_ADVERTISING if the app is already advertising.
+// Status::STATUS_OUT_OF_ORDER_API_CALL if the app is currently
+// connected to remote endpoints; call StopAllEndpoints first.
+DLL_EXPORT void __stdcall StartAdvertising(
+ Core *pCore, const char *service_id, AdvertisingOptions advertising_options,
+ connections::ConnectionRequestInfo info, ResultCallback callback);
+
+// Stops advertising a local endpoint. Should be called after calling
+// StartAdvertising, as soon as the application no longer needs to advertise
+// itself or goes inactive. Payloads can still be sent to connected
+// endpoints after advertising ends.
+//
+// result_cb - to access the status of the operation when available.
+// Possible status codes include:
+// Status::STATUS_OK if none of the above errors occurred.
+DLL_EXPORT void __stdcall StopAdvertising(Core *pCore, ResultCallback callback);
+
+// Starts discovery for remote endpoints with the specified service ID.
+//
+// service_id - The ID for the service to be discovered, as specified in
+// the corresponding call to StartAdvertising.
+// listener - A callback notified when a remote endpoint is discovered.
+// discovery_options - The options for discovery.
+// result_cb - to access the status of the operation when available.
+// Possible status codes include:
+// Status::STATUS_OK if discovery started successfully.
+// Status::STATUS_ALREADY_DISCOVERING if the app is already
+// discovering the specified service.
+// Status::STATUS_OUT_OF_ORDER_API_CALL if the app is currently
+// connected to remote endpoints; call StopAllEndpoints first.
+DLL_EXPORT void __stdcall StartDiscovery(Core *pCore, const char *service_id,
+ DiscoveryOptions discovery_options,
+ DiscoveryListener listener,
+ ResultCallback callback);
+
+// Stops discovery for remote endpoints, after a previous call to
+// StartDiscovery, when the client no longer needs to discover endpoints or
+// goes inactive. Payloads can still be sent to connected endpoints after
+// discovery ends.
+//
+// result_cb - to access the status of the operation when available.
+// Possible status codes include:
+// Status::STATUS_OK if none of the above errors occurred.
+DLL_EXPORT void __stdcall StopDiscovery(connections::Core *pCore,
+ connections::ResultCallback callback);
+
+// Invokes the discovery callback from a previous call to StartDiscovery()
+// with the given endpoint info. The previous call to StartDiscovery() must
+// have been passed ConnectionOptions with is_out_of_band_connection == true.
+//
+// service_id - The ID for the service to be discovered, as
+// specified in the corresponding call to
+// StartDiscovery().
+// metadata - Metadata used in order to inject the endpoint.
+// result_cb - to access the status of the operation when
+// available.
+// Possible status codes include:
+// Status::kSuccess if endpoint injection was attempted.
+// Status::kError if endpoint_id, endpoint_info, or
+// remote_bluetooth_mac_address are malformed.
+// Status::kOutOfOrderApiCall if the app is not discovering.
+DLL_EXPORT void __stdcall InjectEndpoint(Core *pCore, char *service_id,
+ OutOfBandConnectionMetadata metadata,
+ ResultCallback callback);
+
+// Sends a request to connect to a remote endpoint.
+//
+// endpoint_id - The identifier for the remote endpoint to which a
+// connection request will be sent. Should match the value
+// provided in a call to
+// DiscoveryListener::endpoint_found_cb()
+// info - Connection parameters:
+// > name - A human readable name for the local endpoint, to appear on
+// the remote endpoint.
+// > listener - A callback notified when the remote endpoint sends a
+// response to the connection request.
+// result_cb - to access the status of the operation when available.
+// Possible status codes include:
+// Status::STATUS_OK if the connection request was sent.
+// Status::STATUS_ALREADY_CONNECTED_TO_ENDPOINT if the app already
+// has a connection to the specified endpoint.
+// Status::STATUS_RADIO_ERROR if we failed to connect because of an
+// issue with Bluetooth/WiFi.
+// Status::STATUS_ERROR if we failed to connect for any other reason.
+DLL_EXPORT void __stdcall RequestConnection(
+ Core *pCore, const char *endpoint_id, ConnectionRequestInfo info,
+ ConnectionOptions connection_options, ResultCallback callback);
+
+// Accepts a connection to a remote endpoint. This method must be called
+// before Payloads can be exchanged with the remote endpoint.
+//
+// endpoint_id - The identifier for the remote endpoint. Should match the
+// value provided in a call to
+// ConnectionListener::onConnectionInitiated.
+// listener - A callback for payloads exchanged with the remote endpoint.
+// result_cb - to access the status of the operation when available.
+// Possible status codes include:
+// Status::STATUS_OK if the connection request was accepted.
+// Status::STATUS_ALREADY_CONNECTED_TO_ENDPOINT if the app already.
+// has a connection to the specified endpoint.
+DLL_EXPORT void __stdcall AcceptConnection(Core *pCore, const char *endpoint_id,
+ PayloadListener listener,
+ ResultCallback callback);
+
+// Rejects a connection to a remote endpoint.
+//
+// endpoint_id - The identifier for the remote endpoint. Should match the
+// value provided in a call to
+// ConnectionListener::onConnectionInitiated().
+// result_cb - to access the status of the operation when available.
+// Possible status codes include:
+// Status::STATUS_OK} if the connection request was rejected.
+// Status::STATUS_ALREADY_CONNECTED_TO_ENDPOINT} if the app already
+// has a connection to the specified endpoint.
+DLL_EXPORT void __stdcall RejectConnection(Core *pCore, const char *endpoint_id,
+ ResultCallback callback);
+
+// Sends a Payload to a remote endpoint. Payloads can only be sent to remote
+// endpoints once a notice of connection acceptance has been delivered via
+// ConnectionListener::onConnectionResult().
+//
+// endpoint_ids - Array of remote endpoint identifiers for the to which the
+// payload should be sent.
+// payload - The Payload to be sent.
+// result_cb - to access the status of the operation when available.
+// Possible status codes include:
+// Status::STATUS_OUT_OF_ORDER_API_CALL if the device has not first
+// performed advertisement or discovery (to set the Strategy.)
+// Status::STATUS_ENDPOINT_UNKNOWN if there's no active (or pending)
+// connection to the remote endpoint.
+// Status::STATUS_OK if none of the above errors occurred. Note that this
+// indicates that Nearby Connections will attempt to send the Payload,
+// but not that the send has successfully completed yet. Errors might
+// still occur during transmission (and at different times for
+// different endpoints), and will be delivered via
+// PayloadCallback#onPayloadTransferUpdate.
+DLL_EXPORT void __stdcall SendPayload(
+ Core *pCore, absl::Span<const std::string> endpoint_ids, Payload payload,
+ ResultCallback callback);
+
+// Cancels a Payload currently in-flight to or from remote endpoint(s).
+//
+// payload_id - The identifier for the Payload to be canceled.
+// result_cb - to access the status of the operation when available.
+// Possible status codes include:
+// Status::STATUS_OK if none of the above errors occurred.
+DLL_EXPORT void __stdcall CancelPayload(Core *pCore, int64_t payload_id,
+ ResultCallback callback);
+
+// Disconnects from a remote endpoint. {@link Payload}s can no longer be sent
+// to or received from the endpoint after this method is called.
+//
+// endpoint_id - The identifier for the remote endpoint to disconnect from.
+// result_cb - to access the status of the operation when available.
+// Possible status codes include:
+// Status::STATUS_OK - finished successfully.
+DLL_EXPORT void __stdcall DisconnectFromEndpoint(Core *pCore, char *endpoint_id,
+ ResultCallback callback);
+
+// Disconnects from, and removes all traces of, all connected and/or
+// discovered endpoints. This call is expected to be preceded by a call to
+// StopAdvertising or StartDiscovery as needed. After calling
+// StopAllEndpoints, no further operations with remote endpoints will be
+// possible until a new call to one of StartAdvertising() or StartDiscovery().
+//
+// result_cb - to access the status of the operation when available.
+// Possible status codes include:
+// Status::STATUS_OK - finished successfully.
+DLL_EXPORT void __stdcall StopAllEndpoints(Core *pCore,
+ ResultCallback callback);
+
+// Sends a request to initiate connection bandwidth upgrade.
+//
+// endpoint_id - The identifier for the remote endpoint which will be
+// switching to a higher connection data rate and possibly
+// different wireless protocol. On success, calls
+// ConnectionListener::bandwidth_changed_cb().
+// result_cb - to access the status of the operation when available.
+// Possible status codes include:
+// Status::STATUS_OK - finished successfully.
+DLL_EXPORT void __stdcall InitiateBandwidthUpgrade(Core *pCore,
+ char *endpoint_id,
+ ResultCallback callback);
+
+// Gets the local endpoint generated by Nearby Connections.
+DLL_EXPORT const char *__stdcall GetLocalEndpointId(Core *pCore);
+
+// Initializes a default ServiceControllerRouter instance.
+// Returns the instance handle to c# client.
+DLL_EXPORT ServiceControllerRouter *__stdcall InitServiceControllerRouter();
+
+// Close a ServiceControllerRouter instance.
+DLL_EXPORT void __stdcall CloseServiceControllerRouter(
+ ServiceControllerRouter *pRouter);
+
+} // namespace windows
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // LOCATION_NEARBY_CONNECTIONS_WINDOWS_CORE_ADAPTER_H_
diff --git a/chromium/third_party/nearby/src/connections/clients/windows/dart/core_adapter_dart.cc b/chromium/third_party/nearby/src/connections/clients/windows/dart/core_adapter_dart.cc
new file mode 100644
index 00000000000..9697ed38ab0
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/clients/windows/dart/core_adapter_dart.cc
@@ -0,0 +1,584 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/clients/windows/dart/core_adapter_dart.h"
+
+#include <shlobj.h>
+
+#include <cstdint>
+#include <string>
+
+#include "connections/core.h"
+#include "connections/payload.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/file.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace windows {
+
+Strategy GetStrategy(StrategyDart strategy) {
+ switch (strategy) {
+ case StrategyDart::P2P_CLUSTER:
+ return Strategy::kP2pCluster;
+ case StrategyDart::P2P_POINT_TO_POINT:
+ return Strategy::kP2pPointToPoint;
+ case StrategyDart::P2P_STAR:
+ return Strategy::kP2pStar;
+ }
+ return Strategy::kNone;
+}
+
+ByteArray ConvertBluetoothMacAddress(absl::string_view address) {
+ return ByteArray(address.data());
+}
+
+void SetResultCallback(ResultCallback &callback, Dart_Port &port) {
+ callback.result_cb = [port](Status status) {
+ Dart_CObject dart_object_result_callback;
+ dart_object_result_callback.type = Dart_CObject_kInt64;
+ dart_object_result_callback.value.as_int64 = status.value;
+ const bool result = Dart_PostCObject_DL(port, &dart_object_result_callback);
+ if (!result) {
+ NEARBY_LOG(INFO, "Posting message to port failed.");
+ }
+ };
+}
+
+void PostResult(Dart_Port &result_cb, Status::Value value) {
+ Dart_CObject dart_object_result_callback;
+ dart_object_result_callback.type = Dart_CObject_kInt64;
+ dart_object_result_callback.value.as_int64 = value;
+ const bool result =
+ Dart_PostCObject_DL(result_cb, &dart_object_result_callback);
+ if (!result) {
+ NEARBY_LOG(INFO, "Returning error to port failed.");
+ }
+}
+
+void StartAdvertisingDart(Core *pCore, const char *service_id,
+ ConnectionOptionsDart options_dart,
+ ConnectionRequestInfoDart info_dart,
+ Dart_Port result_cb) {
+ if (!pCore) {
+ PostResult(result_cb, Status::Value::kError);
+ return;
+ }
+
+ AdvertisingOptions advertising_options;
+ advertising_options.strategy = GetStrategy(options_dart.strategy);
+ advertising_options.auto_upgrade_bandwidth =
+ options_dart.auto_upgrade_bandwidth;
+ advertising_options.enforce_topology_constraints =
+ options_dart.enforce_topology_constraints;
+ advertising_options.allowed.bluetooth = options_dart.enable_bluetooth;
+ advertising_options.allowed.ble = options_dart.enable_ble;
+ advertising_options.low_power = options_dart.use_low_power_mode;
+ advertising_options.fast_advertisement_service_uuid =
+ options_dart.discover_fast_advertisements
+ ? "0000FE2C-0000-1000-8000-00805F9B34FB"
+ : "";
+ advertising_options.allowed.wifi_lan = options_dart.enable_wifi_lan;
+ advertising_options.allowed.web_rtc = options_dart.enable_web_rtc;
+
+ ConnectionRequestInfo info;
+ info.endpoint_info = ByteArray(info_dart.endpoint_info);
+ info.listener.initiated_cb =
+ [info_dart](const std::string &endpoint_id,
+ const ConnectionResponseInfo &connection_info) {
+ NEARBY_LOG(INFO, "Advertising initiated: id=%s", endpoint_id.c_str());
+
+ Dart_CObject dart_object_endpoint_id;
+ dart_object_endpoint_id.type = Dart_CObject_kString;
+ dart_object_endpoint_id.value.as_string = (char *)endpoint_id.data();
+
+ Dart_CObject dart_object_endpoint_info;
+ dart_object_endpoint_info.type = Dart_CObject_kString;
+ dart_object_endpoint_info.value.as_string =
+ (char *)connection_info.remote_endpoint_info.data();
+
+ Dart_CObject *elements[2];
+ elements[0] = &dart_object_endpoint_id;
+ elements[1] = &dart_object_endpoint_info;
+
+ Dart_CObject dart_object_initiated;
+ dart_object_initiated.type = Dart_CObject_kArray;
+ dart_object_initiated.value.as_array.length = 2;
+ dart_object_initiated.value.as_array.values = elements;
+
+ const bool result =
+ Dart_PostCObject_DL(info_dart.initiated_cb, &dart_object_initiated);
+ if (!result) {
+ NEARBY_LOG(INFO, "Posting message to port failed.");
+ }
+ };
+ info.listener.accepted_cb = [info_dart](const std::string &endpoint_id) {
+ NEARBY_LOG(INFO, "Advertising accepted: id=%s", endpoint_id.c_str());
+ Dart_CObject dart_object_accepted;
+ dart_object_accepted.type = Dart_CObject_kString;
+ dart_object_accepted.value.as_string = (char *)endpoint_id.c_str();
+ const bool result =
+ Dart_PostCObject_DL(info_dart.accepted_cb, &dart_object_accepted);
+ if (!result) {
+ NEARBY_LOG(INFO, "Posting message to port failed.");
+ }
+ };
+ info.listener.rejected_cb = [info_dart](const std::string &endpoint_id,
+ Status status) {
+ NEARBY_LOG(INFO, "Advertising rejected: id=%s", endpoint_id.c_str());
+ Dart_CObject dart_object_rejected;
+ dart_object_rejected.type = Dart_CObject_kString;
+ dart_object_rejected.value.as_string = (char *)endpoint_id.c_str();
+ const bool result =
+ Dart_PostCObject_DL(info_dart.rejected_cb, &dart_object_rejected);
+ if (!result) {
+ NEARBY_LOG(INFO, "Posting message to port failed.");
+ }
+ };
+ info.listener.disconnected_cb = [info_dart](const std::string &endpoint_id) {
+ NEARBY_LOG(INFO, "Advertising disconnected: id=%s", endpoint_id.c_str());
+ Dart_CObject dart_object_disconnected;
+ dart_object_disconnected.type = Dart_CObject_kString;
+ dart_object_disconnected.value.as_string = (char *)endpoint_id.c_str();
+ const bool result = Dart_PostCObject_DL(info_dart.disconnected_cb,
+ &dart_object_disconnected);
+ if (!result) {
+ NEARBY_LOG(INFO, "Posting message to port failed.");
+ }
+ };
+ info.listener.bandwidth_changed_cb =
+ [info_dart](const std::string &endpoint_id, Medium medium) {
+ NEARBY_LOG(INFO, "Advertising bandwidth changed: id=%s",
+ endpoint_id.c_str());
+ Dart_CObject dart_object_bandwidth_changed;
+
+ dart_object_bandwidth_changed.type = Dart_CObject_kString;
+ dart_object_bandwidth_changed.value.as_string =
+ (char *)endpoint_id.c_str();
+ const bool result = Dart_PostCObject_DL(info_dart.bandwidth_changed_cb,
+ &dart_object_bandwidth_changed);
+ if (!result) {
+ NEARBY_LOG(INFO, "Posting message to port failed.");
+ }
+ };
+
+ ResultCallback callback;
+ SetResultCallback(callback, result_cb);
+ StartAdvertising(pCore, service_id, std::move(advertising_options), info,
+ callback);
+}
+
+void StopAdvertisingDart(Core *pCore, Dart_Port result_cb) {
+ if (!pCore) {
+ PostResult(result_cb, Status::Value::kError);
+ return;
+ }
+
+ ResultCallback callback;
+ SetResultCallback(callback, result_cb);
+ StopAdvertising(pCore, callback);
+}
+
+void StartDiscoveryDart(Core *pCore, const char *service_id,
+ ConnectionOptionsDart options_dart,
+ DiscoveryListenerDart listener_dart,
+ Dart_Port result_cb) {
+ if (!pCore) {
+ PostResult(result_cb, Status::Value::kError);
+ return;
+ }
+
+ DiscoveryOptions discovery_options;
+ discovery_options.strategy = GetStrategy(options_dart.strategy);
+ discovery_options.allowed.bluetooth = options_dart.enable_bluetooth;
+ discovery_options.allowed.ble = options_dart.enable_ble;
+ discovery_options.allowed.wifi_lan = options_dart.enable_wifi_lan;
+ discovery_options.allowed.web_rtc = false;
+ discovery_options.enforce_topology_constraints = true;
+ discovery_options.fast_advertisement_service_uuid =
+ options_dart.discover_fast_advertisements
+ ? "0000FE2C-0000-1000-8000-00805F9B34FB"
+ : "";
+
+ DiscoveryListener listener;
+ listener.endpoint_found_cb = [listener_dart](
+ const std::string &endpoint_id,
+ const ByteArray &endpoint_info,
+ const std::string &str_service_id) {
+ NEARBY_LOG(INFO, "Device discovered: id=%s", endpoint_id.c_str());
+ NEARBY_LOG(INFO, "Device discovered: service_id=%s",
+ str_service_id.c_str());
+ NEARBY_LOG(INFO, "Device discovered: info=%s",
+ ((string)endpoint_info).c_str());
+
+ Dart_CObject dart_object_endpoint_id;
+ dart_object_endpoint_id.type = Dart_CObject_kString;
+ dart_object_endpoint_id.value.as_string = (char *)endpoint_id.data();
+
+ Dart_CObject dart_object_endpoint_info;
+ dart_object_endpoint_info.type = Dart_CObject_kString;
+ dart_object_endpoint_info.value.as_string = (char *)endpoint_info.data();
+
+ Dart_CObject *elements[2];
+ elements[0] = &dart_object_endpoint_id;
+ elements[1] = &dart_object_endpoint_info;
+
+ Dart_CObject dart_object_found;
+ dart_object_found.type = Dart_CObject_kArray;
+ dart_object_found.value.as_array.length = 2;
+ dart_object_found.value.as_array.values = elements;
+ const bool result =
+ Dart_PostCObject_DL(listener_dart.found_cb, &dart_object_found);
+ if (!result) {
+ NEARBY_LOG(INFO, "Posting message to port failed.");
+ }
+ };
+ listener.endpoint_lost_cb = [listener_dart](const std::string &endpoint_id) {
+ NEARBY_LOG(INFO, "Device lost: id=%s", endpoint_id.c_str());
+ Dart_CObject dart_object_lost;
+ dart_object_lost.type = Dart_CObject_kString;
+ dart_object_lost.value.as_string = (char *)endpoint_id.c_str();
+ const bool result =
+ Dart_PostCObject_DL(listener_dart.lost_cb, &dart_object_lost);
+ if (!result) {
+ NEARBY_LOG(INFO, "Posting message to port failed.");
+ }
+ };
+ listener.endpoint_distance_changed_cb =
+ [listener_dart](const std::string &endpoint_id, DistanceInfo info) {
+ NEARBY_LOG(INFO, "Device distance changed: id=%s", endpoint_id.c_str());
+ Dart_CObject dart_object_distance_changed;
+ dart_object_distance_changed.type = Dart_CObject_kString;
+ dart_object_distance_changed.value.as_string =
+ (char *)(endpoint_id.c_str());
+ const bool result = Dart_PostCObject_DL(
+ listener_dart.distance_changed_cb, &dart_object_distance_changed);
+ if (!result) {
+ NEARBY_LOG(INFO, "Posting message to port failed.");
+ }
+ };
+
+ ResultCallback callback;
+ SetResultCallback(callback, result_cb);
+ StartDiscovery(pCore, service_id, std::move(discovery_options), listener,
+ callback);
+}
+
+void StopDiscoveryDart(Core *pCore, Dart_Port result_cb) {
+ if (!pCore) {
+ PostResult(result_cb, Status::Value::kError);
+ return;
+ }
+
+ ResultCallback callback;
+ SetResultCallback(callback, result_cb);
+ StopDiscovery(pCore, callback);
+}
+
+void RequestConnectionDart(Core *pCore, const char *endpoint_id,
+ ConnectionOptionsDart options_dart,
+ ConnectionRequestInfoDart info_dart,
+ Dart_Port result_cb) {
+ if (!pCore) {
+ PostResult(result_cb, Status::Value::kError);
+ return;
+ }
+
+ ConnectionOptions connection_options;
+ connection_options.enforce_topology_constraints = false;
+ connection_options.allowed.bluetooth = options_dart.enable_bluetooth;
+ connection_options.allowed.ble = options_dart.enable_ble;
+ connection_options.allowed.wifi_lan = options_dart.enable_wifi_lan;
+ connection_options.allowed.web_rtc = options_dart.enable_web_rtc;
+
+ ConnectionRequestInfo info;
+ info.endpoint_info = ByteArray(info_dart.endpoint_info);
+ info.listener.initiated_cb =
+ [info_dart](const std::string &endpoint_id,
+ const ConnectionResponseInfo &connection_info) {
+ NEARBY_LOG(INFO, "Connection request initiated: id=%s",
+ endpoint_id.c_str());
+
+ Dart_CObject dart_object_endpoint_id;
+ dart_object_endpoint_id.type = Dart_CObject_kString;
+ dart_object_endpoint_id.value.as_string = (char *)endpoint_id.data();
+
+ Dart_CObject dart_object_endpoint_info;
+ dart_object_endpoint_info.type = Dart_CObject_kString;
+ dart_object_endpoint_info.value.as_string =
+ (char *)connection_info.remote_endpoint_info.data();
+
+ Dart_CObject *elements[2];
+ elements[0] = &dart_object_endpoint_id;
+ elements[1] = &dart_object_endpoint_info;
+
+ Dart_CObject dart_object_initiated;
+ dart_object_initiated.type = Dart_CObject_kArray;
+ dart_object_initiated.value.as_array.length = 2;
+ dart_object_initiated.value.as_array.values = elements;
+
+ const bool result =
+ Dart_PostCObject_DL(info_dart.initiated_cb, &dart_object_initiated);
+ if (!result) {
+ NEARBY_LOG(INFO, "Posting message to port failed.");
+ }
+ };
+ info.listener.accepted_cb = [info_dart](const std::string &endpoint_id) {
+ NEARBY_LOG(INFO, "Advertising accepted: id=%s", endpoint_id.c_str());
+ Dart_CObject dart_object_accepted;
+ dart_object_accepted.type = Dart_CObject_kString;
+ dart_object_accepted.value.as_string = (char *)endpoint_id.c_str();
+ const bool result =
+ Dart_PostCObject_DL(info_dart.accepted_cb, &dart_object_accepted);
+ if (!result) {
+ NEARBY_LOG(INFO, "Posting message to port failed.");
+ }
+ };
+ info.listener.rejected_cb = [info_dart](const std::string &endpoint_id,
+ Status status) {
+ NEARBY_LOG(INFO, "Advertising rejected: id=%s", endpoint_id.c_str());
+ Dart_CObject dart_object_rejected;
+ dart_object_rejected.type = Dart_CObject_kString;
+ dart_object_rejected.value.as_string = (char *)endpoint_id.c_str();
+ const bool result =
+ Dart_PostCObject_DL(info_dart.rejected_cb, &dart_object_rejected);
+ if (!result) {
+ NEARBY_LOG(INFO, "Posting message to port failed.");
+ }
+ };
+ info.listener.disconnected_cb = [info_dart](const std::string &endpoint_id) {
+ NEARBY_LOG(INFO, "Advertising disconnected: id=%s", endpoint_id.c_str());
+ Dart_CObject dart_object_disconnected;
+ dart_object_disconnected.type = Dart_CObject_kString;
+ dart_object_disconnected.value.as_string = (char *)endpoint_id.c_str();
+ const bool result = Dart_PostCObject_DL(info_dart.disconnected_cb,
+ &dart_object_disconnected);
+ if (!result) {
+ NEARBY_LOG(INFO, "Posting message to port failed.");
+ }
+ };
+ info.listener.bandwidth_changed_cb =
+ [info_dart](const std::string &endpoint_id, Medium medium) {
+ NEARBY_LOG(INFO, "Advertising bandwidth changed: id=%s",
+ endpoint_id.c_str());
+ Dart_CObject dart_object_bandwidth_changed;
+
+ dart_object_bandwidth_changed.type = Dart_CObject_kString;
+ dart_object_bandwidth_changed.value.as_string =
+ (char *)endpoint_id.c_str();
+ const bool result = Dart_PostCObject_DL(info_dart.bandwidth_changed_cb,
+ &dart_object_bandwidth_changed);
+ if (!result) {
+ NEARBY_LOG(INFO, "Posting message to port failed.");
+ }
+ };
+
+ ResultCallback callback;
+ SetResultCallback(callback, result_cb);
+ RequestConnection(pCore, endpoint_id, info, std::move(connection_options),
+ callback);
+}
+
+void AcceptConnectionDart(Core *pCore, const char *endpoint_id,
+ PayloadListenerDart listener_dart,
+ Dart_Port result_cb) {
+ if (!pCore) {
+ PostResult(result_cb, Status::Value::kError);
+ return;
+ }
+
+ PayloadListener listener;
+ listener.payload_cb = [listener_dart](const std::string &endpoint_id,
+ Payload payload) {
+ NEARBY_LOG(INFO,
+ "Payload callback called. id: %s, "
+ "payload_id: %d, type: %d, offset: %d",
+ endpoint_id.c_str(), payload.GetId(), payload.GetType(),
+ payload.GetOffset());
+
+ Dart_CObject dart_object_endpoint_id;
+ dart_object_endpoint_id.type = Dart_CObject_kString;
+ dart_object_endpoint_id.value.as_string = (char *)endpoint_id.data();
+
+ Dart_CObject dart_object_payload_id;
+ dart_object_payload_id.type = Dart_CObject_kInt64;
+ dart_object_payload_id.value.as_int64 = payload.GetId();
+
+ Dart_CObject dart_object_payload_type;
+ dart_object_payload_type.type = Dart_CObject_kInt64;
+ dart_object_payload_type.value.as_int64 = (int)payload.GetType();
+
+ Dart_CObject dart_object_offset;
+ dart_object_offset.type = Dart_CObject_kInt64;
+ dart_object_offset.value.as_int64 = payload.GetOffset();
+
+ Dart_CObject *elements[4];
+ elements[0] = &dart_object_endpoint_id;
+ elements[1] = &dart_object_payload_id;
+ elements[2] = &dart_object_payload_type;
+ elements[3] = &dart_object_offset;
+
+ Dart_CObject dart_object_payload;
+ dart_object_payload.type = Dart_CObject_kArray;
+ dart_object_payload.value.as_array.length = 4;
+ dart_object_payload.value.as_array.values = elements;
+
+ if (!Dart_PostCObject_DL(listener_dart.payload_cb, &dart_object_payload)) {
+ NEARBY_LOG(INFO, "Posting message to port failed.");
+ }
+ };
+ listener.payload_progress_cb = [listener_dart](
+ const std::string &endpoint_id,
+ const PayloadProgressInfo &info) {
+ NEARBY_LOG(INFO,
+ "Payload progress callback called. id: %s, "
+ "payload_id: %d, bytes transferred: %d, total: %d, status: %d",
+ endpoint_id.c_str(), info.payload_id, info.bytes_transferred,
+ info.total_bytes, info.status);
+ Dart_CObject dart_object_endpoint_id;
+ dart_object_endpoint_id.type = Dart_CObject_kString;
+ dart_object_endpoint_id.value.as_string = (char *)endpoint_id.data();
+
+ Dart_CObject dart_object_payload_id;
+ dart_object_payload_id.type = Dart_CObject_kInt64;
+ dart_object_payload_id.value.as_int64 = info.payload_id;
+
+ Dart_CObject dart_object_bytes_transferred;
+ dart_object_bytes_transferred.type = Dart_CObject_kInt64;
+ dart_object_bytes_transferred.value.as_int64 = info.bytes_transferred;
+
+ Dart_CObject dart_object_total_bytes;
+ dart_object_total_bytes.type = Dart_CObject_kInt64;
+ dart_object_total_bytes.value.as_int64 = info.total_bytes;
+
+ Dart_CObject dart_object_status;
+ dart_object_status.type = Dart_CObject_kInt64;
+ dart_object_status.value.as_int64 = (int64_t)info.status;
+
+ Dart_CObject *elements[5];
+ elements[0] = &dart_object_endpoint_id;
+ elements[1] = &dart_object_payload_id;
+ elements[2] = &dart_object_bytes_transferred;
+ elements[3] = &dart_object_total_bytes;
+ elements[4] = &dart_object_status;
+
+ Dart_CObject dart_object_payload_progress;
+ dart_object_payload_progress.type = Dart_CObject_kArray;
+ dart_object_payload_progress.value.as_array.length = 5;
+ dart_object_payload_progress.value.as_array.values = elements;
+
+ if (!Dart_PostCObject_DL(listener_dart.payload_progress_cb,
+ &dart_object_payload_progress)) {
+ NEARBY_LOG(INFO, "Posting message to port failed.");
+ }
+ };
+
+ ResultCallback callback;
+ SetResultCallback(callback, result_cb);
+ AcceptConnection(pCore, endpoint_id, listener, callback);
+}
+
+void DisconnectFromEndpointDart(Core *pCore, char *endpoint_id,
+ Dart_Port result_cb) {
+ if (!pCore) {
+ PostResult(result_cb, Status::Value::kError);
+ return;
+ }
+
+ ResultCallback callback;
+ SetResultCallback(callback, result_cb);
+ DisconnectFromEndpoint(pCore, endpoint_id, callback);
+}
+
+std::string GetPayloadPath(location::nearby::PayloadId payload_id) {
+ PWSTR basePath;
+
+ // Retrieves the full path of a known folder identified by the folder's
+ // KNOWNFOLDERID.
+ // https://docs.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetknownfolderpath
+ SHGetKnownFolderPath(
+ FOLDERID_Downloads, // rfid: A reference to the KNOWNFOLDERID that
+ // identifies the folder.
+ 0, // dwFlags: Flags that specify special retrieval options.
+ NULL, // hToken: An access token that represents a particular user.
+ &basePath); // ppszPath: When this method returns, contains the address
+ // of a pointer to a null-terminated Unicode string that
+ // specifies the path of the known folder. The calling
+ // process is responsible for freeing this resource once it
+ // is no longer needed by calling CoTaskMemFree, whether
+ // SHGetKnownFolderPath succeeds or not.
+ size_t bufferSize;
+ wcstombs_s(&bufferSize, NULL, 0, basePath, 0);
+ char *fullpathUTF8 = new char[bufferSize + 1];
+ memset(fullpathUTF8, 0, bufferSize);
+ wcstombs_s(&bufferSize, fullpathUTF8, bufferSize, basePath, bufferSize - 1);
+ std::string fullPath = std::string(fullpathUTF8);
+ auto retval = absl::StrCat(fullPath, "\\", payload_id);
+ delete[] fullpathUTF8;
+ return retval;
+}
+
+void SendPayloadDart(Core *pCore, const char *endpoint_id,
+ PayloadDart payload_dart, Dart_Port result_cb) {
+ if (!pCore) {
+ PostResult(result_cb, Status::Value::kError);
+ return;
+ }
+
+ ResultCallback callback;
+ std::vector<string> endpoint_ids = {string(endpoint_id)};
+
+ NEARBY_LOG(INFO, "Payload type: %d", payload_dart.type);
+ switch (payload_dart.type) {
+ case UNKNOWN:
+ case STREAM:
+ NEARBY_LOG(INFO, "Payload type not supported yet");
+ PostResult(result_cb, Status::Value::kPayloadUnknown);
+ break;
+ case BYTE: {
+ Payload payload(Payload::GenerateId(), ByteArray(payload_dart.data));
+ SendPayload(pCore, absl::Span<const std::string>(endpoint_ids),
+ std::move(payload), callback);
+ }
+ SetResultCallback(callback, result_cb);
+ break;
+ case FILE:
+ NEARBY_LOG(INFO, "File name: %s, size %d", payload_dart.data,
+ payload_dart.size);
+ std::string file_name_str(payload_dart.data);
+
+ // TODO(yanfangliu) Clean this up when John's file payload change rolls
+ // out
+ Payload::Id id = std::hash<std::string>()(file_name_str);
+ std::string download_path = GetPayloadPath(id);
+ CopyFileA((LPSTR)payload_dart.data, (LPSTR)download_path.c_str(),
+ /*FailIfFileAlreadyExists=*/ false);
+ NEARBY_LOGS(INFO) << "Copy File to " << download_path;
+
+ InputFile input_file{id, payload_dart.size};
+ {
+ Payload payload{id, std::move(input_file)};
+ SendPayload(pCore, absl::Span<const std::string>(endpoint_ids),
+ std::move(payload), callback);
+ }
+ SetResultCallback(callback, result_cb);
+
+ break;
+ }
+}
+} // namespace windows
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/clients/windows/dart/core_adapter_dart.h b/chromium/third_party/nearby/src/connections/clients/windows/dart/core_adapter_dart.h
new file mode 100644
index 00000000000..188dcf95cde
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/clients/windows/dart/core_adapter_dart.h
@@ -0,0 +1,216 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef LOCATION_NEARBY_CONNECTIONS_WINDOWS_DART_CORE_ADAPTER_DART_H_
+#define LOCATION_NEARBY_CONNECTIONS_WINDOWS_DART_CORE_ADAPTER_DART_H_
+
+#include "third_party/dart_lang/v2/runtime/include/dart_api_dl.h"
+#include "third_party/dart_lang/v2/runtime/include/dart_native_api.h"
+#include "connections/clients/windows/core_adapter.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace windows {
+
+enum StrategyDart {
+ P2P_CLUSTER = 0,
+ P2P_STAR,
+ P2P_POINT_TO_POINT,
+};
+
+enum PayloadType {
+ UNKNOWN = 0,
+ BYTE,
+ STREAM,
+ FILE,
+};
+
+struct ConnectionOptionsDart {
+ StrategyDart strategy;
+ int64_t auto_upgrade_bandwidth;
+ int64_t enforce_topology_constraints;
+ int64_t enable_bluetooth;
+ int64_t enable_ble;
+ int64_t advertise_nearby_notifications_beacon;
+ int64_t use_low_power_mode;
+ int64_t discover_fast_advertisements;
+ int64_t enable_wifi_lan;
+ int64_t enable_nfc;
+ int64_t enable_wifi_aware;
+ int64_t enable_web_rtc;
+};
+
+struct ConnectionRequestInfoDart {
+ char *endpoint_info;
+ int64_t initiated_cb;
+ int64_t accepted_cb;
+ int64_t rejected_cb;
+ int64_t disconnected_cb;
+ int64_t bandwidth_changed_cb;
+};
+
+struct DiscoveryListenerDart {
+ int64_t found_cb;
+ int64_t lost_cb;
+ int64_t distance_changed_cb;
+};
+
+struct PayloadListenerDart {
+ int64_t payload_cb;
+ int64_t payload_progress_cb;
+};
+
+struct PayloadDart {
+ int64_t id;
+ PayloadType type;
+ int64_t size;
+ char *data;
+};
+
+// Starts advertising an endpoint for a local app.
+//
+// service_id - An identifier to advertise your app to other endpoints.
+// This can be an arbitrary string, so long as it uniquely
+// identifies your service. A good default is to use your
+// app's package name.
+// options_dart - options for advertising
+// info_dart - Including callbacks notified when remote
+// endpoints request a connection to this endpoint.
+// result_cb - to access the status of the operation when available.
+// Possible status codes include:
+// Status::STATUS_OK if advertising started successfully.
+// Status::STATUS_ALREADY_ADVERTISING if the app is already advertising.
+// Status::STATUS_OUT_OF_ORDER_API_CALL if the app is currently
+// connected to remote endpoints; call StopAllEndpoints first.
+DLL_EXPORT void __stdcall StartAdvertisingDart(
+ Core *pCore, const char *service_id, ConnectionOptionsDart options_dart,
+ ConnectionRequestInfoDart info_dart, Dart_Port result_cb);
+
+// Stops advertising a local endpoint. Should be called after calling
+// StartAdvertising, as soon as the application no longer needs to advertise
+// itself or goes inactive. Payloads can still be sent to connected
+// endpoints after advertising ends.
+//
+// result_cb - to access the status of the operation when available.
+// Possible status codes include:
+// Status::STATUS_OK if none of the above errors occurred.
+DLL_EXPORT void __stdcall StopAdvertisingDart(Core *pCore, Dart_Port result_cb);
+
+// Starts discovery for remote endpoints with the specified service ID.
+//
+// service_id - The ID for the service to be discovered, as specified in
+// the corresponding call to StartAdvertising.
+// options - The options for discovery.
+// listener - Callbacks notified when a remote endpoint is discovered.
+// result_cb - to access the status of the operation when available.
+// Possible status codes include:
+// Status::STATUS_OK if discovery started successfully.
+// Status::STATUS_ALREADY_DISCOVERING if the app is already
+// discovering the specified service.
+// Status::STATUS_OUT_OF_ORDER_API_CALL if the app is currently
+// connected to remote endpoints; call StopAllEndpoints first.
+DLL_EXPORT void __stdcall StartDiscoveryDart(
+ Core *pCore, const char *service_id, ConnectionOptionsDart options_dart,
+ DiscoveryListenerDart listener_dart, Dart_Port result_cb);
+
+// Stops discovery for remote endpoints, after a previous call to
+// StartDiscovery, when the client no longer needs to discover endpoints or
+// goes inactive. Payloads can still be sent to connected endpoints after
+// discovery ends.
+//
+// result_cb - to access the status of the operation when available.
+// Possible status codes include:
+// Status::STATUS_OK if none of the above errors occurred.
+DLL_EXPORT void __stdcall StopDiscoveryDart(Core *pCore, Dart_Port result_cb);
+
+// Sends a request to connect to a remote endpoint.
+//
+// endpoint_id - The identifier for the remote endpoint to which a
+// connection request will be sent. Should match the value
+// provided in a call to
+// DiscoveryListener::endpoint_found_cb()
+// options_dart - The options for connection.
+// info_dart - Connection parameters:
+// > name - A human readable name for the local endpoint, to appear on
+// the remote endpoint.
+// > listener - Callbacks notified when the remote endpoint sends a
+// response to the connection request.
+// result_cb - to access the status of the operation when available.
+// Possible status codes include:
+// Status::STATUS_OK if the connection request was sent.
+// Status::STATUS_ALREADY_CONNECTED_TO_ENDPOINT if the app already
+// has a connection to the specified endpoint.
+// Status::STATUS_RADIO_ERROR if we failed to connect because of an
+// issue with Bluetooth/WiFi.
+// Status::STATUS_ERROR if we failed to connect for any other reason.
+DLL_EXPORT void __stdcall RequestConnectionDart(
+ Core *pCore, const char *endpoint_id, ConnectionOptionsDart options_dart,
+ ConnectionRequestInfoDart info_dart, Dart_Port result_cb);
+
+// Accepts a connection to a remote endpoint. This method must be called
+// before Payloads can be exchanged with the remote endpoint.
+//
+// endpoint_id - The identifier for the remote endpoint. Should match the
+// value provided in a call to
+// ConnectionListener::onConnectionInitiated.
+// listener_dart - A callback for payloads exchanged with the remote endpoint.
+// result_cb - to access the status of the operation when available.
+// Possible status codes include:
+// Status::STATUS_OK if the connection request was accepted.
+// Status::STATUS_ALREADY_CONNECTED_TO_ENDPOINT if the app already.
+// has a connection to the specified endpoint.
+DLL_EXPORT void __stdcall AcceptConnectionDart(
+ Core *pCore, const char *endpoint_id, PayloadListenerDart listener_dart,
+ Dart_Port result_cb);
+
+// Disconnects from a remote endpoint. {@link Payload}s can no longer be sent
+// to or received from the endpoint after this method is called.
+// endpoint_id - The identifier for the remote endpoint to disconnect from.
+// result_cb - to access the status of the operation when available.
+// Possible status codes include:
+// Status::STATUS_OK - finished successfully.
+DLL_EXPORT void __stdcall DisconnectFromEndpointDart(Core *pCore,
+ char *endpoint_id,
+ Dart_Port result_cb);
+
+// Sends a Payload to a remote endpoint. Payloads can only be sent to remote
+// endpoints once a notice of connection acceptance has been delivered via
+// ConnectionListener::onConnectionResult().
+//
+// endpoint_id - Remote endpoint identifier for the to which the
+// payload should be sent.
+// payload - The Payload to be sent.
+// result_cb - to access the status of the operation when available.
+// Possible status codes include:
+// Status::STATUS_OUT_OF_ORDER_API_CALL if the device has not first
+// performed advertisement or discovery (to set the Strategy.)
+// Status::STATUS_ENDPOINT_UNKNOWN if there's no active (or pending)
+// connection to the remote endpoint.
+// Status::STATUS_OK if none of the above errors occurred. Note that this
+// indicates that Nearby Connections will attempt to send the Payload,
+// but not that the send has successfully completed yet. Errors might
+// still occur during transmission (and at different times for
+// different endpoints), and will be delivered via
+// PayloadCallback#onPayloadTransferUpdate.
+DLL_EXPORT void __stdcall SendPayloadDart(Core *pCore, const char *endpoint_id,
+ PayloadDart payload_dart,
+ Dart_Port result_cb);
+
+} // namespace windows
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // LOCATION_NEARBY_CONNECTIONS_WINDOWS_CORE_ADAPTER_DART_H_
diff --git a/chromium/third_party/nearby/src/connections/connection_options.cc b/chromium/third_party/nearby/src/connections/connection_options.cc
new file mode 100644
index 00000000000..573bd504868
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/connection_options.cc
@@ -0,0 +1,29 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/connection_options.h"
+
+#include <string>
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+std::vector<Medium> ConnectionOptions::GetMediums() const {
+ return allowed.GetMediums(true);
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/connection_options.h b/chromium/third_party/nearby/src/connections/connection_options.h
new file mode 100644
index 00000000000..0afd2a218d2
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/connection_options.h
@@ -0,0 +1,55 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+#ifndef CORE_CONNECTION_OPTIONS_H_
+#define CORE_CONNECTION_OPTIONS_H_
+#include <string>
+
+#include "connections/medium_selector.h"
+#include "connections/options_base.h"
+#include "connections/power_level.h"
+#include "connections/strategy.h"
+#include "internal/platform/byte_array.h"
+#include "proto/connections_enums.pb.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Feature On/Off switch for mediums.
+using BooleanMediumSelector = MediumSelector<bool>;
+
+// Connection Options: used for both Advertising and Discovery.
+// All fields are mutable, to make the type copy-assignable.
+struct ConnectionOptions : public OptionsBase {
+ bool auto_upgrade_bandwidth;
+ bool enforce_topology_constraints;
+ bool low_power;
+ bool enable_bluetooth_listening;
+ bool enable_webrtc_listening;
+
+ // Whether this is intended to be used in conjunction with InjectEndpoint().
+ bool is_out_of_band_connection = false;
+ ByteArray remote_bluetooth_mac_address;
+ std::string fast_advertisement_service_uuid;
+ int keep_alive_interval_millis = 0;
+ int keep_alive_timeout_millis = 0;
+
+ std::vector<Medium> GetMediums() const;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_CONNECTION_OPTIONS_H_
diff --git a/chromium/third_party/nearby/src/connections/core.cc b/chromium/third_party/nearby/src/connections/core.cc
new file mode 100644
index 00000000000..c6bdf0a078f
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/core.cc
@@ -0,0 +1,160 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/core.h"
+
+#include <cassert>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "absl/time/clock.h"
+#include "internal/platform/feature_flags.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+constexpr absl::Duration kWaitForDisconnect = absl::Milliseconds(5000);
+} // namespace
+
+Core::Core(ServiceControllerRouter* router) : router_(router) {}
+
+Core::~Core() {
+ CountDownLatch latch(1);
+ router_->StopAllEndpoints(
+ &client_, {
+ .result_cb = [&latch](Status) { latch.CountDown(); },
+ });
+ if (!latch.Await(kWaitForDisconnect).result()) {
+ NEARBY_LOG(FATAL, "Unable to shutdown");
+ }
+}
+
+Core::Core(Core&&) = default;
+
+Core& Core::operator=(Core&&) = default;
+
+void Core::StartAdvertising(absl::string_view service_id,
+ AdvertisingOptions advertising_options,
+ ConnectionRequestInfo info,
+ ResultCallback callback) {
+ assert(!service_id.empty());
+ assert(advertising_options.strategy.IsValid());
+
+ router_->StartAdvertising(&client_, service_id, advertising_options, info,
+ callback);
+}
+
+void Core::StopAdvertising(const ResultCallback callback) {
+ router_->StopAdvertising(&client_, callback);
+}
+
+void Core::StartDiscovery(absl::string_view service_id,
+ DiscoveryOptions discovery_options,
+ DiscoveryListener listener, ResultCallback callback) {
+ assert(!service_id.empty());
+ assert(discovery_options.strategy.IsValid());
+
+ router_->StartDiscovery(&client_, service_id, discovery_options, listener,
+ callback);
+}
+
+void Core::InjectEndpoint(absl::string_view service_id,
+ OutOfBandConnectionMetadata metadata,
+ ResultCallback callback) {
+ router_->InjectEndpoint(&client_, service_id, metadata, callback);
+}
+
+void Core::StopDiscovery(ResultCallback callback) {
+ router_->StopDiscovery(&client_, callback);
+}
+
+void Core::RequestConnection(absl::string_view endpoint_id,
+ ConnectionRequestInfo info,
+ ConnectionOptions connection_options,
+ ResultCallback callback) {
+ assert(!endpoint_id.empty());
+
+ // Assign the default from feature flags for the keep-alive frame interval and
+ // timeout values if client don't mind them or has the unexpected ones.
+ if (connection_options.keep_alive_interval_millis == 0 ||
+ connection_options.keep_alive_timeout_millis == 0 ||
+ connection_options.keep_alive_interval_millis >=
+ connection_options.keep_alive_timeout_millis) {
+ NEARBY_LOG(
+ WARNING,
+ "Client request connection with keep-alive frame as interval=%d, "
+ "timeout=%d, which is un-expected. Change to default.",
+ connection_options.keep_alive_interval_millis,
+ connection_options.keep_alive_timeout_millis);
+ connection_options.keep_alive_interval_millis =
+ FeatureFlags::GetInstance().GetFlags().keep_alive_interval_millis;
+ connection_options.keep_alive_timeout_millis =
+ FeatureFlags::GetInstance().GetFlags().keep_alive_timeout_millis;
+ }
+
+ router_->RequestConnection(&client_, endpoint_id, info, connection_options,
+ callback);
+}
+
+void Core::AcceptConnection(absl::string_view endpoint_id,
+ PayloadListener listener, ResultCallback callback) {
+ assert(!endpoint_id.empty());
+
+ router_->AcceptConnection(&client_, endpoint_id, listener, callback);
+}
+
+void Core::RejectConnection(absl::string_view endpoint_id,
+ ResultCallback callback) {
+ assert(!endpoint_id.empty());
+
+ router_->RejectConnection(&client_, endpoint_id, callback);
+}
+
+void Core::InitiateBandwidthUpgrade(absl::string_view endpoint_id,
+ ResultCallback callback) {
+ router_->InitiateBandwidthUpgrade(&client_, endpoint_id, callback);
+}
+
+void Core::SendPayload(absl::Span<const std::string> endpoint_ids,
+ Payload payload, ResultCallback callback) {
+ assert(payload.GetType() != Payload::Type::kUnknown);
+ assert(!endpoint_ids.empty());
+
+ router_->SendPayload(&client_, endpoint_ids, std::move(payload), callback);
+}
+
+void Core::CancelPayload(std::int64_t payload_id, ResultCallback callback) {
+ assert(payload_id != 0);
+
+ router_->CancelPayload(&client_, payload_id, callback);
+}
+
+void Core::DisconnectFromEndpoint(absl::string_view endpoint_id,
+ ResultCallback callback) {
+ assert(!endpoint_id.empty());
+
+ router_->DisconnectFromEndpoint(&client_, endpoint_id, callback);
+}
+
+void Core::StopAllEndpoints(ResultCallback callback) {
+ router_->StopAllEndpoints(&client_, callback);
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/core.h b/chromium/third_party/nearby/src/connections/core.h
new file mode 100644
index 00000000000..d82bf672225
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/core.h
@@ -0,0 +1,249 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_CORE_H_
+#define CORE_CORE_H_
+
+#include <functional>
+#include <string>
+
+#include "absl/strings/string_view.h"
+#include "absl/types/span.h"
+#include "connections/event_logger.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/service_controller.h"
+#include "connections/implementation/service_controller_router.h"
+#include "connections/listeners.h"
+#include "connections/params.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// This class defines the API of the Nearby Connections Core library.
+class Core {
+ public:
+ explicit Core(ServiceControllerRouter* router);
+ // Client needs to call this constructor if analytics logger is needed.
+ Core(analytics::EventLogger* event_logger, ServiceControllerRouter* router)
+ : client_(event_logger), router_(router) {}
+ ~Core();
+ Core(Core&&);
+ Core& operator=(Core&&);
+
+ // Starts advertising an endpoint for a local app.
+ //
+ // service_id - An identifier to advertise your app to other endpoints.
+ // This can be an arbitrary string, so long as it uniquely
+ // identifies your service. A good default is to use your
+ // app's package name.
+ // advertising_options - The options for advertising.
+ // info - Connection parameters:
+ // > name - A human readable name for this endpoint, to appear on
+ // other devices.
+ // > listener - A callback notified when remote endpoints request a
+ // connection to this endpoint.
+ // callback - to access the status of the operation when available.
+ // Possible status codes include:
+ // Status::STATUS_OK if advertising started successfully.
+ // Status::STATUS_ALREADY_ADVERTISING if the app is already advertising.
+ // Status::STATUS_OUT_OF_ORDER_API_CALL if the app is currently
+ // connected to remote endpoints; call StopAllEndpoints first.
+ void StartAdvertising(absl::string_view service_id,
+ AdvertisingOptions advertising_options,
+ ConnectionRequestInfo info, ResultCallback callback);
+
+ // Stops advertising a local endpoint. Should be called after calling
+ // StartAdvertising, as soon as the application no longer needs to advertise
+ // itself or goes inactive. Payloads can still be sent to connected
+ // endpoints after advertising ends.
+ //
+ // result_cb - to access the status of the operation when available.
+ // Possible status codes include:
+ // Status::STATUS_OK if none of the above errors occurred.
+ void StopAdvertising(ResultCallback callback);
+
+ // Starts discovery for remote endpoints with the specified service ID.
+ //
+ // service_id - The ID for the service to be discovered, as specified in
+ // the corresponding call to StartAdvertising.
+ // listener - A callback notified when a remote endpoint is discovered.
+ // discovery_options - The options for discovery.
+ // result_cb - to access the status of the operation when available.
+ // Possible status codes include:
+ // Status::STATUS_OK if discovery started successfully.
+ // Status::STATUS_ALREADY_DISCOVERING if the app is already
+ // discovering the specified service.
+ // Status::STATUS_OUT_OF_ORDER_API_CALL if the app is currently
+ // connected to remote endpoints; call StopAllEndpoints first.
+ void StartDiscovery(absl::string_view service_id,
+ DiscoveryOptions discovery_options,
+ DiscoveryListener listener, ResultCallback callback);
+
+ // Stops discovery for remote endpoints, after a previous call to
+ // StartDiscovery, when the client no longer needs to discover endpoints or
+ // goes inactive. Payloads can still be sent to connected endpoints after
+ // discovery ends.
+ //
+ // result_cb - to access the status of the operation when available.
+ // Possible status codes include:
+ // Status::STATUS_OK if none of the above errors occurred.
+ void StopDiscovery(ResultCallback callback);
+
+ // Invokes the discovery callback from a previous call to StartDiscovery()
+ // with the given endpoint info. The previous call to StartDiscovery() must
+ // have been passed ConnectionOptions with is_out_of_band_connection == true.
+ //
+ // service_id - The ID for the service to be discovered, as
+ // specified in the corresponding call to
+ // StartDiscovery().
+ // metadata - Metadata used in order to inject the endpoint.
+ // result_cb - to access the status of the operation when
+ // available.
+ // Possible status codes include:
+ // Status::kSuccess if endpoint injection was attempted.
+ // Status::kError if endpoint_id, endpoint_info, or
+ // remote_bluetooth_mac_address are malformed.
+ // Status::kOutOfOrderApiCall if the app is not discovering.
+ void InjectEndpoint(absl::string_view service_id,
+ OutOfBandConnectionMetadata metadata,
+ ResultCallback callback);
+
+ // Sends a request to connect to a remote endpoint.
+ //
+ // endpoint_id - The identifier for the remote endpoint to which a
+ // connection request will be sent. Should match the value
+ // provided in a call to
+ // DiscoveryListener::endpoint_found_cb()
+ // info - Connection parameters:
+ // > name - A human readable name for the local endpoint, to appear on
+ // the remote endpoint.
+ // > listener - A callback notified when the remote endpoint sends a
+ // response to the connection request.
+ // result_cb - to access the status of the operation when available.
+ // Possible status codes include:
+ // Status::STATUS_OK if the connection request was sent.
+ // Status::STATUS_ALREADY_CONNECTED_TO_ENDPOINT if the app already
+ // has a connection to the specified endpoint.
+ // Status::STATUS_RADIO_ERROR if we failed to connect because of an
+ // issue with Bluetooth/WiFi.
+ // Status::STATUS_ERROR if we failed to connect for any other reason.
+ void RequestConnection(absl::string_view endpoint_id,
+ ConnectionRequestInfo info,
+ ConnectionOptions connection_options,
+ ResultCallback callback);
+
+ // Accepts a connection to a remote endpoint. This method must be called
+ // before Payloads can be exchanged with the remote endpoint.
+ //
+ // endpoint_id - The identifier for the remote endpoint. Should match the
+ // value provided in a call to
+ // ConnectionListener::onConnectionInitiated.
+ // listener - A callback for payloads exchanged with the remote endpoint.
+ // result_cb - to access the status of the operation when available.
+ // Possible status codes include:
+ // Status::STATUS_OK if the connection request was accepted.
+ // Status::STATUS_ALREADY_CONNECTED_TO_ENDPOINT if the app already.
+ // has a connection to the specified endpoint.
+ void AcceptConnection(absl::string_view endpoint_id, PayloadListener listener,
+ ResultCallback callback);
+
+ // Rejects a connection to a remote endpoint.
+ //
+ // endpoint_id - The identifier for the remote endpoint. Should match the
+ // value provided in a call to
+ // ConnectionListener::onConnectionInitiated().
+ // result_cb - to access the status of the operation when available.
+ // Possible status codes include:
+ // Status::STATUS_OK} if the connection request was rejected.
+ // Status::STATUS_ALREADY_CONNECTED_TO_ENDPOINT} if the app already
+ // has a connection to the specified endpoint.
+ void RejectConnection(absl::string_view endpoint_id, ResultCallback callback);
+
+ // Sends a Payload to a remote endpoint. Payloads can only be sent to remote
+ // endpoints once a notice of connection acceptance has been delivered via
+ // ConnectionListener::onConnectionResult().
+ //
+ // endpoint_ids - Array of remote endpoint identifiers for the to which the
+ // payload should be sent.
+ // payload - The Payload to be sent.
+ // result_cb - to access the status of the operation when available.
+ // Possible status codes include:
+ // Status::STATUS_OUT_OF_ORDER_API_CALL if the device has not first
+ // performed advertisement or discovery (to set the Strategy.
+ // Status::STATUS_ENDPOINT_UNKNOWN if there's no active (or pending)
+ // connection to the remote endpoint.
+ // Status::STATUS_OK if none of the above errors occurred. Note that this
+ // indicates that Nearby Connections will attempt to send the Payload,
+ // but not that the send has successfully completed yet. Errors might
+ // still occur during transmission (and at different times for
+ // different endpoints), and will be delivered via
+ // PayloadCallback#onPayloadTransferUpdate.
+ void SendPayload(absl::Span<const std::string> endpoint_ids, Payload payload,
+ ResultCallback callback);
+
+ // Cancels a Payload currently in-flight to or from remote endpoint(s).
+ //
+ // payload_id - The identifier for the Payload to be canceled.
+ // result_cb - to access the status of the operation when available.
+ // Possible status codes include:
+ // Status::STATUS_OK if none of the above errors occurred.
+ void CancelPayload(std::int64_t payload_id, ResultCallback callback);
+
+ // Disconnects from a remote endpoint. {@link Payload}s can no longer be sent
+ // to or received from the endpoint after this method is called.
+ //
+ // endpoint_id - The identifier for the remote endpoint to disconnect from.
+ // result_cb - to access the status of the operation when available.
+ // Possible status codes include:
+ // Status::STATUS_OK - finished successfully.
+ void DisconnectFromEndpoint(absl::string_view endpoint_id,
+ ResultCallback callback);
+
+ // Disconnects from, and removes all traces of, all connected and/or
+ // discovered endpoints. This call is expected to be preceded by a call to
+ // StopAdvertising or StartDiscovery as needed. After calling
+ // StopAllEndpoints, no further operations with remote endpoints will be
+ // possible until a new call to one of StartAdvertising() or StartDiscovery().
+ //
+ // result_cb - to access the status of the operation when available.
+ // Possible status codes include:
+ // Status::STATUS_OK - finished successfully.
+ void StopAllEndpoints(ResultCallback callback);
+
+ // Sends a request to initiate connection bandwidth upgrade.
+ //
+ // endpoint_id - The identifier for the remote endpoint which will be
+ // switching to a higher connection data rate and possibly
+ // different wireless protocol. On success, calls
+ // ConnectionListener::bandwidth_changed_cb().
+ // result_cb - to access the status of the operation when available.
+ // Possible status codes include:
+ // Status::STATUS_OK - finished successfully.
+ void InitiateBandwidthUpgrade(absl::string_view endpoint_id,
+ ResultCallback callback);
+
+ // Gets the local endpoint generated by Nearby Connections.
+ std::string GetLocalEndpointId() { return client_.GetLocalEndpointId(); }
+
+ private:
+ ClientProxy client_;
+ ServiceControllerRouter* router_ = nullptr;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_CORE_H_
diff --git a/chromium/third_party/nearby/src/connections/core_test.cc b/chromium/third_party/nearby/src/connections/core_test.cc
new file mode 100644
index 00000000000..14ef0072906
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/core_test.cc
@@ -0,0 +1,53 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/core.h"
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "absl/time/clock.h"
+#include "connections/implementation/mock_service_controller_router.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+
+TEST(CoreTest, ConstructorDestructorWorks) {
+ MockServiceControllerRouter mock;
+ // Called when Core is destroyed.
+ EXPECT_CALL(mock, StopAllEndpoints)
+ .WillOnce([&](ClientProxy* client, const ResultCallback& callback) {
+ callback.result_cb({Status::kSuccess});
+ });
+ Core core{&mock};
+}
+
+TEST(CoreTest, DestructorReportsFatalFailure) {
+ ASSERT_DEATH(
+ {
+ MockServiceControllerRouter mock;
+ // Never invoke the result callback so ~Core will time out.
+ EXPECT_CALL(mock, StopAllEndpoints);
+ Core core{&mock};
+ },
+ "Unable to shutdown");
+}
+
+} // namespace
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/discovery_options.cc b/chromium/third_party/nearby/src/connections/discovery_options.cc
new file mode 100644
index 00000000000..d2321afbf9d
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/discovery_options.cc
@@ -0,0 +1,52 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/discovery_options.h"
+
+#include <string>
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Returns a copy and normalizes allowed mediums:
+// (1) If is_out_of_band_connection is true, verifies that there is only one
+// medium allowed, defaulting to only Bluetooth if unspecified.
+// (2) If no mediums are allowed, allow all mediums.
+DiscoveryOptions DiscoveryOptions::CompatibleOptions() const {
+ DiscoveryOptions result = *this;
+
+ // Out-of-band connections initiate connections via an injected endpoint
+ // rather than through the normal discovery flow. These types of connections
+ // can only be injected via a single medium.
+ if (is_out_of_band_connection) {
+ int num_enabled = result.allowed.Count(true);
+
+ // Default to allow only Bluetooth if no single medium is specified.
+ if (num_enabled != 1) {
+ result.allowed.SetAll(false);
+ result.allowed.bluetooth = true;
+ }
+ return result;
+ }
+
+ // Normal connections (i.e., not out-of-band) connections can specify
+ // multiple mediums. If none are specified, default to allowing all mediums.
+ if (!allowed.Any(true)) result.allowed.SetAll(true);
+ return result;
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/discovery_options.h b/chromium/third_party/nearby/src/connections/discovery_options.h
new file mode 100644
index 00000000000..aa351b92471
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/discovery_options.h
@@ -0,0 +1,55 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+#ifndef CORE_DISCOVERY_OPTIONS_H_
+#define CORE_DISCOVERY_OPTIONS_H_
+#include <string>
+
+#include "connections/medium_selector.h"
+#include "connections/options_base.h"
+#include "connections/power_level.h"
+#include "connections/strategy.h"
+#include "internal/platform/byte_array.h"
+#include "proto/connections_enums.pb.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Feature On/Off switch for mediums.
+using BooleanMediumSelector = MediumSelector<bool>;
+
+// Connection Options: used for both Advertising and Discovery.
+// All fields are mutable, to make the type copy-assignable.
+struct DiscoveryOptions : OptionsBase {
+ bool auto_upgrade_bandwidth;
+ bool enforce_topology_constraints;
+ int keep_alive_interval_millis = 0;
+ int keep_alive_timeout_millis = 0;
+
+ // Whether this is intended to be used in conjunction with InjectEndpoint().
+ bool is_out_of_band_connection = false;
+ std::string fast_advertisement_service_uuid;
+
+ // Returns a copy and normalizes allowed mediums:
+ // (1) If is_out_of_band_connection is true, verifies that there is only one
+ // medium allowed, defaulting to only Bluetooth if unspecified.
+ // (2) If no mediums are allowed, allow all mediums.
+ DiscoveryOptions CompatibleOptions() const;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_DISCOVERY_OPTIONS_H_
diff --git a/chromium/third_party/nearby/src/connections/event_logger.h b/chromium/third_party/nearby/src/connections/event_logger.h
new file mode 100644
index 00000000000..788940973e1
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/event_logger.h
@@ -0,0 +1,39 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_EVENT_LOGGER_H_
+#define CORE_EVENT_LOGGER_H_
+
+#include "internal/proto/analytics/connections_log.pb.h"
+
+namespace location {
+namespace nearby {
+namespace analytics {
+
+// Allows callers to log |ConnectionsLog| collected at Nearby Connections
+// library. Callers need to implement the API if they want to collect this log.
+class EventLogger {
+ public:
+ virtual ~EventLogger() = default;
+
+ // Logs |ConnectionsLog| details. Might block to do I/O, e.g. upload
+ // synchronously to some metrics server.
+ virtual void Log(const proto::ConnectionsLog& connections_log) = 0;
+};
+
+} // namespace analytics
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_EVENT_LOGGER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/BUILD b/chromium/third_party/nearby/src/connections/implementation/BUILD
new file mode 100644
index 00000000000..d10daeecafb
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/BUILD
@@ -0,0 +1,214 @@
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+licenses(["notice"])
+
+cc_library(
+ name = "internal",
+ srcs = [
+ "base_endpoint_channel.cc",
+ "base_pcp_handler.cc",
+ "ble_advertisement.cc",
+ "ble_endpoint_channel.cc",
+ "bluetooth_bwu_handler.cc",
+ "bluetooth_device_name.cc",
+ "bluetooth_endpoint_channel.cc",
+ "bwu_manager.cc",
+ "client_proxy.cc",
+ "encryption_runner.cc",
+ "endpoint_channel_manager.cc",
+ "endpoint_manager.cc",
+ "injected_bluetooth_device_store.cc",
+ "internal_payload.cc",
+ "internal_payload_factory.cc",
+ "offline_frames.cc",
+ "offline_frames_validator.cc",
+ "offline_service_controller.cc",
+ "p2p_cluster_pcp_handler.cc",
+ "p2p_point_to_point_pcp_handler.cc",
+ "p2p_star_pcp_handler.cc",
+ "payload_manager.cc",
+ "pcp_manager.cc",
+ "service_controller_router.cc",
+ "webrtc_bwu_handler.cc",
+ "webrtc_endpoint_channel.cc",
+ "wifi_lan_bwu_handler.cc",
+ "wifi_lan_endpoint_channel.cc",
+ "wifi_lan_service_info.cc",
+ ],
+ hdrs = [
+ "base_bwu_handler.h",
+ "base_endpoint_channel.h",
+ "base_pcp_handler.h",
+ "ble_advertisement.h",
+ "ble_endpoint_channel.h",
+ "bluetooth_bwu_handler.h",
+ "bluetooth_device_name.h",
+ "bluetooth_endpoint_channel.h",
+ "bwu_handler.h",
+ "bwu_manager.h",
+ "client_proxy.h",
+ "encryption_runner.h",
+ "endpoint_channel.h",
+ "endpoint_channel_manager.h",
+ "endpoint_manager.h",
+ "injected_bluetooth_device_store.h",
+ "internal_payload.h",
+ "internal_payload_factory.h",
+ "offline_frames.h",
+ "offline_frames_validator.h",
+ "offline_service_controller.h",
+ "p2p_cluster_pcp_handler.h",
+ "p2p_point_to_point_pcp_handler.h",
+ "p2p_star_pcp_handler.h",
+ "payload_manager.h",
+ "pcp.h",
+ "pcp_handler.h",
+ "pcp_manager.h",
+ "service_controller.h",
+ "service_controller_router.h",
+ "webrtc_bwu_handler.h",
+ "webrtc_endpoint_channel.h",
+ "wifi_lan_bwu_handler.h",
+ "wifi_lan_endpoint_channel.h",
+ "wifi_lan_service_info.h",
+ ],
+ copts = ["-DCORE_ADAPTER_DLL"],
+ defines = ["NO_WEBRTC"],
+ visibility = [
+ "//connections:__pkg__",
+ "//connections/implementation/fuzzers:__pkg__",
+ ],
+ deps = [
+ ":message_lite",
+ ":ukey2",
+ "//connections:core_types",
+ "//connections/implementation/mediums",
+ "//connections/implementation/mediums:utils",
+ "//connections/implementation/proto:offline_wire_formats_cc_proto",
+ "//internal/analytics",
+ "//internal/platform:base",
+ "//internal/platform:cancellation_flag",
+ "//internal/platform:comm",
+ "//internal/platform:error_code_recorder",
+ "//internal/platform:logging",
+ "//internal/platform:types",
+ "//internal/platform:util",
+ "//internal/platform/implementation:comm",
+ "//proto:connections_enums_cc_proto",
+ "@com_google_absl//absl/base:core_headers",
+ "@com_google_absl//absl/container:btree",
+ "@com_google_absl//absl/container:flat_hash_map",
+ "@com_google_absl//absl/container:flat_hash_set",
+ "@com_google_absl//absl/functional:bind_front",
+ "@com_google_absl//absl/memory",
+ "@com_google_absl//absl/strings",
+ "@com_google_absl//absl/time",
+ "@com_google_absl//absl/types:span",
+ ],
+)
+
+cc_library(
+ name = "message_lite",
+ hdrs = [
+ "message_lite.h",
+ ],
+ defines = ["NO_WEBRTC"],
+ visibility = [
+ "//connections:__subpackages__",
+ ],
+ deps = [
+ "@com_google_protobuf//:protobuf_lite",
+ ],
+)
+
+cc_library(
+ name = "internal_test",
+ testonly = True,
+ srcs = [
+ "offline_simulation_user.cc",
+ "simulation_user.cc",
+ ],
+ hdrs = [
+ "mock_service_controller.h",
+ "mock_service_controller_router.h",
+ "offline_simulation_user.h",
+ "simulation_user.h",
+ ],
+ defines = ["NO_WEBRTC"],
+ visibility = [
+ "//connections:__subpackages__",
+ ],
+ deps = [
+ ":internal",
+ "//connections:core_types",
+ "//internal/platform:base",
+ "//internal/platform:test_util",
+ "//internal/platform:types",
+ "@com_google_absl//absl/functional:bind_front",
+ "@com_google_absl//absl/strings",
+ "@com_google_googletest//:gtest_for_library_testonly",
+ ],
+)
+
+cc_test(
+ name = "core_internal_test",
+ size = "small",
+ timeout = "moderate",
+ srcs = [
+ "base_endpoint_channel_test.cc",
+ "base_pcp_handler_test.cc",
+ "ble_advertisement_test.cc",
+ "bluetooth_device_name_test.cc",
+ "bwu_manager_test.cc",
+ "client_proxy_test.cc",
+ "encryption_runner_test.cc",
+ "endpoint_channel_manager_test.cc",
+ "endpoint_manager_test.cc",
+ "injected_bluetooth_device_store_test.cc",
+ "internal_payload_factory_test.cc",
+ "offline_frames_validator_test.cc",
+ "offline_service_controller_test.cc",
+ "p2p_cluster_pcp_handler_test.cc",
+ "payload_manager_test.cc",
+ "pcp_manager_test.cc",
+ "service_controller_router_test.cc",
+ "wifi_lan_service_info_test.cc",
+ ],
+ defines = ["NO_WEBRTC"],
+ shard_count = 16,
+ deps = [
+ ":internal",
+ ":internal_test",
+ ":ukey2",
+ "//connections:core_types",
+ "//connections/implementation/mediums",
+ "//connections/implementation/mediums:utils",
+ "//connections/implementation/proto:offline_wire_formats_cc_proto",
+ "//internal/platform:base",
+ "//internal/platform:comm",
+ "//internal/platform:logging",
+ "//internal/platform:test_util",
+ "//internal/platform:types",
+ "//internal/platform/implementation/g3", # build_cleaner: keep
+ "//proto:connections_enums_cc_proto",
+ "@com_github_protobuf_matchers//protobuf-matchers",
+ "@com_google_absl//absl/container:flat_hash_set",
+ "@com_google_absl//absl/strings",
+ "@com_google_absl//absl/synchronization",
+ "@com_google_absl//absl/time",
+ "@com_google_absl//absl/types:span",
+ "@com_google_googletest//:gtest",
+ "@com_google_googletest//:gtest_main",
+ ],
+)
diff --git a/chromium/third_party/nearby/src/connections/implementation/BUILD.bazel b/chromium/third_party/nearby/src/connections/implementation/BUILD.bazel
new file mode 100644
index 00000000000..705c8484fdf
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/BUILD.bazel
@@ -0,0 +1,216 @@
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+licenses(["notice"])
+
+cc_library(
+ name = "internal",
+ srcs = [
+ "base_endpoint_channel.cc",
+ "base_pcp_handler.cc",
+ "ble_advertisement.cc",
+ "ble_endpoint_channel.cc",
+ "bluetooth_bwu_handler.cc",
+ "bluetooth_device_name.cc",
+ "bluetooth_endpoint_channel.cc",
+ "bwu_manager.cc",
+ "client_proxy.cc",
+ "encryption_runner.cc",
+ "endpoint_channel_manager.cc",
+ "endpoint_manager.cc",
+ "injected_bluetooth_device_store.cc",
+ "internal_payload.cc",
+ "internal_payload_factory.cc",
+ "offline_frames.cc",
+ "offline_frames_validator.cc",
+ "offline_service_controller.cc",
+ "p2p_cluster_pcp_handler.cc",
+ "p2p_point_to_point_pcp_handler.cc",
+ "p2p_star_pcp_handler.cc",
+ "payload_manager.cc",
+ "pcp_manager.cc",
+ "service_controller_router.cc",
+ "webrtc_bwu_handler.cc",
+ "webrtc_endpoint_channel.cc",
+ "wifi_lan_bwu_handler.cc",
+ "wifi_lan_endpoint_channel.cc",
+ "wifi_lan_service_info.cc",
+ ],
+ hdrs = [
+ "base_bwu_handler.h",
+ "base_endpoint_channel.h",
+ "base_pcp_handler.h",
+ "ble_advertisement.h",
+ "ble_endpoint_channel.h",
+ "bluetooth_bwu_handler.h",
+ "bluetooth_device_name.h",
+ "bluetooth_endpoint_channel.h",
+ "bwu_handler.h",
+ "bwu_manager.h",
+ "client_proxy.h",
+ "encryption_runner.h",
+ "endpoint_channel.h",
+ "endpoint_channel_manager.h",
+ "endpoint_manager.h",
+ "injected_bluetooth_device_store.h",
+ "internal_payload.h",
+ "internal_payload_factory.h",
+ "offline_frames.h",
+ "offline_frames_validator.h",
+ "offline_service_controller.h",
+ "p2p_cluster_pcp_handler.h",
+ "p2p_point_to_point_pcp_handler.h",
+ "p2p_star_pcp_handler.h",
+ "payload_manager.h",
+ "pcp.h",
+ "pcp_handler.h",
+ "pcp_manager.h",
+ "service_controller.h",
+ "service_controller_router.h",
+ "webrtc_bwu_handler.h",
+ "webrtc_endpoint_channel.h",
+ "wifi_lan_bwu_handler.h",
+ "wifi_lan_endpoint_channel.h",
+ "wifi_lan_service_info.h",
+ ],
+ compatible_with = ["//buildenv/target:non_prod"],
+ copts = ["-DCORE_ADAPTER_DLL"],
+ defines = ["NO_WEBRTC"],
+ visibility = [
+ "//third_party/nearby/connections:__pkg__",
+ "//third_party/nearby/connections/implementation/fuzzers:__pkg__",
+ ],
+ deps = [
+ ":message_lite",
+ "//third_party/absl/base:core_headers",
+ "//third_party/absl/container:btree",
+ "//third_party/absl/container:flat_hash_map",
+ "//third_party/absl/container:flat_hash_set",
+ "//third_party/absl/functional:bind_front",
+ "//third_party/absl/memory",
+ "//third_party/absl/strings",
+ "//third_party/absl/time",
+ "//third_party/absl/types:span",
+ "//third_party/nearby/connections/implementation/proto:offline_wire_formats_portable_proto",
+ "//third_party/nearby/connections:core_types",
+ "//third_party/nearby/connections/implementation/mediums",
+ "//third_party/nearby/connections/implementation/mediums:utils",
+ "//third_party/nearby/internal/platform/implementation:comm",
+ "//third_party/nearby/internal/platform:base",
+ "//third_party/nearby/internal/platform:cancellation_flag",
+ "//third_party/nearby/internal/platform:error_code_recorder",
+ "//third_party/nearby/internal/platform:util",
+ "//third_party/nearby/internal/platform:comm",
+ "//third_party/nearby/internal/platform:logging",
+ "//third_party/nearby/internal/platform:types",
+ "//third_party/nearby/internal/analytics",
+ "//third_party/nearby/proto:connections_enums_portable_proto",
+ "//third_party/ukey2",
+ ],
+)
+
+cc_library(
+ name = "message_lite",
+ hdrs = [
+ "message_lite.h",
+ ],
+ compatible_with = ["//buildenv/target:non_prod"],
+ visibility = [
+ "//third_party/nearby/connections:__subpackages__",
+ ],
+ deps = [
+ "//net/proto2/public:proto2_lite",
+ ],
+)
+
+cc_library(
+ name = "internal_test",
+ testonly = True,
+ srcs = [
+ "offline_simulation_user.cc",
+ "simulation_user.cc",
+ ],
+ hdrs = [
+ "mock_service_controller.h",
+ "mock_service_controller_router.h",
+ "offline_simulation_user.h",
+ "simulation_user.h",
+ ],
+ defines = ["NO_WEBRTC"],
+ visibility = [
+ "//third_party/nearby/connections:__subpackages__",
+ ],
+ deps = [
+ ":internal",
+ "//testing/base/public:gunit_for_library_testonly",
+ "//third_party/absl/functional:bind_front",
+ "//third_party/absl/strings",
+ "//third_party/nearby/connections:core_types",
+ "//third_party/nearby/internal/platform:base",
+ "//third_party/nearby/internal/platform:test_util",
+ "//third_party/nearby/internal/platform:types",
+ ],
+)
+
+cc_test(
+ name = "core_internal_test",
+ size = "small",
+ timeout = "moderate",
+ srcs = [
+ "base_endpoint_channel_test.cc",
+ "base_pcp_handler_test.cc",
+ "ble_advertisement_test.cc",
+ "bluetooth_device_name_test.cc",
+ "bwu_manager_test.cc",
+ "client_proxy_test.cc",
+ "encryption_runner_test.cc",
+ "endpoint_channel_manager_test.cc",
+ "endpoint_manager_test.cc",
+ "injected_bluetooth_device_store_test.cc",
+ "internal_payload_factory_test.cc",
+ "offline_frames_test.cc",
+ "offline_frames_validator_test.cc",
+ "offline_service_controller_test.cc",
+ "p2p_cluster_pcp_handler_test.cc",
+ "payload_manager_test.cc",
+ "pcp_manager_test.cc",
+ "service_controller_router_test.cc",
+ "wifi_lan_service_info_test.cc",
+ ],
+ defines = ["NO_WEBRTC"],
+ shard_count = 16,
+ deps = [
+ ":internal",
+ ":internal_test",
+ "//testing/base/public:gunit",
+ "//testing/base/public:gunit_main",
+ "//third_party/absl/container:flat_hash_set",
+ "//third_party/absl/strings",
+ "//third_party/absl/synchronization",
+ "//third_party/absl/time",
+ "//third_party/absl/types:span",
+ "//third_party/nearby/connections/implementation/proto:offline_wire_formats_portable_proto",
+ "//third_party/nearby/connections:core_types",
+ "//third_party/nearby/connections/implementation/mediums",
+ "//third_party/nearby/connections/implementation/mediums:utils",
+ "//third_party/nearby/internal/platform:base",
+ "//third_party/nearby/internal/platform:test_util",
+ "//third_party/nearby/internal/platform/implementation/g3", # build_cleaner: keep
+ "//third_party/nearby/internal/platform:comm",
+ "//third_party/nearby/internal/platform:logging",
+ "//third_party/nearby/internal/platform:types",
+ "//third_party/nearby/internal/analytics",
+ "//third_party/nearby/proto:connections_enums_portable_proto",
+ "//third_party/ukey2",
+ ],
+)
diff --git a/chromium/third_party/nearby/src/connections/implementation/base_bwu_handler.h b/chromium/third_party/nearby/src/connections/implementation/base_bwu_handler.h
new file mode 100644
index 00000000000..390cc7fe482
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/base_bwu_handler.h
@@ -0,0 +1,58 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_BASE_BWU_HANDLER_H_
+#define CORE_INTERNAL_BASE_BWU_HANDLER_H_
+
+#include <cstdint>
+#include <memory>
+#include <string>
+
+#include "absl/container/flat_hash_map.h"
+#include "absl/time/clock.h"
+#include "connections/implementation/bwu_handler.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/endpoint_channel_manager.h"
+#include "internal/platform/cancelable_alarm.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/scheduled_executor.h"
+#include "internal/platform/single_thread_executor.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+class BaseBwuHandler : public BwuHandler {
+ public:
+ using ClientIntroduction = BwuNegotiationFrame::ClientIntroduction;
+
+ BaseBwuHandler(EndpointChannelManager& channel_manager,
+ BwuNotifications bwu_notifications)
+ : channel_manager_(&channel_manager),
+ bwu_notifications_(std::move(bwu_notifications)) {}
+ ~BaseBwuHandler() override = default;
+
+ protected:
+ // Represents the incoming Socket the Initiator has gotten after initializing
+ // its upgraded bandwidth medium.
+ EndpointChannelManager* GetEndpointChannelManager();
+ EndpointChannelManager* channel_manager_;
+ BwuNotifications bwu_notifications_;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_BASE_BWU_HANDLER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/base_endpoint_channel.cc b/chromium/third_party/nearby/src/connections/implementation/base_endpoint_channel.cc
new file mode 100644
index 00000000000..ea04f9eeb4e
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/base_endpoint_channel.cc
@@ -0,0 +1,401 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/base_endpoint_channel.h"
+
+#include <cassert>
+
+#include "absl/strings/escaping.h"
+#include "absl/strings/str_cat.h"
+#include "connections/implementation/offline_frames.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/mutex.h"
+#include "internal/platform/mutex_lock.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+namespace {
+
+std::int32_t BytesToInt(const ByteArray& bytes) {
+ const char* int_bytes = bytes.data();
+
+ std::int32_t result = 0;
+ result |= (static_cast<std::int32_t>(int_bytes[0]) & 0x0FF) << 24;
+ result |= (static_cast<std::int32_t>(int_bytes[1]) & 0x0FF) << 16;
+ result |= (static_cast<std::int32_t>(int_bytes[2]) & 0x0FF) << 8;
+ result |= (static_cast<std::int32_t>(int_bytes[3]) & 0x0FF);
+
+ return result;
+}
+
+ByteArray IntToBytes(std::int32_t value) {
+ char int_bytes[sizeof(std::int32_t)];
+ int_bytes[0] = static_cast<char>((value >> 24) & 0x0FF);
+ int_bytes[1] = static_cast<char>((value >> 16) & 0x0FF);
+ int_bytes[2] = static_cast<char>((value >> 8) & 0x0FF);
+ int_bytes[3] = static_cast<char>((value)&0x0FF);
+
+ return ByteArray(int_bytes, sizeof(int_bytes));
+}
+
+ExceptionOr<ByteArray> ReadExactly(InputStream* reader, std::int64_t size) {
+ ByteArray buffer(size);
+ std::int64_t current_pos = 0;
+
+ while (current_pos < size) {
+ ExceptionOr<ByteArray> read_bytes = reader->Read(size - current_pos);
+ if (!read_bytes.ok()) {
+ return read_bytes;
+ }
+ ByteArray result = read_bytes.result();
+
+ if (result.Empty()) {
+ NEARBY_LOGS(WARNING) << __func__ << ": Empty result when reading bytes.";
+ return ExceptionOr<ByteArray>(Exception::kIo);
+ }
+
+ buffer.CopyAt(current_pos, result);
+ current_pos += result.size();
+ }
+
+ return ExceptionOr<ByteArray>(std::move(buffer));
+}
+
+ExceptionOr<std::int32_t> ReadInt(InputStream* reader) {
+ ExceptionOr<ByteArray> read_bytes = ReadExactly(reader, sizeof(std::int32_t));
+ if (!read_bytes.ok()) {
+ return ExceptionOr<std::int32_t>(read_bytes.exception());
+ }
+ return ExceptionOr<std::int32_t>(BytesToInt(std::move(read_bytes.result())));
+}
+
+Exception WriteInt(OutputStream* writer, std::int32_t value) {
+ return writer->Write(IntToBytes(value));
+}
+
+} // namespace
+
+BaseEndpointChannel::BaseEndpointChannel(const std::string& channel_name,
+ InputStream* reader,
+ OutputStream* writer)
+ : BaseEndpointChannel(
+ channel_name, reader, writer,
+ // TODO(edwinwu): Below values should be retrieved from a base socket,
+ // the #MediumSocket in Android counterpart, from which all the
+ // derived medium sockets should dervied, and implement the supported
+ // values and leave the default values in base #MediumSocket.
+ /*ConnectionTechnology*/
+ proto::connections::CONNECTION_TECHNOLOGY_UNKNOWN_TECHNOLOGY,
+ /*ConnectionBand*/ proto::connections::CONNECTION_BAND_UNKNOWN_BAND,
+ /*frequency*/ -1,
+ /*try_count*/ 0) {}
+
+BaseEndpointChannel::BaseEndpointChannel(
+ const std::string& channel_name, InputStream* reader, OutputStream* writer,
+ proto::connections::ConnectionTechnology technology,
+ proto::connections::ConnectionBand band, int frequency, int try_count)
+ : channel_name_(channel_name),
+ reader_(reader),
+ writer_(writer),
+ technology_(technology),
+ band_(band),
+ frequency_(frequency),
+ try_count_(try_count) {}
+
+ExceptionOr<ByteArray> BaseEndpointChannel::Read() {
+ ByteArray result;
+ {
+ MutexLock lock(&reader_mutex_);
+
+ ExceptionOr<std::int32_t> read_int = ReadInt(reader_);
+ if (!read_int.ok()) {
+ return ExceptionOr<ByteArray>(read_int.exception());
+ }
+
+ if (read_int.result() < 0 || read_int.result() > kMaxAllowedReadBytes) {
+ NEARBY_LOGS(WARNING) << __func__ << ": Read an invalid number of bytes: "
+ << read_int.result();
+ return ExceptionOr<ByteArray>(Exception::kIo);
+ }
+
+ ExceptionOr<ByteArray> read_bytes = ReadExactly(reader_, read_int.result());
+ if (!read_bytes.ok()) {
+ return read_bytes;
+ }
+ result = std::move(read_bytes.result());
+ }
+
+ {
+ MutexLock crypto_lock(&crypto_mutex_);
+ if (IsEncryptionEnabledLocked()) {
+ // If encryption is enabled, decode the message.
+ std::string input(std::move(result));
+ std::unique_ptr<std::string> decrypted_data =
+ crypto_context_->DecodeMessageFromPeer(input);
+ if (decrypted_data) {
+ result = ByteArray(std::move(*decrypted_data));
+ } else {
+ // It could be a protocol race, where remote party sends a KEEP_ALIVE
+ // before encryption is setup on their side, and we receive it after
+ // we switched to encryption mode.
+ // In this case, we verify that message is indeed a valid KEEP_ALIVE,
+ // and let it through if it is, otherwise message is erased.
+ // TODO(apolyudov): verify this happens at most once per session.
+ result = {};
+ auto parsed = parser::FromBytes(ByteArray(input));
+ if (parsed.ok()) {
+ if (parser::GetFrameType(parsed.result()) == V1Frame::KEEP_ALIVE) {
+ NEARBY_LOGS(INFO)
+ << __func__
+ << ": Read unencrypted KEEP_ALIVE on encrypted channel.";
+ result = ByteArray(input);
+ } else {
+ NEARBY_LOGS(WARNING)
+ << __func__ << ": Read unexpected unencrypted frame of type "
+ << parser::GetFrameType(parsed.result());
+ }
+ } else {
+ NEARBY_LOGS(WARNING)
+ << __func__ << ": Unable to parse data as unencrypted message.";
+ }
+ }
+ if (result.Empty()) {
+ NEARBY_LOGS(WARNING) << __func__ << ": Unable to parse read result.";
+ return ExceptionOr<ByteArray>(Exception::kInvalidProtocolBuffer);
+ }
+ }
+ }
+
+ {
+ MutexLock lock(&last_read_mutex_);
+ last_read_timestamp_ = SystemClock::ElapsedRealtime();
+ }
+ return ExceptionOr<ByteArray>(result);
+}
+
+Exception BaseEndpointChannel::Write(const ByteArray& data) {
+ {
+ MutexLock pause_lock(&is_paused_mutex_);
+ if (is_paused_) {
+ BlockUntilUnpaused();
+ }
+ }
+
+ ByteArray encrypted_data;
+ const ByteArray* data_to_write = &data;
+ {
+ // Holding both mutexes is necessary to prevent the keep alive and payload
+ // threads from writing encrypted messages out of order which causes a
+ // failure to decrypt on the reader side. However we need to release the
+ // crypto lock after encrypting to ensure read decryption is not blocked.
+ MutexLock lock(&writer_mutex_);
+ {
+ MutexLock crypto_lock(&crypto_mutex_);
+ if (IsEncryptionEnabledLocked()) {
+ // If encryption is enabled, encode the message.
+ std::unique_ptr<std::string> encrypted =
+ crypto_context_->EncodeMessageToPeer(std::string(data));
+ if (!encrypted) {
+ NEARBY_LOGS(WARNING) << __func__ << ": Failed to encrypt data.";
+ return {Exception::kIo};
+ }
+ encrypted_data = ByteArray(std::move(*encrypted));
+ data_to_write = &encrypted_data;
+ }
+ }
+
+ Exception write_exception =
+ WriteInt(writer_, static_cast<std::int32_t>(data_to_write->size()));
+ if (write_exception.Raised()) {
+ NEARBY_LOGS(WARNING) << __func__ << ": Failed to write header: "
+ << write_exception.value;
+ return write_exception;
+ }
+ write_exception = writer_->Write(*data_to_write);
+ if (write_exception.Raised()) {
+ NEARBY_LOGS(WARNING) << __func__ << ": Failed to write data: "
+ << write_exception.value;
+ return write_exception;
+ }
+ Exception flush_exception = writer_->Flush();
+ if (flush_exception.Raised()) {
+ NEARBY_LOGS(WARNING) << __func__ << ": Failed to flush writer: "
+ << flush_exception.value;
+ return flush_exception;
+ }
+ }
+
+ {
+ MutexLock lock(&last_write_mutex_);
+ last_write_timestamp_ = SystemClock::ElapsedRealtime();
+ }
+ return {Exception::kSuccess};
+}
+
+void BaseEndpointChannel::Close() {
+ {
+ // In case channel is paused, resume it first thing.
+ MutexLock lock(&is_paused_mutex_);
+ UnblockPausedWriter();
+ }
+ CloseIo();
+ CloseImpl();
+}
+
+void BaseEndpointChannel::CloseIo() {
+ // Keep this method dedicated to reader and writer handling an nothing else.
+ {
+ // Do not take reader_mutex_ here: read may be in progress, and it will
+ // deadlock. Calling Close() with Read() in progress will terminate the
+ // IO and Read() will proceed normally (with Exception::kIo).
+ Exception exception = reader_->Close();
+ if (!exception.Ok()) {
+ NEARBY_LOGS(WARNING) << __func__
+ << ": Exception closing reader: " << exception.value;
+ }
+ }
+ {
+ // Do not take writer_mutex_ here: write may be in progress, and it will
+ // deadlock. Calling Close() with Write() in progress will terminate the
+ // IO and Write() will proceed normally (with Exception::kIo).
+ Exception exception = writer_->Close();
+ if (!exception.Ok()) {
+ NEARBY_LOGS(WARNING) << __func__
+ << ": Exception closing writer: " << exception.value;
+ }
+ }
+}
+
+void BaseEndpointChannel::SetAnalyticsRecorder(
+ analytics::AnalyticsRecorder* analytics_recorder,
+ const std::string& endpoint_id) {
+ analytics_recorder_ = analytics_recorder;
+ endpoint_id_ = endpoint_id;
+}
+
+void BaseEndpointChannel::Close(
+ proto::connections::DisconnectionReason reason) {
+ NEARBY_LOGS(INFO) << __func__
+ << ": Closing endpoint channel, reason: " << reason;
+ Close();
+
+ if (analytics_recorder_ != nullptr && !endpoint_id_.empty()) {
+ analytics_recorder_->OnConnectionClosed(endpoint_id_, GetMedium(), reason);
+ }
+}
+
+std::string BaseEndpointChannel::GetType() const {
+ MutexLock crypto_lock(&crypto_mutex_);
+ std::string subtype = IsEncryptionEnabledLocked() ? "ENCRYPTED_" : "";
+ std::string medium = proto::connections::Medium_Name(
+ proto::connections::Medium::UNKNOWN_MEDIUM);
+
+ if (GetMedium() != proto::connections::Medium::UNKNOWN_MEDIUM) {
+ medium =
+ absl::StrCat(subtype, proto::connections::Medium_Name(GetMedium()));
+ }
+ return medium;
+}
+
+std::string BaseEndpointChannel::GetName() const { return channel_name_; }
+
+int BaseEndpointChannel::GetMaxTransmitPacketSize() const {
+ // Return default value if the medium never define it's chunk size.
+ return kDefaultMaxTransmitPacketSize;
+}
+
+void BaseEndpointChannel::EnableEncryption(
+ std::shared_ptr<EncryptionContext> context) {
+ MutexLock crypto_lock(&crypto_mutex_);
+ crypto_context_ = context;
+}
+
+void BaseEndpointChannel::DisableEncryption() {
+ MutexLock crypto_lock(&crypto_mutex_);
+ crypto_context_.reset();
+}
+
+bool BaseEndpointChannel::IsPaused() const {
+ MutexLock lock(&is_paused_mutex_);
+ return is_paused_;
+}
+
+void BaseEndpointChannel::Pause() {
+ MutexLock lock(&is_paused_mutex_);
+ is_paused_ = true;
+}
+
+void BaseEndpointChannel::Resume() {
+ MutexLock lock(&is_paused_mutex_);
+ is_paused_ = false;
+ is_paused_cond_.Notify();
+}
+
+absl::Time BaseEndpointChannel::GetLastReadTimestamp() const {
+ MutexLock lock(&last_read_mutex_);
+ return last_read_timestamp_;
+}
+
+absl::Time BaseEndpointChannel::GetLastWriteTimestamp() const {
+ MutexLock lock(&last_write_mutex_);
+ return last_write_timestamp_;
+}
+
+proto::connections::ConnectionTechnology BaseEndpointChannel::GetTechnology()
+ const {
+ return technology_;
+}
+
+// Returns the used wifi band of this EndpointChannel.
+proto::connections::ConnectionBand BaseEndpointChannel::GetBand() const {
+ return band_;
+}
+
+// Returns the used wifi frequency of this EndpointChannel.
+int BaseEndpointChannel::GetFrequency() const { return frequency_; }
+
+// Returns the try count of this EndpointChannel.
+int BaseEndpointChannel::GetTryCount() const { return try_count_; }
+
+bool BaseEndpointChannel::IsEncryptionEnabledLocked() const {
+ return crypto_context_ != nullptr;
+}
+
+void BaseEndpointChannel::BlockUntilUnpaused() {
+ // For more on how this works, see
+ // https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html
+ while (is_paused_) {
+ Exception wait_succeeded = is_paused_cond_.Wait();
+ if (!wait_succeeded.Ok()) {
+ NEARBY_LOGS(WARNING) << __func__ << ": Failure waiting to unpause: "
+ << wait_succeeded.value;
+ return;
+ }
+ }
+}
+
+void BaseEndpointChannel::UnblockPausedWriter() {
+ // For more on how this works, see
+ // https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html
+ is_paused_ = false;
+ is_paused_cond_.Notify();
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/base_endpoint_channel.h b/chromium/third_party/nearby/src/connections/implementation/base_endpoint_channel.h
new file mode 100644
index 00000000000..563b5d9d077
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/base_endpoint_channel.h
@@ -0,0 +1,179 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_BASE_ENDPOINT_CHANNEL_H_
+#define CORE_INTERNAL_BASE_ENDPOINT_CHANNEL_H_
+
+#include <cstdint>
+#include <memory>
+#include <string>
+
+#include "securegcm/d2d_connection_context_v1.h"
+#include "absl/base/thread_annotations.h"
+#include "connections/implementation/endpoint_channel.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/input_stream.h"
+#include "internal/platform/output_stream.h"
+#include "internal/platform/atomic_reference.h"
+#include "internal/platform/condition_variable.h"
+#include "internal/platform/mutex.h"
+#include "internal/platform/system_clock.h"
+#include "internal/analytics/analytics_recorder.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+class BaseEndpointChannel : public EndpointChannel {
+ public:
+ BaseEndpointChannel(const std::string& channel_name, InputStream* reader,
+ OutputStream* writer);
+ BaseEndpointChannel(const std::string& channel_name, InputStream* reader,
+ OutputStream* writer,
+ proto::connections::ConnectionTechnology,
+ proto::connections::ConnectionBand band, int frequency,
+ int try_count);
+ ~BaseEndpointChannel() override = default;
+
+ ExceptionOr<ByteArray> Read()
+ ABSL_LOCKS_EXCLUDED(reader_mutex_, crypto_mutex_,
+ last_read_mutex_) override;
+
+ Exception Write(const ByteArray& data)
+ ABSL_LOCKS_EXCLUDED(writer_mutex_, crypto_mutex_) override;
+
+ // Closes this EndpointChannel, without tracking the closure in analytics.
+ void Close() ABSL_LOCKS_EXCLUDED(is_paused_mutex_) override;
+
+ // Closes this EndpointChannel and records the closure with the given reason.
+ void Close(proto::connections::DisconnectionReason reason) override;
+
+ // Returns a one-word type descriptor for the concrete EndpointChannel
+ // implementation that can be used in log messages; eg: BLUETOOTH, BLE,
+ // WIFI.
+ std::string GetType() const override;
+
+ // Returns the name of the EndpointChannel.
+ std::string GetName() const override;
+
+ // Returns the maximum supported transmit packet size(MTU) for the underlying
+ // transport.
+ int GetMaxTransmitPacketSize() const override;
+
+ // Enables encryption on the EndpointChannel.
+ // Should be called after connection is accepted by both parties, and
+ // before entering data phase, where Payloads may be exchanged.
+ void EnableEncryption(std::shared_ptr<EncryptionContext> context) override;
+
+ // Disables encryption on the EndpointChannel.
+ void DisableEncryption() override;
+
+ // True if the EndpointChannel is currently pausing all writes.
+ bool IsPaused() const ABSL_LOCKS_EXCLUDED(is_paused_mutex_) override;
+
+ // Pauses all writes on this EndpointChannel until resume() is called.
+ void Pause() ABSL_LOCKS_EXCLUDED(is_paused_mutex_) override;
+
+ // Resumes any writes on this EndpointChannel that were suspended when pause()
+ // was called.
+ void Resume() ABSL_LOCKS_EXCLUDED(is_paused_mutex_) override;
+
+ // Returns the timestamp (returned by ElapsedRealtime) of the last read from
+ // this endpoint, or -1 if no reads have occurred.
+ absl::Time GetLastReadTimestamp() const
+ ABSL_LOCKS_EXCLUDED(last_read_mutex_) override;
+
+ // Returns the timestamp (returned by ElapsedRealtime) of the last write to
+ // this endpoint, or -1 if no writes have occurred.
+ absl::Time GetLastWriteTimestamp() const
+ ABSL_LOCKS_EXCLUDED(last_write_mutex_) override;
+
+ // Returns the used technology of this EndpointChannel.
+ proto::connections::ConnectionTechnology GetTechnology() const override;
+
+ // Returns the used wifi band of this EndpointChannel.
+ proto::connections::ConnectionBand GetBand() const override;
+
+ // Returns the used wifi frequency of this EndpointChannel.
+ int GetFrequency() const override;
+
+ // Returns the try count of this EndpointChannel.
+ int GetTryCount() const override;
+
+ void SetAnalyticsRecorder(analytics::AnalyticsRecorder* analytics_recorder,
+ const std::string& endpoint_id) override;
+
+ protected:
+ virtual void CloseImpl() = 0;
+
+ private:
+ // Used to sanity check that our frame sizes are reasonable.
+ static constexpr std::int32_t kMaxAllowedReadBytes = 1048576; // 1MB
+
+ // The default maximum transmit unit/packet size.
+ static constexpr int kDefaultMaxTransmitPacketSize = 65536; // 64 KB
+
+ bool IsEncryptionEnabledLocked() const
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(crypto_mutex_);
+ void UnblockPausedWriter() ABSL_EXCLUSIVE_LOCKS_REQUIRED(is_paused_mutex_);
+ void BlockUntilUnpaused() ABSL_EXCLUSIVE_LOCKS_REQUIRED(is_paused_mutex_);
+ void CloseIo() ABSL_NO_THREAD_SAFETY_ANALYSIS;
+
+ // We need a separate mutex to protect read timestamp, because if a read
+ // blocks on IO, we don't want timestamp read access to block too.
+ mutable Mutex last_read_mutex_;
+ absl::Time last_read_timestamp_ ABSL_GUARDED_BY(last_read_mutex_) =
+ absl::InfinitePast();
+
+ // We need a separate mutex to protect write timestamp, because if a write
+ // blocks on IO, we don't want timestamp write access to block too.
+ mutable Mutex last_write_mutex_;
+ absl::Time last_write_timestamp_ ABSL_GUARDED_BY(last_write_mutex_) =
+ absl::InfinitePast();
+
+ const std::string channel_name_;
+
+ // The reader and writer are synchronized independently since we can't have
+ // writes waiting on reads that might potentially block forever.
+ Mutex reader_mutex_;
+ InputStream* reader_ ABSL_PT_GUARDED_BY(reader_mutex_);
+
+ Mutex writer_mutex_;
+ OutputStream* writer_ ABSL_PT_GUARDED_BY(writer_mutex_);
+
+ // An encryptor/decryptor. May be null.
+ mutable Mutex crypto_mutex_;
+ std::shared_ptr<EncryptionContext> crypto_context_
+ ABSL_GUARDED_BY(crypto_mutex_) ABSL_PT_GUARDED_BY(crypto_mutex_);
+
+ mutable Mutex is_paused_mutex_;
+ ConditionVariable is_paused_cond_{&is_paused_mutex_};
+ // If true, writes should block until this has been set to false.
+ bool is_paused_ ABSL_GUARDED_BY(is_paused_mutex_) = false;
+
+ // The medium technology information of this endpoint channel.
+ proto::connections::ConnectionTechnology technology_;
+ proto::connections::ConnectionBand band_;
+ int frequency_;
+ int try_count_;
+
+ analytics::AnalyticsRecorder* analytics_recorder_ = nullptr;
+ std::string endpoint_id_ = "";
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_BASE_ENDPOINT_CHANNEL_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/base_endpoint_channel_test.cc b/chromium/third_party/nearby/src/connections/implementation/base_endpoint_channel_test.cc
new file mode 100644
index 00000000000..18832994898
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/base_endpoint_channel_test.cc
@@ -0,0 +1,410 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/base_endpoint_channel.h"
+
+#include <functional>
+#include <string>
+#include <utility>
+
+#include "securegcm/d2d_connection_context_v1.h"
+#include "securegcm/ukey2_handshake.h"
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "absl/synchronization/mutex.h"
+#include "absl/time/time.h"
+#include "connections/implementation/encryption_runner.h"
+#include "connections/implementation/offline_frames.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/input_stream.h"
+#include "internal/platform/output_stream.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/multi_thread_executor.h"
+#include "internal/platform/pipe.h"
+#include "internal/platform/single_thread_executor.h"
+#include "proto/connections_enums.pb.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+
+using ::location::nearby::proto::connections::DisconnectionReason;
+using ::location::nearby::proto::connections::Medium;
+using EncryptionContext = BaseEndpointChannel::EncryptionContext;
+
+class TestEndpointChannel : public BaseEndpointChannel {
+ public:
+ explicit TestEndpointChannel(InputStream* input, OutputStream* output)
+ : BaseEndpointChannel("channel", input, output) {}
+
+ MOCK_METHOD(Medium, GetMedium, (), (const override));
+ MOCK_METHOD(void, CloseImpl, (), (override));
+};
+
+std::function<void()> MakeDataPump(
+ std::string label, InputStream* input, OutputStream* output,
+ std::function<void(const ByteArray&)> monitor = nullptr) {
+ return [label, input, output, monitor]() {
+ NEARBY_LOGS(INFO) << "streaming data through '" << label << "'";
+ while (true) {
+ auto read_response = input->Read(Pipe::kChunkSize);
+ if (!read_response.ok()) {
+ NEARBY_LOGS(INFO) << "Peer reader closed on '" << label << "'";
+ output->Close();
+ break;
+ }
+ if (monitor) {
+ monitor(read_response.result());
+ }
+ auto write_response = output->Write(read_response.result());
+ if (write_response.Raised()) {
+ NEARBY_LOGS(INFO) << "Peer writer closed on '" << label << "'";
+ input->Close();
+ break;
+ }
+ }
+ NEARBY_LOGS(INFO) << "streaming terminated on '" << label << "'";
+ };
+}
+
+std::function<void(const ByteArray&)> MakeDataMonitor(const std::string& label,
+ std::string* capture,
+ absl::Mutex* mutex) {
+ return [label, capture, mutex](const ByteArray& input) mutable {
+ std::string s = std::string(input);
+ {
+ absl::MutexLock lock(mutex);
+ *capture += s;
+ }
+ NEARBY_LOGS(INFO) << "source='" << label << "'"
+ << "; message='" << s << "'";
+ };
+}
+
+std::pair<std::shared_ptr<EncryptionContext>,
+ std::shared_ptr<EncryptionContext>>
+DoDhKeyExchange(BaseEndpointChannel* channel_a,
+ BaseEndpointChannel* channel_b) {
+ std::shared_ptr<EncryptionContext> context_a;
+ std::shared_ptr<EncryptionContext> context_b;
+ EncryptionRunner crypto_a;
+ EncryptionRunner crypto_b;
+ ClientProxy proxy_a;
+ ClientProxy proxy_b;
+ CountDownLatch latch(2);
+ crypto_a.StartClient(
+ &proxy_a, "endpoint_id", channel_a,
+ {
+ .on_success_cb =
+ [&latch, &context_a](
+ const std::string& endpoint_id,
+ std::unique_ptr<securegcm::UKey2Handshake> ukey2,
+ const std::string& auth_token,
+ const ByteArray& raw_auth_token) {
+ NEARBY_LOGS(INFO) << "client-A side key negotiation done";
+ EXPECT_TRUE(ukey2->VerifyHandshake());
+ auto context = ukey2->ToConnectionContext();
+ EXPECT_NE(context, nullptr);
+ context_a = std::move(context);
+ latch.CountDown();
+ },
+ .on_failure_cb =
+ [&latch](const std::string& endpoint_id,
+ EndpointChannel* channel) {
+ NEARBY_LOGS(INFO) << "client-A side key negotiation failed";
+ latch.CountDown();
+ },
+ });
+ crypto_b.StartServer(
+ &proxy_b, "endpoint_id", channel_b,
+ {
+ .on_success_cb =
+ [&latch, &context_b](
+ const std::string& endpoint_id,
+ std::unique_ptr<securegcm::UKey2Handshake> ukey2,
+ const std::string& auth_token,
+ const ByteArray& raw_auth_token) {
+ NEARBY_LOGS(INFO) << "client-B side key negotiation done";
+ EXPECT_TRUE(ukey2->VerifyHandshake());
+ auto context = ukey2->ToConnectionContext();
+ EXPECT_NE(context, nullptr);
+ context_b = std::move(context);
+ latch.CountDown();
+ },
+ .on_failure_cb =
+ [&latch](const std::string& endpoint_id,
+ EndpointChannel* channel) {
+ NEARBY_LOGS(INFO) << "client-B side key negotiation failed";
+ latch.CountDown();
+ },
+ });
+ EXPECT_TRUE(latch.Await(absl::Milliseconds(5000)).result());
+ return std::make_pair(std::move(context_a), std::move(context_b));
+}
+
+TEST(BaseEndpointChannelTest, ConstructorDestructorWorks) {
+ Pipe pipe;
+ InputStream& input_stream = pipe.GetInputStream();
+ OutputStream& output_stream = pipe.GetOutputStream();
+
+ TestEndpointChannel test_channel(&input_stream, &output_stream);
+}
+
+TEST(BaseEndpointChannelTest, ReadWrite) {
+ // Direct not-encrypted IO.
+ Pipe pipe_a; // channel_a writes to pipe_a, reads from pipe_b.
+ Pipe pipe_b; // channel_b writes to pipe_b, reads from pipe_a.
+ TestEndpointChannel channel_a(&pipe_b.GetInputStream(),
+ &pipe_a.GetOutputStream());
+ TestEndpointChannel channel_b(&pipe_a.GetInputStream(),
+ &pipe_b.GetOutputStream());
+ ByteArray tx_message{"data message"};
+ channel_a.Write(tx_message);
+ ByteArray rx_message = std::move(channel_b.Read().result());
+ EXPECT_EQ(rx_message, tx_message);
+}
+
+TEST(BaseEndpointChannelTest, NotEncryptedReadWriteCanBeIntercepted) {
+ // Not encrypted IO; MITM scenario.
+
+ // Setup test communication environment.
+ absl::Mutex mutex;
+ std::string capture_a;
+ std::string capture_b;
+ Pipe client_a; // Channel "a" writes to client "a", reads from server "a".
+ Pipe client_b; // Channel "b" writes to client "b", reads from server "b".
+ Pipe server_a; // Data pump "a" reads from client "a", writes to server "b".
+ Pipe server_b; // Data pump "b" reads from client "b", writes to server "a".
+ TestEndpointChannel channel_a(&server_a.GetInputStream(),
+ &client_a.GetOutputStream());
+ TestEndpointChannel channel_b(&server_b.GetInputStream(),
+ &client_b.GetOutputStream());
+
+ ON_CALL(channel_a, GetMedium).WillByDefault([]() { return Medium::BLE; });
+ ON_CALL(channel_b, GetMedium).WillByDefault([]() { return Medium::BLE; });
+
+ MultiThreadExecutor executor(2);
+ executor.Execute(MakeDataPump(
+ "pump_a", &client_a.GetInputStream(), &server_b.GetOutputStream(),
+ MakeDataMonitor("monitor_a", &capture_a, &mutex)));
+ executor.Execute(MakeDataPump(
+ "pump_b", &client_b.GetInputStream(), &server_a.GetOutputStream(),
+ MakeDataMonitor("monitor_b", &capture_b, &mutex)));
+
+ EXPECT_EQ(channel_a.GetType(), "BLE");
+ EXPECT_EQ(channel_b.GetType(), "BLE");
+
+ // Start data transfer
+ ByteArray tx_message{"data message"};
+ channel_a.Write(tx_message);
+ ByteArray rx_message = std::move(channel_b.Read().result());
+
+ // Verify expectations.
+ EXPECT_EQ(rx_message, tx_message);
+ {
+ absl::MutexLock lock(&mutex);
+ std::string message{tx_message};
+ EXPECT_TRUE(capture_a.find(message) != std::string::npos ||
+ capture_b.find(message) != std::string::npos);
+ }
+
+ // Shutdown test environment.
+ channel_a.Close(DisconnectionReason::LOCAL_DISCONNECTION);
+ channel_b.Close(DisconnectionReason::REMOTE_DISCONNECTION);
+}
+
+TEST(BaseEndpointChannelTest, EncryptedReadWriteCanNotBeIntercepted) {
+ // Encrypted IO; MITM scenario.
+
+ // Setup test communication environment.
+ absl::Mutex mutex;
+ std::string capture_a;
+ std::string capture_b;
+ Pipe client_a; // Channel "a" writes to client "a", reads from server "a".
+ Pipe client_b; // Channel "b" writes to client "b", reads from server "b".
+ Pipe server_a; // Data pump "a" reads from client "a", writes to server "b".
+ Pipe server_b; // Data pump "b" reads from client "b", writes to server "a".
+ TestEndpointChannel channel_a(&server_a.GetInputStream(),
+ &client_a.GetOutputStream());
+ TestEndpointChannel channel_b(&server_b.GetInputStream(),
+ &client_b.GetOutputStream());
+
+ ON_CALL(channel_a, GetMedium).WillByDefault([]() {
+ return Medium::BLUETOOTH;
+ });
+ ON_CALL(channel_b, GetMedium).WillByDefault([]() {
+ return Medium::BLUETOOTH;
+ });
+
+ MultiThreadExecutor executor(2);
+ executor.Execute(MakeDataPump(
+ "pump_a", &client_a.GetInputStream(), &server_b.GetOutputStream(),
+ MakeDataMonitor("monitor_a", &capture_a, &mutex)));
+ executor.Execute(MakeDataPump(
+ "pump_b", &client_b.GetInputStream(), &server_a.GetOutputStream(),
+ MakeDataMonitor("monitor_b", &capture_b, &mutex)));
+
+ // Run DH key exchange; setup encryption contexts for channels.
+ auto [context_a, context_b] = DoDhKeyExchange(&channel_a, &channel_b);
+ ASSERT_NE(context_a, nullptr);
+ ASSERT_NE(context_b, nullptr);
+ channel_a.EnableEncryption(context_a);
+ channel_b.EnableEncryption(context_b);
+
+ EXPECT_EQ(channel_a.GetType(), "ENCRYPTED_BLUETOOTH");
+ EXPECT_EQ(channel_b.GetType(), "ENCRYPTED_BLUETOOTH");
+
+ // Start data transfer
+ ByteArray tx_message{"data message"};
+ channel_a.Write(tx_message);
+ ByteArray rx_message = std::move(channel_b.Read().result());
+
+ // Verify expectations.
+ EXPECT_EQ(rx_message, tx_message);
+ {
+ absl::MutexLock lock(&mutex);
+ std::string message{tx_message};
+ EXPECT_TRUE(capture_a.find(message) == std::string::npos &&
+ capture_b.find(message) == std::string::npos);
+ }
+
+ // Shutdown test environment.
+ channel_a.Close(DisconnectionReason::LOCAL_DISCONNECTION);
+ channel_b.Close(DisconnectionReason::REMOTE_DISCONNECTION);
+}
+
+TEST(BaseEndpointChannelTest, CanBesuspendedAndResumed) {
+ // Setup test communication environment.
+ Pipe pipe_a; // channel_a writes to pipe_a, reads from pipe_b.
+ Pipe pipe_b; // channel_b writes to pipe_b, reads from pipe_a.
+ TestEndpointChannel channel_a(&pipe_b.GetInputStream(),
+ &pipe_a.GetOutputStream());
+ TestEndpointChannel channel_b(&pipe_a.GetInputStream(),
+ &pipe_b.GetOutputStream());
+
+ ON_CALL(channel_a, GetMedium).WillByDefault([]() {
+ return Medium::WIFI_LAN;
+ });
+ ON_CALL(channel_b, GetMedium).WillByDefault([]() {
+ return Medium::WIFI_LAN;
+ });
+
+ EXPECT_EQ(channel_a.GetType(), "WIFI_LAN");
+ EXPECT_EQ(channel_b.GetType(), "WIFI_LAN");
+
+ // Start data transfer
+ ByteArray tx_message{"data message"};
+ ByteArray more_message{"more data"};
+ channel_a.Write(tx_message);
+ ByteArray rx_message = std::move(channel_b.Read().result());
+
+ // Pause and make sure reader blocks.
+ MultiThreadExecutor pause_resume_executor(2);
+ channel_a.Pause();
+ pause_resume_executor.Execute([&channel_a, &more_message]() {
+ // Write will block until channel is resumed, or closed.
+ EXPECT_TRUE(channel_a.Write(more_message).Ok());
+ });
+ CountDownLatch latch(1);
+ ByteArray read_more;
+ pause_resume_executor.Execute([&channel_b, &read_more, &latch]() {
+ // Read will block until channel is resumed, or closed.
+ auto response = channel_b.Read();
+ EXPECT_TRUE(response.ok());
+ read_more = std::move(response.result());
+ latch.CountDown();
+ });
+ absl::SleepFor(absl::Milliseconds(500));
+ EXPECT_TRUE(read_more.Empty());
+
+ // Resume; verify that data transfer comepleted.
+ channel_a.Resume();
+ EXPECT_TRUE(latch.Await(absl::Milliseconds(1000)).result());
+ EXPECT_EQ(read_more, more_message);
+
+ // Shutdown test environment.
+ channel_a.Close(DisconnectionReason::LOCAL_DISCONNECTION);
+ channel_b.Close(DisconnectionReason::REMOTE_DISCONNECTION);
+}
+
+TEST(BaseEndpointChannelTest, ReadAfterInputStreamClosed) {
+ Pipe pipe;
+ InputStream& input_stream = pipe.GetInputStream();
+ OutputStream& output_stream = pipe.GetOutputStream();
+
+ TestEndpointChannel test_channel(&input_stream, &output_stream);
+
+ // Close the output stream before trying to read from the input.
+ output_stream.Close();
+
+ // Trying to read should fail gracefully with an IO error.
+ ExceptionOr<ByteArray> read_data = test_channel.Read();
+
+ ASSERT_FALSE(read_data.ok());
+ ASSERT_TRUE(read_data.GetException().Raised(Exception::kIo));
+}
+
+TEST(BaseEndpointChannelTest, ReadUnencryptedFrameOnEncryptedChannel) {
+ // Setup test communication environment.
+ Pipe pipe_a; // channel_a writes to pipe_a, reads from pipe_b.
+ Pipe pipe_b; // channel_b writes to pipe_b, reads from pipe_a.
+ TestEndpointChannel channel_a(&pipe_b.GetInputStream(),
+ &pipe_a.GetOutputStream());
+ TestEndpointChannel channel_b(&pipe_a.GetInputStream(),
+ &pipe_b.GetOutputStream());
+
+ ON_CALL(channel_a, GetMedium).WillByDefault([]() {
+ return Medium::BLUETOOTH;
+ });
+ ON_CALL(channel_b, GetMedium).WillByDefault([]() {
+ return Medium::BLUETOOTH;
+ });
+
+ // Run DH key exchange; setup encryption contexts for channels. But only
+ // encrypt |channel_b|.
+ auto [context_a, context_b] = DoDhKeyExchange(&channel_a, &channel_b);
+ ASSERT_NE(context_a, nullptr);
+ ASSERT_NE(context_b, nullptr);
+ channel_b.EnableEncryption(context_b);
+
+ EXPECT_EQ(channel_a.GetType(), "BLUETOOTH");
+ EXPECT_EQ(channel_b.GetType(), "ENCRYPTED_BLUETOOTH");
+
+ // An unencrypted KeepAlive should succeed.
+ ByteArray keep_alive_message = parser::ForKeepAlive();
+ channel_a.Write(keep_alive_message);
+ ExceptionOr<ByteArray> result = channel_b.Read();
+ EXPECT_TRUE(result.ok());
+ EXPECT_EQ(result.result(), keep_alive_message);
+
+ // An unencrypted data frame should fail.
+ ByteArray tx_message{"data message"};
+ channel_a.Write(tx_message);
+ result = channel_b.Read();
+ EXPECT_FALSE(result.ok());
+ EXPECT_EQ(result.exception(), Exception::kInvalidProtocolBuffer);
+
+ // Shutdown test environment.
+ channel_a.Close(DisconnectionReason::LOCAL_DISCONNECTION);
+ channel_b.Close(DisconnectionReason::REMOTE_DISCONNECTION);
+}
+
+} // namespace
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/base_pcp_handler.cc b/chromium/third_party/nearby/src/connections/implementation/base_pcp_handler.cc
new file mode 100644
index 00000000000..313ac26cbc0
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/base_pcp_handler.cc
@@ -0,0 +1,1579 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/base_pcp_handler.h"
+
+#include <cassert>
+#include <cinttypes>
+#include <cstdlib>
+#include <limits>
+#include <memory>
+
+#include "securegcm/d2d_connection_context_v1.h"
+#include "securegcm/ukey2_handshake.h"
+#include "absl/container/flat_hash_set.h"
+#include "absl/strings/escaping.h"
+#include "absl/types/span.h"
+#include "connections/implementation/mediums/utils.h"
+#include "connections/implementation/offline_frames.h"
+#include "connections/implementation/pcp_handler.h"
+#include "internal/platform/base64_utils.h"
+#include "internal/platform/bluetooth_utils.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/system_clock.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+using ::location::nearby::proto::connections::Medium;
+using ::securegcm::UKey2Handshake;
+
+constexpr absl::Duration BasePcpHandler::kConnectionRequestReadTimeout;
+constexpr absl::Duration BasePcpHandler::kRejectedConnectionCloseDelay;
+
+BasePcpHandler::BasePcpHandler(Mediums* mediums,
+ EndpointManager* endpoint_manager,
+ EndpointChannelManager* channel_manager,
+ BwuManager* bwu_manager, Pcp pcp)
+ : mediums_(mediums),
+ endpoint_manager_(endpoint_manager),
+ channel_manager_(channel_manager),
+ pcp_(pcp),
+ bwu_manager_(bwu_manager) {}
+
+BasePcpHandler::~BasePcpHandler() {
+ NEARBY_LOGS(INFO) << "Initiating shutdown of BasePcpHandler("
+ << strategy_.GetName() << ")";
+ DisconnectFromEndpointManager();
+ // Stop all the ongoing Runnables (as gracefully as possible).
+ NEARBY_LOGS(INFO) << "BasePcpHandler(" << strategy_.GetName()
+ << ") is bringing down executors.";
+ serial_executor_.Shutdown();
+ alarm_executor_.Shutdown();
+ NEARBY_LOGS(INFO) << "BasePcpHandler(" << strategy_.GetName()
+ << ") has shut down.";
+}
+
+void BasePcpHandler::DisconnectFromEndpointManager() {
+ if (stop_.Set(true)) return;
+ NEARBY_LOGS(INFO) << "BasePcpHandler(" << strategy_.GetName()
+ << ") unregister from EPM.";
+ // Unregister ourselves from EPM message dispatcher.
+ endpoint_manager_->UnregisterFrameProcessor(V1Frame::CONNECTION_RESPONSE,
+ this);
+}
+
+Status BasePcpHandler::StartAdvertising(
+ ClientProxy* client, const std::string& service_id,
+ const AdvertisingOptions& advertising_options,
+ const ConnectionRequestInfo& info) {
+ Future<Status> response;
+
+ NEARBY_LOGS(INFO) << "StartAdvertising with supported mediums: "
+ << GetStringValueOfSupportedMediums(advertising_options);
+
+ AdvertisingOptions compatible_advertising_options =
+ advertising_options.CompatibleOptions();
+
+ RunOnPcpHandlerThread(
+ "start-advertising",
+ [this, client, &service_id, &info, &compatible_advertising_options,
+ &response]() RUN_ON_PCP_HANDLER_THREAD() {
+ // The endpoint id inside of the advertisement is different to high
+ // visibility and low visibility mode. In order to decide if client
+ // should grab the high visibility or low visibility id, it needs to
+ // tell client which one right now, before
+ // client#StartedAdvertising.
+ if (ShouldEnterHighVisibilityMode(compatible_advertising_options)) {
+ client->EnterHighVisibilityMode();
+ }
+
+ auto result = StartAdvertisingImpl(
+ client, service_id, client->GetLocalEndpointId(),
+ info.endpoint_info, compatible_advertising_options);
+ if (!result.status.Ok()) {
+ client->ExitHighVisibilityMode();
+ response.Set(result.status);
+ return;
+ }
+
+ // Now that we've succeeded, mark the client as advertising.
+ // Save the advertising options for local reference in later process
+ // like upgrading bandwidth.
+ advertising_listener_ = info.listener;
+ client->StartedAdvertising(service_id, GetStrategy(), info.listener,
+ absl::MakeSpan(result.mediums),
+ compatible_advertising_options);
+ response.Set({Status::kSuccess});
+ });
+ return WaitForResult(absl::StrCat("StartAdvertising(", service_id, ")"),
+ client->GetClientId(), &response);
+}
+
+void BasePcpHandler::StopAdvertising(ClientProxy* client) {
+ NEARBY_LOGS(INFO) << "StopAdvertising local_endpoint_id="
+ << client->GetLocalEndpointId();
+ CountDownLatch latch(1);
+ RunOnPcpHandlerThread("stop-advertising",
+ [this, client, &latch]() RUN_ON_PCP_HANDLER_THREAD() {
+ StopAdvertisingImpl(client);
+ client->StoppedAdvertising();
+ latch.CountDown();
+ });
+ WaitForLatch("StopAdvertising", &latch);
+}
+
+std::string BasePcpHandler::GetStringValueOfSupportedMediums(
+ const ConnectionOptions& connection_options) const {
+ std::ostringstream result;
+ OptionsAllowed(connection_options.allowed, result);
+ return result.str();
+}
+
+std::string BasePcpHandler::GetStringValueOfSupportedMediums(
+ const AdvertisingOptions& advertising_options) const {
+ std::ostringstream result;
+ OptionsAllowed(advertising_options.allowed, result);
+ return result.str();
+}
+
+std::string BasePcpHandler::GetStringValueOfSupportedMediums(
+ const DiscoveryOptions& discovery_options) const {
+ std::ostringstream result;
+ OptionsAllowed(discovery_options.allowed, result);
+ return result.str();
+}
+
+void BasePcpHandler::OptionsAllowed(const BooleanMediumSelector& allowed,
+ std::ostringstream& result) const {
+ result << "{ ";
+ if (allowed.bluetooth) {
+ result << proto::connections::Medium_Name(Medium::BLUETOOTH) << " ";
+ }
+ if (allowed.ble) {
+ result << proto::connections::Medium_Name(Medium::BLE) << " ";
+ }
+ if (allowed.web_rtc) {
+ result << proto::connections::Medium_Name(Medium::WEB_RTC) << " ";
+ }
+ if (allowed.wifi_lan) {
+ result << proto::connections::Medium_Name(Medium::WIFI_LAN) << " ";
+ }
+ result << "}";
+}
+
+bool BasePcpHandler::ShouldEnterHighVisibilityMode(
+ const AdvertisingOptions& advertising_options) {
+ return !advertising_options.low_power &&
+ advertising_options.allowed.bluetooth;
+}
+
+BooleanMediumSelector BasePcpHandler::ComputeIntersectionOfSupportedMediums(
+ const PendingConnectionInfo& connection_info) {
+ absl::flat_hash_set<Medium> intersection;
+ auto their_mediums = connection_info.supported_mediums;
+
+ // If no supported mediums were set, use the default upgrade medium.
+ if (their_mediums.empty()) {
+ their_mediums.push_back(GetDefaultUpgradeMedium());
+ }
+
+ for (Medium my_medium : GetConnectionMediumsByPriority()) {
+ if (std::find(their_mediums.begin(), their_mediums.end(), my_medium) !=
+ their_mediums.end()) {
+ // We use advertising options as a proxy to whether or not the local
+ // client does want to enable a WebRTC upgrade.
+ if (my_medium == location::nearby::proto::connections::Medium::WEB_RTC) {
+ AdvertisingOptions advertising_options =
+ connection_info.client->GetAdvertisingOptions();
+
+ if (!advertising_options.enable_webrtc_listening &&
+ !advertising_options.allowed.web_rtc) {
+ // The local client does not allow WebRTC for listening or upgrades,
+ // ignore.
+ continue;
+ }
+ }
+
+ intersection.emplace(my_medium);
+ }
+ }
+
+ // Not using designated initializers here since the VS C++ compiler errors
+ // out indicating that MediumSelector<bool> is not an aggregate
+ MediumSelector<bool> mediumSelector{};
+ mediumSelector.bluetooth = intersection.contains(Medium::BLUETOOTH);
+ mediumSelector.ble = intersection.contains(Medium::BLE);
+ mediumSelector.web_rtc = intersection.contains(Medium::WEB_RTC);
+ mediumSelector.wifi_lan = intersection.contains(Medium::WIFI_LAN);
+ return mediumSelector;
+}
+
+Status BasePcpHandler::StartDiscovery(ClientProxy* client,
+ const std::string& service_id,
+ const DiscoveryOptions& discovery_options,
+ const DiscoveryListener& listener) {
+ Future<Status> response;
+
+ NEARBY_LOGS(INFO) << "StartDiscovery with supported mediums:"
+ << GetStringValueOfSupportedMediums(discovery_options);
+ RunOnPcpHandlerThread(
+ "start-discovery", [this, client, service_id, discovery_options,
+ &listener, &response]() RUN_ON_PCP_HANDLER_THREAD() {
+ // Ask the implementation to attempt to start discovery.
+ auto result = StartDiscoveryImpl(client, service_id, discovery_options);
+ if (!result.status.Ok()) {
+ response.Set(result.status);
+ return;
+ }
+
+ // Now that we've succeeded, mark the client as discovering and clear
+ // out any old endpoints we had discovered.
+ discovered_endpoints_.clear();
+ client->StartedDiscovery(service_id, GetStrategy(), listener,
+ absl::MakeSpan(result.mediums),
+ discovery_options);
+ response.Set({Status::kSuccess});
+ });
+ return WaitForResult(absl::StrCat("StartDiscovery(", service_id, ")"),
+ client->GetClientId(), &response);
+}
+
+void BasePcpHandler::StopDiscovery(ClientProxy* client) {
+ CountDownLatch latch(1);
+ RunOnPcpHandlerThread("stop-discovery",
+ [this, client, &latch]() RUN_ON_PCP_HANDLER_THREAD() {
+ StopDiscoveryImpl(client);
+ client->StoppedDiscovery();
+ latch.CountDown();
+ });
+
+ WaitForLatch("StopDiscovery", &latch);
+}
+
+void BasePcpHandler::InjectEndpoint(
+ ClientProxy* client, const std::string& service_id,
+ const OutOfBandConnectionMetadata& metadata) {
+ CountDownLatch latch(1);
+ RunOnPcpHandlerThread("inject-endpoint",
+ [this, client, service_id, metadata, &latch]()
+ RUN_ON_PCP_HANDLER_THREAD() {
+ InjectEndpointImpl(client, service_id, metadata);
+ latch.CountDown();
+ });
+
+ WaitForLatch(absl::StrCat("InjectEndpoint(", service_id, ")"), &latch);
+}
+
+void BasePcpHandler::WaitForLatch(const std::string& method_name,
+ CountDownLatch* latch) {
+ Exception await_exception = latch->Await();
+ if (!await_exception.Ok()) {
+ if (await_exception.Raised(Exception::kTimeout)) {
+ NEARBY_LOGS(INFO) << "Blocked in " << method_name;
+ }
+ }
+}
+
+Status BasePcpHandler::WaitForResult(const std::string& method_name,
+ std::int64_t client_id,
+ Future<Status>* future) {
+ if (!future) {
+ NEARBY_LOGS(INFO) << "No future to wait for; return with error";
+ return {Status::kError};
+ }
+ NEARBY_LOGS(INFO) << "Waiting for future to complete: " << method_name;
+ ExceptionOr<Status> result = future->Get();
+ if (!result.ok()) {
+ NEARBY_LOGS(INFO) << "Future:[" << method_name
+ << "] completed with exception:" << result.exception();
+ return {Status::kError};
+ }
+ NEARBY_LOGS(INFO) << "Future:[" << method_name
+ << "] completed with status:" << result.result().value;
+ return result.result();
+}
+
+void BasePcpHandler::RunOnPcpHandlerThread(const std::string& name,
+ Runnable runnable) {
+ serial_executor_.Execute(name, std::move(runnable));
+}
+
+EncryptionRunner::ResultListener BasePcpHandler::GetResultListener() {
+ return {
+ .on_success_cb =
+ [this](const std::string& endpoint_id,
+ std::unique_ptr<UKey2Handshake> ukey2,
+ const std::string& auth_token,
+ const ByteArray& raw_auth_token) {
+ RunOnPcpHandlerThread(
+ "encryption-success",
+ [this, endpoint_id, raw_ukey2 = ukey2.release(), auth_token,
+ raw_auth_token]() RUN_ON_PCP_HANDLER_THREAD() mutable {
+ OnEncryptionSuccessRunnable(
+ endpoint_id, std::unique_ptr<UKey2Handshake>(raw_ukey2),
+ auth_token, raw_auth_token);
+ });
+ },
+ .on_failure_cb =
+ [this](const std::string& endpoint_id, EndpointChannel* channel) {
+ RunOnPcpHandlerThread(
+ "encryption-failure",
+ [this, endpoint_id, channel]() RUN_ON_PCP_HANDLER_THREAD() {
+ NEARBY_LOGS(ERROR)
+ << "Encryption failed for endpoint_id=" << endpoint_id
+ << " on medium="
+ << proto::connections::Medium_Name(channel->GetMedium());
+ OnEncryptionFailureRunnable(endpoint_id, channel);
+ });
+ },
+ };
+}
+
+void BasePcpHandler::OnEncryptionSuccessRunnable(
+ const std::string& endpoint_id, std::unique_ptr<UKey2Handshake> ukey2,
+ const std::string& auth_token, const ByteArray& raw_auth_token) {
+ // Quick fail if we've been removed from pending connections while we were
+ // busy running UKEY2.
+ auto it = pending_connections_.find(endpoint_id);
+ if (it == pending_connections_.end()) {
+ NEARBY_LOGS(INFO)
+ << "Connection not found on UKEY negotination complete; endpoint_id="
+ << endpoint_id;
+ return;
+ }
+
+ BasePcpHandler::PendingConnectionInfo& connection_info = it->second;
+ Medium medium = connection_info.channel->GetMedium();
+
+ if (!ukey2) {
+ // Fail early, if there is no crypto context.
+ ProcessPreConnectionInitiationFailure(
+ connection_info.client, medium, endpoint_id,
+ connection_info.channel.get(), connection_info.is_incoming,
+ connection_info.start_time, {Status::kEndpointIoError},
+ connection_info.result.lock().get());
+ return;
+ }
+
+ connection_info.SetCryptoContext(std::move(ukey2));
+ connection_info.connection_token = GetHashedConnectionToken(raw_auth_token);
+ NEARBY_LOGS(INFO)
+ << "Register encrypted connection; wait for response; endpoint_id="
+ << endpoint_id;
+
+ // Set ourselves up so that we receive all acceptance/rejection messages
+ endpoint_manager_->RegisterFrameProcessor(V1Frame::CONNECTION_RESPONSE, this);
+
+ // Now we register our endpoint so that we can listen for both sides to
+ // accept.
+ LogConnectionAttemptSuccess(endpoint_id, connection_info);
+ endpoint_manager_->RegisterEndpoint(
+ connection_info.client, endpoint_id,
+ {
+ .remote_endpoint_info = connection_info.remote_endpoint_info,
+ .authentication_token = auth_token,
+ .raw_authentication_token = raw_auth_token,
+ .is_incoming_connection = connection_info.is_incoming,
+ },
+ {
+ {
+ connection_info.connection_options.strategy,
+ ComputeIntersectionOfSupportedMediums(connection_info),
+ },
+ connection_info.connection_options.auto_upgrade_bandwidth,
+ connection_info.connection_options.enforce_topology_constraints,
+ connection_info.connection_options.low_power,
+ connection_info.connection_options.enable_bluetooth_listening,
+ connection_info.connection_options.enable_webrtc_listening,
+ connection_info.connection_options.is_out_of_band_connection,
+ connection_info.connection_options.remote_bluetooth_mac_address,
+ connection_info.connection_options.fast_advertisement_service_uuid,
+ connection_info.connection_options.keep_alive_interval_millis,
+ connection_info.connection_options.keep_alive_timeout_millis,
+ },
+ std::move(connection_info.channel), connection_info.listener,
+ connection_info.connection_token);
+
+ if (auto future_status = connection_info.result.lock()) {
+ NEARBY_LOGS(INFO) << "Connection established; Finalising future OK.";
+ future_status->Set({Status::kSuccess});
+ connection_info.result.reset();
+ }
+}
+
+void BasePcpHandler::OnEncryptionFailureRunnable(
+ const std::string& endpoint_id, EndpointChannel* endpoint_channel) {
+ auto it = pending_connections_.find(endpoint_id);
+ if (it == pending_connections_.end()) {
+ NEARBY_LOGS(INFO)
+ << "Connection not found on UKEY negotination complete; endpoint_id="
+ << endpoint_id;
+ return;
+ }
+
+ BasePcpHandler::PendingConnectionInfo& info = it->second;
+ // We had a bug here, caused by a race with EncryptionRunner. We now verify
+ // the EndpointChannel to avoid it. In a simultaneous connection, we clean
+ // up one of the two EndpointChannels and then update our pendingConnections
+ // with the winning channel's state. Closing a channel that was in the
+ // middle of EncryptionRunner would trigger onEncryptionFailed, and, since
+ // the map had already updated with the winning EndpointChannel, we closed
+ // it too by accident.
+ if (*endpoint_channel != *info.channel) {
+ NEARBY_LOGS(INFO) << "Not destroying channel [mismatch]: passed="
+ << endpoint_channel->GetName()
+ << "; expected=" << info.channel->GetName();
+ return;
+ }
+
+ ProcessPreConnectionInitiationFailure(
+ info.client, info.channel->GetMedium(), endpoint_id, info.channel.get(),
+ info.is_incoming, info.start_time, {Status::kEndpointIoError},
+ info.result.lock().get());
+}
+
+Status BasePcpHandler::RequestConnection(
+ ClientProxy* client, const std::string& endpoint_id,
+ const ConnectionRequestInfo& info,
+ const ConnectionOptions& connection_options) {
+ auto result = std::make_shared<Future<Status>>();
+ RunOnPcpHandlerThread(
+ "request-connection",
+ [this, client, &info, connection_options, endpoint_id,
+ result]() RUN_ON_PCP_HANDLER_THREAD() {
+ absl::Time start_time = SystemClock::ElapsedRealtime();
+
+ // If we already have a pending connection, then we shouldn't allow any
+ // more outgoing connections to this endpoint.
+ if (pending_connections_.count(endpoint_id)) {
+ NEARBY_LOGS(INFO)
+ << "In requestConnection(), connection requested with "
+ "endpoint(id="
+ << endpoint_id
+ << "), but we already have a pending connection with them.";
+ result->Set({Status::kAlreadyConnectedToEndpoint});
+ return;
+ }
+
+ // If our child class says we can't send any more outgoing connections,
+ // listen to them.
+ if (ShouldEnforceTopologyConstraints(client->GetAdvertisingOptions()) &&
+ !CanSendOutgoingConnection(client)) {
+ NEARBY_LOGS(INFO)
+ << "In requestConnection(), client=" << client->GetClientId()
+ << " attempted a connection with endpoint(id=" << endpoint_id
+ << "), but outgoing connections are disallowed";
+ result->Set({Status::kOutOfOrderApiCall});
+ return;
+ }
+
+ DiscoveredEndpoint* endpoint = GetDiscoveredEndpoint(endpoint_id);
+ if (endpoint == nullptr) {
+ NEARBY_LOGS(INFO)
+ << "Discovered endpoint not found: endpoint_id=" << endpoint_id;
+ result->Set({Status::kEndpointUnknown});
+ return;
+ }
+
+ auto remote_bluetooth_mac_address = BluetoothUtils::ToString(
+ connection_options.remote_bluetooth_mac_address);
+ if (!remote_bluetooth_mac_address.empty()) {
+ if (AppendRemoteBluetoothMacAddressEndpoint(
+ endpoint_id, remote_bluetooth_mac_address,
+ client->GetDiscoveryOptions()))
+ NEARBY_LOGS(INFO)
+ << "Appended remote Bluetooth MAC Address endpoint ["
+ << remote_bluetooth_mac_address << "]";
+ }
+
+ if (AppendWebRTCEndpoint(endpoint_id, client->GetDiscoveryOptions()))
+ NEARBY_LOGS(INFO) << "Appended Web RTC endpoint.";
+
+ auto discovered_endpoints = GetDiscoveredEndpoints(endpoint_id);
+ std::unique_ptr<EndpointChannel> channel;
+ ConnectImplResult connect_impl_result;
+
+ for (auto connect_endpoint : discovered_endpoints) {
+ if (!MediumSupportedByClientOptions(connect_endpoint->medium,
+ connection_options))
+ continue;
+ connect_impl_result = ConnectImpl(client, connect_endpoint);
+ if (connect_impl_result.status.Ok()) {
+ channel = std::move(connect_impl_result.endpoint_channel);
+ break;
+ }
+ }
+
+ Medium channel_medium =
+ channel ? channel->GetMedium() : Medium::UNKNOWN_MEDIUM;
+ if (channel == nullptr) {
+ NEARBY_LOGS(INFO)
+ << "Endpoint channel not available: endpoint_id=" << endpoint_id;
+ ProcessPreConnectionInitiationFailure(
+ client, channel_medium, endpoint_id, channel.get(),
+ /* is_incoming = */ false, start_time, connect_impl_result.status,
+ result.get());
+ return;
+ }
+
+ NEARBY_LOGS(INFO)
+ << "In requestConnection(), wrote ConnectionRequestFrame "
+ "to endpoint_id="
+ << endpoint_id;
+ // Generate the nonce to use for this connection.
+ std::int32_t nonce = prng_.NextInt32();
+
+ // The first message we have to send, after connecting, is to tell the
+ // endpoint about ourselves.
+ Exception write_exception = WriteConnectionRequestFrame(
+ channel.get(), client->GetLocalEndpointId(), info.endpoint_info,
+ nonce, GetSupportedConnectionMediumsByPriority(connection_options),
+ connection_options.keep_alive_interval_millis,
+ connection_options.keep_alive_timeout_millis);
+ if (!write_exception.Ok()) {
+ NEARBY_LOGS(INFO) << "Failed to send connection request: endpoint_id="
+ << endpoint_id;
+ ProcessPreConnectionInitiationFailure(
+ client, channel_medium, endpoint_id, channel.get(),
+ /* is_incoming = */ false, start_time, {Status::kEndpointIoError},
+ result.get());
+ return;
+ }
+
+ NEARBY_LOGS(INFO) << "Adding connection to pending set: endpoint_id="
+ << endpoint_id;
+
+ // We've successfully connected to the device, and are now about to jump
+ // on to the EncryptionRunner thread to start running our encryption
+ // protocol. We'll mark ourselves as pending in case we get another call
+ // to RequestConnection or OnIncomingConnection, so that we can cancel
+ // the connection if needed.
+ // Not using designated initializers here since the VS C++ compiler
+ // errors out indicating that MediumSelector<bool> is not an aggregate
+ PendingConnectionInfo pendingConnectionInfo{};
+ pendingConnectionInfo.client = client;
+ pendingConnectionInfo.remote_endpoint_info = endpoint->endpoint_info;
+ pendingConnectionInfo.nonce = nonce;
+ pendingConnectionInfo.is_incoming = false;
+ pendingConnectionInfo.start_time = start_time;
+ pendingConnectionInfo.listener = info.listener;
+ pendingConnectionInfo.connection_options = connection_options;
+ pendingConnectionInfo.result = result;
+ pendingConnectionInfo.channel = std::move(channel);
+
+ EndpointChannel* endpoint_channel =
+ pending_connections_
+ .emplace(endpoint_id, std::move(pendingConnectionInfo))
+ .first->second.channel.get();
+
+ NEARBY_LOGS(INFO) << "Initiating secure connection: endpoint_id="
+ << endpoint_id;
+ // Next, we'll set up encryption. When it's done, our future will return
+ // and RequestConnection() will finish.
+ encryption_runner_.StartClient(client, endpoint_id, endpoint_channel,
+ GetResultListener());
+ });
+ NEARBY_LOGS(INFO) << "Waiting for connection to complete: endpoint_id="
+ << endpoint_id;
+ auto status =
+ WaitForResult(absl::StrCat("RequestConnection(", endpoint_id, ")"),
+ client->GetClientId(), result.get());
+ NEARBY_LOGS(INFO) << "Wait is complete: endpoint_id=" << endpoint_id
+ << "; status=" << status.value;
+ return status;
+}
+
+bool BasePcpHandler::MediumSupportedByClientOptions(
+ const proto::connections::Medium& medium,
+ const ConnectionOptions& client_options) const {
+ for (auto supported_medium : client_options.GetMediums()) {
+ if (medium == supported_medium) {
+ return true;
+ }
+ }
+ return false;
+}
+
+// Get ordered supported connection medium based on local advertising/discovery
+// option.
+std::vector<proto::connections::Medium>
+BasePcpHandler::GetSupportedConnectionMediumsByPriority(
+ const ConnectionOptions& local_connection_option) {
+ std::vector<proto::connections::Medium> supported_mediums_by_priority;
+ for (auto medium_by_priority : GetConnectionMediumsByPriority()) {
+ if (MediumSupportedByClientOptions(medium_by_priority,
+ local_connection_option)) {
+ supported_mediums_by_priority.push_back(medium_by_priority);
+ }
+ }
+ return supported_mediums_by_priority;
+}
+
+// Get any single discovered endpoint for a given endpoint_id.
+BasePcpHandler::DiscoveredEndpoint* BasePcpHandler::GetDiscoveredEndpoint(
+ const std::string& endpoint_id) {
+ auto it = discovered_endpoints_.find(endpoint_id);
+ if (it == discovered_endpoints_.end()) {
+ return nullptr;
+ }
+ return it->second.get();
+}
+
+std::vector<BasePcpHandler::DiscoveredEndpoint*>
+BasePcpHandler::GetDiscoveredEndpoints(const std::string& endpoint_id) {
+ std::vector<BasePcpHandler::DiscoveredEndpoint*> result;
+ auto it = discovered_endpoints_.equal_range(endpoint_id);
+ for (auto item = it.first; item != it.second; item++) {
+ result.push_back(item->second.get());
+ }
+ std::sort(result.begin(), result.end(),
+ [this](DiscoveredEndpoint* a, DiscoveredEndpoint* b) -> bool {
+ return IsPreferred(*a, *b);
+ });
+
+ return result;
+}
+
+std::vector<BasePcpHandler::DiscoveredEndpoint*>
+BasePcpHandler::GetDiscoveredEndpoints(
+ const proto::connections::Medium medium) {
+ std::vector<BasePcpHandler::DiscoveredEndpoint*> result;
+ for (const auto& item : discovered_endpoints_) {
+ if (item.second->medium == medium) {
+ result.push_back(item.second.get());
+ }
+ }
+ return result;
+}
+
+mediums::WebrtcPeerId BasePcpHandler::CreatePeerIdFromAdvertisement(
+ const std::string& service_id, const std::string& endpoint_id,
+ const ByteArray& endpoint_info) {
+ std::string seed =
+ absl::StrCat(service_id, endpoint_id, std::string(endpoint_info));
+ return mediums::WebrtcPeerId::FromSeed(ByteArray(std::move(seed)));
+}
+
+bool BasePcpHandler::HasOutgoingConnections(ClientProxy* client) const {
+ for (const auto& item : pending_connections_) {
+ auto& connection = item.second;
+ if (!connection.is_incoming) {
+ return true;
+ }
+ }
+ return client->GetNumOutgoingConnections() > 0;
+}
+
+bool BasePcpHandler::HasIncomingConnections(ClientProxy* client) const {
+ for (const auto& item : pending_connections_) {
+ auto& connection = item.second;
+ if (connection.is_incoming) {
+ return true;
+ }
+ }
+ return client->GetNumIncomingConnections() > 0;
+}
+
+bool BasePcpHandler::CanSendOutgoingConnection(ClientProxy* client) const {
+ return true;
+}
+
+bool BasePcpHandler::CanReceiveIncomingConnection(ClientProxy* client) const {
+ return true;
+}
+
+Exception BasePcpHandler::WriteConnectionRequestFrame(
+ EndpointChannel* endpoint_channel, const std::string& local_endpoint_id,
+ const ByteArray& local_endpoint_info, std::int32_t nonce,
+ const std::vector<proto::connections::Medium>& supported_mediums,
+ std::int32_t keep_alive_interval_millis,
+ std::int32_t keep_alive_timeout_millis) {
+ return endpoint_channel->Write(parser::ForConnectionRequest(
+ local_endpoint_id, local_endpoint_info, nonce, /*supports_5_ghz =*/false,
+ /*bssid=*/std::string{}, supported_mediums, keep_alive_interval_millis,
+ keep_alive_timeout_millis));
+}
+
+void BasePcpHandler::ProcessPreConnectionInitiationFailure(
+ ClientProxy* client, Medium medium, const std::string& endpoint_id,
+ EndpointChannel* channel, bool is_incoming, absl::Time start_time,
+ Status status, Future<Status>* result) {
+ if (channel != nullptr) {
+ channel->Close();
+ }
+
+ if (result != nullptr) {
+ NEARBY_LOGS(INFO) << "Connection failed; aborting future";
+ result->Set(status);
+ }
+
+ LogConnectionAttemptFailure(client, medium, endpoint_id, is_incoming,
+ start_time, channel);
+ // result is hold inside a swapper, and saved in PendingConnectionInfo.
+ // PendingConnectionInfo destructor will clear the memory of SettableFuture
+ // shared_ptr for result.
+ pending_connections_.erase(endpoint_id);
+}
+
+void BasePcpHandler::ProcessPreConnectionResultFailure(
+ ClientProxy* client, const std::string& endpoint_id) {
+ auto item = pending_connections_.extract(endpoint_id);
+ endpoint_manager_->DiscardEndpoint(client, endpoint_id);
+ client->OnConnectionRejected(endpoint_id, {Status::kError});
+}
+
+bool BasePcpHandler::ShouldEnforceTopologyConstraints(
+ const AdvertisingOptions& local_advertising_options) const {
+ // Topology constraints only matter for the advertiser.
+ // For discoverers, we'll always enforce them.
+ if (local_advertising_options.strategy.IsNone()) {
+ return true;
+ }
+
+ return local_advertising_options.enforce_topology_constraints;
+}
+
+bool BasePcpHandler::AutoUpgradeBandwidth(
+ const AdvertisingOptions& local_advertising_options) const {
+ if (local_advertising_options.strategy.IsNone()) {
+ return true;
+ }
+
+ return local_advertising_options.auto_upgrade_bandwidth;
+}
+
+Status BasePcpHandler::AcceptConnection(
+ ClientProxy* client, const std::string& endpoint_id,
+ const PayloadListener& payload_listener) {
+ Future<Status> response;
+ RunOnPcpHandlerThread(
+ "accept-connection", [this, client, endpoint_id, payload_listener,
+ &response]() RUN_ON_PCP_HANDLER_THREAD() {
+ NEARBY_LOGS(INFO) << "AcceptConnection: endpoint_id=" << endpoint_id;
+ if (!pending_connections_.count(endpoint_id)) {
+ NEARBY_LOGS(INFO)
+ << "AcceptConnection: no pending connection for endpoint_id="
+ << endpoint_id;
+
+ response.Set({Status::kEndpointUnknown});
+ return;
+ }
+ auto& connection_info = pending_connections_[endpoint_id];
+
+ // By this point in the flow, connection_info.channel has been
+ // nulled out because ownership of that EndpointChannel was passed on to
+ // EndpointChannelManager via a call to
+ // EndpointManager::registerEndpoint(), so we now need to get access to
+ // the EndpointChannel from the authoritative owner.
+ std::shared_ptr<EndpointChannel> channel =
+ channel_manager_->GetChannelForEndpoint(endpoint_id);
+ if (channel == nullptr) {
+ NEARBY_LOGS(ERROR) << "Channel destroyed before Accept; bring down "
+ "connection: endpoint_id="
+ << endpoint_id;
+ ProcessPreConnectionResultFailure(client, endpoint_id);
+ response.Set({Status::kEndpointUnknown});
+ return;
+ }
+
+ Exception write_exception =
+ channel->Write(parser::ForConnectionResponse(Status::kSuccess));
+ if (!write_exception.Ok()) {
+ NEARBY_LOGS(INFO)
+ << "AcceptConnection: failed to send response: endpoint_id="
+ << endpoint_id;
+ ProcessPreConnectionResultFailure(client, endpoint_id);
+ response.Set({Status::kEndpointIoError});
+ return;
+ }
+
+ NEARBY_LOGS(INFO) << "AcceptConnection: accepting locally: endpoint_id="
+ << endpoint_id;
+ connection_info.LocalEndpointAcceptedConnection(endpoint_id,
+ payload_listener);
+ EvaluateConnectionResult(client, endpoint_id,
+ false /* can_close_immediately */);
+ response.Set({Status::kSuccess});
+ });
+
+ return WaitForResult(absl::StrCat("AcceptConnection(", endpoint_id, ")"),
+ client->GetClientId(), &response);
+}
+
+Status BasePcpHandler::RejectConnection(ClientProxy* client,
+ const std::string& endpoint_id) {
+ Future<Status> response;
+ RunOnPcpHandlerThread(
+ "reject-connection",
+ [this, client, endpoint_id, &response]() RUN_ON_PCP_HANDLER_THREAD() {
+ NEARBY_LOG(INFO, "RejectConnection: id=%s", endpoint_id.c_str());
+ if (!pending_connections_.count(endpoint_id)) {
+ NEARBY_LOGS(INFO)
+ << "RejectConnection: no pending connection for endpoint_id="
+ << endpoint_id;
+ response.Set({Status::kEndpointUnknown});
+ return;
+ }
+ auto& connection_info = pending_connections_[endpoint_id];
+
+ // By this point in the flow, connection_info->endpoint_channel_ has
+ // been nulled out because ownership of that EndpointChannel was passed
+ // on to EndpointChannelManager via a call to
+ // EndpointManager::registerEndpoint(), so we now need to get access to
+ // the EndpointChannel from the authoritative owner.
+ std::shared_ptr<EndpointChannel> channel =
+ channel_manager_->GetChannelForEndpoint(endpoint_id);
+ if (channel == nullptr) {
+ NEARBY_LOGS(ERROR)
+ << "Channel destroyed before Reject; bring down connection: "
+ "endpoint_id="
+ << endpoint_id;
+ ProcessPreConnectionResultFailure(client, endpoint_id);
+ response.Set({Status::kEndpointUnknown});
+ return;
+ }
+
+ Exception write_exception = channel->Write(
+ parser::ForConnectionResponse(Status::kConnectionRejected));
+ if (!write_exception.Ok()) {
+ NEARBY_LOGS(INFO)
+ << "RejectConnection: failed to send response: endpoint_id="
+ << endpoint_id;
+ ProcessPreConnectionResultFailure(client, endpoint_id);
+ response.Set({Status::kEndpointIoError});
+ return;
+ }
+
+ NEARBY_LOGS(INFO) << "RejectConnection: rejecting locally: endpoint_id="
+ << endpoint_id;
+ connection_info.LocalEndpointRejectedConnection(endpoint_id);
+ EvaluateConnectionResult(client, endpoint_id,
+ false /* can_close_immediately */);
+ response.Set({Status::kSuccess});
+ });
+
+ return WaitForResult(absl::StrCat("RejectConnection(", endpoint_id, ")"),
+ client->GetClientId(), &response);
+}
+
+void BasePcpHandler::OnIncomingFrame(OfflineFrame& frame,
+ const std::string& endpoint_id,
+ ClientProxy* client,
+ proto::connections::Medium medium) {
+ CountDownLatch latch(1);
+ RunOnPcpHandlerThread(
+ "incoming-frame",
+ [this, client, endpoint_id, frame, &latch]() RUN_ON_PCP_HANDLER_THREAD() {
+ NEARBY_LOGS(INFO) << "OnConnectionResponse: endpoint_id="
+ << endpoint_id;
+
+ if (client->HasRemoteEndpointResponded(endpoint_id)) {
+ NEARBY_LOGS(INFO)
+ << "OnConnectionResponse: already handled; endpoint_id="
+ << endpoint_id;
+ return;
+ }
+
+ const ConnectionResponseFrame& connection_response =
+ frame.v1().connection_response();
+
+ // For backward compatible, here still check both status and
+ // response parameters until the response feature is roll out in all
+ // supported devices.
+ bool accepted = false;
+ if (connection_response.has_response()) {
+ accepted =
+ connection_response.response() == ConnectionResponseFrame::ACCEPT;
+ } else {
+ accepted = connection_response.status() == Status::kSuccess;
+ }
+ if (accepted) {
+ NEARBY_LOGS(INFO)
+ << "OnConnectionResponse: remote accepted; endpoint_id="
+ << endpoint_id;
+ client->RemoteEndpointAcceptedConnection(endpoint_id);
+ } else {
+ NEARBY_LOGS(INFO)
+ << "OnConnectionResponse: remote rejected; endpoint_id="
+ << endpoint_id << "; status=" << connection_response.status();
+ client->RemoteEndpointRejectedConnection(endpoint_id);
+ }
+
+ EvaluateConnectionResult(client, endpoint_id,
+ /* can_close_immediately= */ true);
+
+ latch.CountDown();
+ });
+ WaitForLatch("OnIncomingFrame()", &latch);
+}
+
+void BasePcpHandler::OnEndpointDisconnect(ClientProxy* client,
+ const std::string& endpoint_id,
+ CountDownLatch barrier) {
+ if (stop_.Get()) {
+ barrier.CountDown();
+ return;
+ }
+ RunOnPcpHandlerThread("on-endpoint-disconnect",
+ [this, client, endpoint_id, barrier]()
+ RUN_ON_PCP_HANDLER_THREAD() mutable {
+ auto item = pending_alarms_.find(endpoint_id);
+ if (item != pending_alarms_.end()) {
+ auto& alarm = item->second;
+ alarm.Cancel();
+ pending_alarms_.erase(item);
+ }
+ ProcessPreConnectionResultFailure(client,
+ endpoint_id);
+ barrier.CountDown();
+ });
+}
+
+BluetoothDevice BasePcpHandler::GetRemoteBluetoothDevice(
+ const std::string& remote_bluetooth_mac_address) {
+ return mediums_->GetBluetoothClassic().GetRemoteDevice(
+ remote_bluetooth_mac_address);
+}
+
+void BasePcpHandler::OnEndpointFound(
+ ClientProxy* client, std::shared_ptr<DiscoveredEndpoint> endpoint) {
+ // Check if we've seen this endpoint ID before.
+ std::string& endpoint_id = endpoint->endpoint_id;
+ NEARBY_LOGS(INFO) << "OnEndpointFound: id=" << endpoint_id << " [enter]";
+
+ auto range = discovered_endpoints_.equal_range(endpoint->endpoint_id);
+
+ DiscoveredEndpoint* owned_endpoint = nullptr;
+ for (auto& item = range.first; item != range.second; ++item) {
+ auto& discovered_endpoint = item->second;
+ if (discovered_endpoint->medium != endpoint->medium) continue;
+ // Check if there was a info change. If there was, report the previous
+ // endpoint as lost.
+ if (discovered_endpoint->endpoint_info != endpoint->endpoint_info) {
+ OnEndpointLost(client, *discovered_endpoint);
+ discovered_endpoint = endpoint; // Replace endpoint.
+ OnEndpointFound(client, std::move(endpoint));
+ return;
+ } else {
+ owned_endpoint = endpoint.get();
+ break;
+ }
+ }
+
+ if (!owned_endpoint) {
+ owned_endpoint =
+ discovered_endpoints_.emplace(endpoint_id, std::move(endpoint))
+ ->second.get();
+ }
+
+ // Range is empty: this is the first endpoint we discovered so far.
+ // Report this endpoint_id to client.
+ if (range.first == range.second) {
+ NEARBY_LOGS(INFO) << "Adding new endpoint: endpoint_id=" << endpoint_id;
+ // And, as it's the first time, report it to the client.
+ client->OnEndpointFound(
+ owned_endpoint->service_id, owned_endpoint->endpoint_id,
+ owned_endpoint->endpoint_info, owned_endpoint->medium);
+ } else {
+ NEARBY_LOGS(INFO) << "Adding new medium for endpoint: endpoint_id="
+ << endpoint_id << "; medium=" << owned_endpoint->medium;
+ }
+}
+
+void BasePcpHandler::OnEndpointLost(
+ ClientProxy* client, const BasePcpHandler::DiscoveredEndpoint& endpoint) {
+ // Look up the DiscoveredEndpoint we have in our cache.
+ const auto* discovered_endpoint = GetDiscoveredEndpoint(endpoint.endpoint_id);
+ if (discovered_endpoint == nullptr) {
+ NEARBY_LOGS(INFO) << "No previous endpoint (nothing to lose): endpoint_id="
+ << endpoint.endpoint_id;
+ return;
+ }
+
+ // Validate that the cached endpoint has the same info as the one reported as
+ // onLost. If the info differs, then no-op. This likely means that the remote
+ // device changed their info. We reported onFound for the new info and are
+ // just now figuring out that we lost the old info.
+ if (discovered_endpoint->endpoint_info != endpoint.endpoint_info) {
+ NEARBY_LOGS(INFO) << "Previous endpoint name mismatch; passed="
+ << absl::BytesToHexString(endpoint.endpoint_info.data())
+ << "; expected="
+ << absl::BytesToHexString(
+ discovered_endpoint->endpoint_info.data());
+ return;
+ }
+
+ auto item = discovered_endpoints_.extract(endpoint.endpoint_id);
+ if (!discovered_endpoints_.count(endpoint.endpoint_id)) {
+ client->OnEndpointLost(endpoint.service_id, endpoint.endpoint_id);
+ }
+}
+
+bool BasePcpHandler::IsPreferred(
+ const BasePcpHandler::DiscoveredEndpoint& new_endpoint,
+ const BasePcpHandler::DiscoveredEndpoint& old_endpoint) {
+ std::vector<proto::connections::Medium> mediums =
+ GetConnectionMediumsByPriority();
+ // As we iterate through the list of mediums, we see if we run into the new
+ // endpoint's medium or the old endpoint's medium first.
+ for (const auto& medium : mediums) {
+ if (medium == new_endpoint.medium) {
+ // The new endpoint's medium came first. It's preferred!
+ return true;
+ }
+
+ if (medium == old_endpoint.medium) {
+ // The old endpoint's medium came first. Stick with the old endpoint!
+ return false;
+ }
+ }
+ std::string medium_string;
+ for (const auto& medium : mediums) {
+ absl::StrAppend(&medium_string, medium, "; ");
+ }
+ NEARBY_LOGS(ERROR) << "Failed to find either " << new_endpoint.medium
+ << " or " << old_endpoint.medium
+ << " in the list of locally supported mediums despite "
+ "expecting to find both, when deciding which medium "
+ << medium_string << " is preferred.";
+ return false;
+}
+
+Exception BasePcpHandler::OnIncomingConnection(
+ ClientProxy* client, const ByteArray& remote_endpoint_info,
+ std::unique_ptr<EndpointChannel> channel,
+ proto::connections::Medium medium) {
+ absl::Time start_time = SystemClock::ElapsedRealtime();
+
+ // Fixes an NPE in ClientProxy.OnConnectionAccepted. The crash happened when
+ // the client stopped advertising and we nulled out state, followed by an
+ // incoming connection where we attempted to check that state.
+ if (!client->IsAdvertising()) {
+ NEARBY_LOGS(WARNING) << "Ignoring incoming connection on medium "
+ << proto::connections::Medium_Name(
+ channel->GetMedium())
+ << " because client=" << client->GetClientId()
+ << " is no longer advertising.";
+ return {Exception::kIo};
+ }
+
+ // Endpoints connecting to us will always tell us about themselves first.
+ ExceptionOr<OfflineFrame> wrapped_frame =
+ ReadConnectionRequestFrame(channel.get());
+
+ if (!wrapped_frame.ok()) {
+ if (wrapped_frame.exception()) {
+ NEARBY_LOGS(ERROR)
+ << "Failed to parse incoming connection request; client="
+ << client->GetClientId()
+ << "; device=" << absl::BytesToHexString(remote_endpoint_info.data());
+ ProcessPreConnectionInitiationFailure(
+ client, medium, "", channel.get(),
+ /* is_incoming= */ false, start_time, {Status::kError}, nullptr);
+ return {Exception::kSuccess};
+ }
+ return wrapped_frame.GetException();
+ }
+
+ OfflineFrame& frame = wrapped_frame.result();
+ const ConnectionRequestFrame& connection_request =
+ frame.v1().connection_request();
+ NEARBY_LOGS(INFO) << "In onIncomingConnection("
+ << proto::connections::Medium_Name(channel->GetMedium())
+ << ") for client=" << client->GetClientId()
+ << ", read ConnectionRequestFrame from endpoint(id="
+ << connection_request.endpoint_id() << ")";
+ if (client->IsConnectedToEndpoint(connection_request.endpoint_id())) {
+ NEARBY_LOGS(ERROR) << "Incoming connection on medium "
+ << proto::connections::Medium_Name(channel->GetMedium())
+ << " was denied because we're "
+ "already connected to endpoint(id="
+ << connection_request.endpoint_id() << ").";
+ return {Exception::kIo};
+ }
+
+ // If we've already sent out a connection request to this endpoint, then this
+ // is where we need to decide which connection to break.
+ if (BreakTie(client, connection_request.endpoint_id(),
+ connection_request.nonce(), channel.get())) {
+ return {Exception::kSuccess};
+ }
+
+ // If our child class says we can't accept any more incoming connections,
+ // listen to them.
+ if (ShouldEnforceTopologyConstraints(client->GetAdvertisingOptions()) &&
+ !CanReceiveIncomingConnection(client)) {
+ NEARBY_LOGS(ERROR) << "Incoming connections are currently disallowed.";
+ return {Exception::kIo};
+ }
+
+ // The ConnectionRequest frame has two fields that both contain the
+ // EndpointInfo. The legacy field stores it as a string while the newer field
+ // stores it as a byte array. We'll attempt to grab from the newer field, but
+ // will accept the older string if it's all that exists.
+ const ByteArray endpoint_info{connection_request.has_endpoint_info()
+ ? connection_request.endpoint_info()
+ : connection_request.endpoint_name()};
+
+ // Retrieve the keep-alive frame interval and timeout fields. If the frame
+ // doesn't have those fields, we need to get them as default from feature
+ // flags to prevent 0-values causing thread ill.
+ ConnectionOptions connection_options = {.keep_alive_interval_millis = 0,
+ .keep_alive_timeout_millis = 0};
+ if (connection_request.has_keep_alive_interval_millis() &&
+ connection_request.has_keep_alive_timeout_millis()) {
+ connection_options.keep_alive_interval_millis =
+ connection_request.keep_alive_interval_millis();
+ connection_options.keep_alive_timeout_millis =
+ connection_request.keep_alive_timeout_millis();
+ }
+ if (connection_options.keep_alive_interval_millis == 0 ||
+ connection_options.keep_alive_timeout_millis == 0 ||
+ connection_options.keep_alive_interval_millis >=
+ connection_options.keep_alive_timeout_millis) {
+ NEARBY_LOGS(WARNING)
+ << "Incoming connection has wrong keep-alive frame interval="
+ << connection_options.keep_alive_interval_millis
+ << ", timeout=" << connection_options.keep_alive_timeout_millis
+ << " values; correct them as default.",
+ connection_options.keep_alive_interval_millis =
+ FeatureFlags::GetInstance().GetFlags().keep_alive_interval_millis;
+ connection_options.keep_alive_timeout_millis =
+ FeatureFlags::GetInstance().GetFlags().keep_alive_timeout_millis;
+ }
+
+ // We've successfully connected to the device, and are now about to jump on to
+ // the EncryptionRunner thread to start running our encryption protocol. We'll
+ // mark ourselves as pending in case we get another call to RequestConnection
+ // or OnIncomingConnection, so that we can cancel the connection if needed.
+ // Not using designated initializers here since the VS C++ compiler errors
+ // out indicating that MediumSelector<bool> is not an aggregate
+ PendingConnectionInfo pendingConnectionInfo{};
+ pendingConnectionInfo.client = client;
+ pendingConnectionInfo.remote_endpoint_info = endpoint_info;
+ pendingConnectionInfo.nonce = connection_request.nonce();
+ pendingConnectionInfo.is_incoming = true;
+ pendingConnectionInfo.start_time = start_time;
+ pendingConnectionInfo.listener = advertising_listener_;
+ pendingConnectionInfo.connection_options = connection_options;
+ pendingConnectionInfo.supported_mediums =
+ parser::ConnectionRequestMediumsToMediums(connection_request);
+ pendingConnectionInfo.channel = std::move(channel);
+
+ auto* owned_channel = pending_connections_
+ .emplace(connection_request.endpoint_id(),
+ std::move(pendingConnectionInfo))
+ .first->second.channel.get();
+
+ // Next, we'll set up encryption.
+ encryption_runner_.StartServer(client, connection_request.endpoint_id(),
+ owned_channel, GetResultListener());
+ return {Exception::kSuccess};
+}
+
+bool BasePcpHandler::BreakTie(ClientProxy* client,
+ const std::string& endpoint_id,
+ std::int32_t incoming_nonce,
+ EndpointChannel* endpoint_channel) {
+ auto it = pending_connections_.find(endpoint_id);
+ if (it != pending_connections_.end()) {
+ BasePcpHandler::PendingConnectionInfo& info = it->second;
+
+ NEARBY_LOGS(INFO)
+ << "In onIncomingConnection("
+ << proto::connections::Medium_Name(endpoint_channel->GetMedium())
+ << ") for client=" << client->GetClientId()
+ << ", found a collision with endpoint " << endpoint_id
+ << ". We've already sent a connection request to them with nonce "
+ << info.nonce
+ << ", but they're also trying to connect to us with nonce "
+ << incoming_nonce;
+ // Break the lowest connection. In the (extremely) rare case of a tie, break
+ // both.
+ if (info.nonce > incoming_nonce) {
+ // Our connection won! Clean up their connection.
+ endpoint_channel->Close();
+
+ NEARBY_LOGS(INFO) << "In onIncomingConnection("
+ << proto::connections::Medium_Name(
+ endpoint_channel->GetMedium())
+ << ") for client=" << client->GetClientId()
+ << ", cleaned up the collision with endpoint "
+ << endpoint_id << " by closing their channel.";
+ return true;
+ } else if (info.nonce < incoming_nonce) {
+ // Aw, we lost. Clean up our connection, and then we'll let their
+ // connection continue on.
+ ProcessTieBreakLoss(client, endpoint_id, &info);
+ NEARBY_LOGS(INFO)
+ << "In onIncomingConnection("
+ << proto::connections::Medium_Name(endpoint_channel->GetMedium())
+ << ") for client=" << client->GetClientId()
+ << ", cleaned up the collision with endpoint " << endpoint_id
+ << " by closing our channel and notifying our client of the failure.";
+ } else {
+ // Oh. Huh. We both lost. Well, that's awkward. We'll clean up both and
+ // just force the devices to retry.
+ endpoint_channel->Close();
+
+ ProcessTieBreakLoss(client, endpoint_id, &info);
+
+ NEARBY_LOGS(INFO)
+ << "In onIncomingConnection("
+ << proto::connections::Medium_Name(endpoint_channel->GetMedium())
+ << ") for client=" << client->GetClientId()
+ << ", cleaned up the collision with endpoint " << endpoint_id
+ << " by closing both channels. Our nonces were identical, so we "
+ "couldn't decide which channel to use.";
+ return true;
+ }
+ }
+
+ return false;
+}
+
+void BasePcpHandler::ProcessTieBreakLoss(
+ ClientProxy* client, const std::string& endpoint_id,
+ BasePcpHandler::PendingConnectionInfo* info) {
+ ProcessPreConnectionInitiationFailure(
+ client, info->channel->GetMedium(), endpoint_id, info->channel.get(),
+ info->is_incoming, info->start_time, {Status::kEndpointIoError},
+ info->result.lock().get());
+ ProcessPreConnectionResultFailure(client, endpoint_id);
+}
+
+bool BasePcpHandler::AppendRemoteBluetoothMacAddressEndpoint(
+ const std::string& endpoint_id,
+ const std::string& remote_bluetooth_mac_address,
+ const DiscoveryOptions& local_discovery_options) {
+ if (!local_discovery_options.allowed.bluetooth) {
+ return false;
+ }
+
+ auto it = discovered_endpoints_.equal_range(endpoint_id);
+ if (it.first == it.second) {
+ return false;
+ }
+ auto endpoint = it.first->second.get();
+ for (auto item = it.first; item != it.second; item++) {
+ if (item->second->medium == proto::connections::Medium::BLUETOOTH) {
+ NEARBY_LOGS(INFO)
+ << "Cannot append remote Bluetooth MAC Address endpoint, because "
+ "the endpoint has already been found over Bluetooth ["
+ << remote_bluetooth_mac_address << "]";
+ return false;
+ }
+ }
+
+ auto remote_bluetooth_device =
+ GetRemoteBluetoothDevice(remote_bluetooth_mac_address);
+ if (!remote_bluetooth_device.IsValid()) {
+ NEARBY_LOGS(INFO)
+ << "Cannot append remote Bluetooth MAC Address endpoint, because a "
+ "valid Bluetooth device could not be derived ["
+ << remote_bluetooth_mac_address << "]";
+ return false;
+ }
+
+ auto bluetooth_endpoint =
+ std::make_shared<BluetoothEndpoint>(BluetoothEndpoint{
+ {endpoint_id, endpoint->endpoint_info, endpoint->service_id,
+ proto::connections::Medium::BLUETOOTH, WebRtcState::kUnconnectable},
+ remote_bluetooth_device,
+ });
+
+ discovered_endpoints_.emplace(endpoint_id, std::move(bluetooth_endpoint));
+ return true;
+}
+
+bool BasePcpHandler::AppendWebRTCEndpoint(
+ const std::string& endpoint_id,
+ const DiscoveryOptions& local_discovery_options) {
+ if (!local_discovery_options.allowed.web_rtc) {
+ return false;
+ }
+
+ bool should_connect_web_rtc = false;
+ auto it = discovered_endpoints_.equal_range(endpoint_id);
+ if (it.first == it.second) return false;
+ auto endpoint = it.first->second.get();
+ for (auto item = it.first; item != it.second; item++) {
+ if (item->second->web_rtc_state != WebRtcState::kUnconnectable) {
+ should_connect_web_rtc = true;
+ break;
+ }
+ }
+ if (!should_connect_web_rtc) return false;
+
+ auto webrtc_endpoint = std::make_shared<WebRtcEndpoint>(WebRtcEndpoint{
+ {endpoint_id, endpoint->endpoint_info, endpoint->service_id,
+ proto::connections::Medium::WEB_RTC, WebRtcState::kConnectable},
+ CreatePeerIdFromAdvertisement(endpoint->service_id, endpoint->endpoint_id,
+ endpoint->endpoint_info),
+ });
+
+ discovered_endpoints_.emplace(endpoint_id, std::move(webrtc_endpoint));
+ return true;
+}
+
+void BasePcpHandler::EvaluateConnectionResult(ClientProxy* client,
+ const std::string& endpoint_id,
+ bool can_close_immediately) {
+ // Short-circuit immediately if we're not in an actionable state yet. We will
+ // be called again once the other side has made their decision.
+ if (!client->IsConnectionAccepted(endpoint_id) &&
+ !client->IsConnectionRejected(endpoint_id)) {
+ if (!client->HasLocalEndpointResponded(endpoint_id)) {
+ NEARBY_LOGS(INFO)
+ << "ConnectionResult: local client did not respond; endpoint_id="
+ << endpoint_id;
+ } else if (!client->HasRemoteEndpointResponded(endpoint_id)) {
+ NEARBY_LOGS(INFO)
+ << "ConnectionResult: remote client did not respond; endpoint_id="
+ << endpoint_id;
+ }
+ return;
+ }
+
+ // Clean up the endpoint channel from our list of 'pending' connections. It's
+ // no longer pending.
+ auto it = pending_connections_.find(endpoint_id);
+ if (it == pending_connections_.end()) {
+ NEARBY_LOGS(INFO) << "No pending connection to evaluate; endpoint_id="
+ << endpoint_id;
+ return;
+ }
+
+ auto pair = pending_connections_.extract(it);
+ BasePcpHandler::PendingConnectionInfo& connection_info = pair.mapped();
+ bool is_connection_accepted = client->IsConnectionAccepted(endpoint_id);
+
+ Status response_code;
+ if (is_connection_accepted) {
+ NEARBY_LOGS(INFO) << "Pending connection accepted; endpoint_id="
+ << endpoint_id;
+ response_code = {Status::kSuccess};
+
+ // Both sides have accepted, so we can now start talking over encrypted
+ // channels
+ // Now, after both parties accepted connection (presumably after verifying &
+ // matching security tokens), we are allowed to extract the shared key.
+ auto ukey2 = std::move(connection_info.ukey2);
+ bool succeeded = ukey2->VerifyHandshake();
+ CHECK(succeeded); // If this fails, it's a UKEY2 protocol bug.
+ auto context = ukey2->ToConnectionContext();
+ CHECK(context); // there is no way how this can fail, if Verify succeeded.
+ // If it did, it's a UKEY2 protocol bug.
+
+ channel_manager_->EncryptChannelForEndpoint(endpoint_id,
+ std::move(context));
+
+ client->GetAnalyticsRecorder().OnConnectionEstablished(
+ endpoint_id,
+ channel_manager_->GetChannelForEndpoint(endpoint_id)->GetMedium(),
+ connection_info.connection_token);
+ } else {
+ NEARBY_LOGS(INFO) << "Pending connection rejected; endpoint_id="
+ << endpoint_id;
+ response_code = {Status::kConnectionRejected};
+ }
+
+ // Invoke the client callback to let it know of the connection result.
+ if (response_code.Ok()) {
+ client->OnConnectionAccepted(endpoint_id);
+ } else {
+ client->OnConnectionRejected(endpoint_id, response_code);
+ }
+
+ // If the connection failed, clean everything up and short circuit.
+ if (!is_connection_accepted) {
+ // Clean up the channel in EndpointManager if it's no longer required.
+ if (can_close_immediately) {
+ endpoint_manager_->DiscardEndpoint(client, endpoint_id);
+ } else {
+ pending_alarms_.emplace(
+ endpoint_id,
+ CancelableAlarm(
+ "BasePcpHandler.evaluateConnectionResult() delayed close",
+ [this, client, endpoint_id]() {
+ endpoint_manager_->DiscardEndpoint(client, endpoint_id);
+ },
+ kRejectedConnectionCloseDelay, &alarm_executor_));
+ }
+
+ return;
+ }
+
+ // Kick off the bandwidth upgrade for incoming connections.
+ if (connection_info.is_incoming &&
+ AutoUpgradeBandwidth(client->GetAdvertisingOptions())) {
+ bwu_manager_->InitiateBwuForEndpoint(client, endpoint_id);
+ }
+}
+
+ExceptionOr<OfflineFrame> BasePcpHandler::ReadConnectionRequestFrame(
+ EndpointChannel* endpoint_channel) {
+ if (endpoint_channel == nullptr) {
+ return ExceptionOr<OfflineFrame>(Exception::kIo);
+ }
+
+ // To avoid a device connecting but never sending their introductory frame, we
+ // time out the connection after a certain amount of time.
+ CancelableAlarm timeout_alarm(
+ absl::StrCat("PcpHandler(", this->GetStrategy().GetName(),
+ ")::ReadConnectionRequestFrame"),
+ [endpoint_channel]() { endpoint_channel->Close(); },
+ kConnectionRequestReadTimeout, &alarm_executor_);
+ // Do a blocking read to try and find the ConnectionRequestFrame
+ ExceptionOr<ByteArray> wrapped_bytes = endpoint_channel->Read();
+ timeout_alarm.Cancel();
+
+ if (!wrapped_bytes.ok()) {
+ return ExceptionOr<OfflineFrame>(wrapped_bytes.exception());
+ }
+
+ ByteArray bytes = std::move(wrapped_bytes.result());
+ ExceptionOr<OfflineFrame> wrapped_frame = parser::FromBytes(bytes);
+ if (wrapped_frame.GetException().Raised(Exception::kInvalidProtocolBuffer)) {
+ return ExceptionOr<OfflineFrame>(Exception::kIo);
+ }
+
+ OfflineFrame& frame = wrapped_frame.result();
+ if (V1Frame::CONNECTION_REQUEST != parser::GetFrameType(frame)) {
+ return ExceptionOr<OfflineFrame>(Exception::kIo);
+ }
+
+ return wrapped_frame;
+}
+
+std::string BasePcpHandler::GetHashedConnectionToken(
+ const ByteArray& token_bytes) {
+ auto token = std::string(token_bytes);
+ return location::nearby::Base64Utils::Encode(
+ Utils::Sha256Hash(token, token.size()))
+ .substr(0, kConnectionTokenLength);
+}
+
+void BasePcpHandler::LogConnectionAttemptFailure(
+ ClientProxy* client, Medium medium, const std::string& endpoint_id,
+ bool is_incoming, absl::Time start_time,
+ EndpointChannel* endpoint_channel) {
+ proto::connections::ConnectionAttemptResult result =
+ Cancelled(client, endpoint_id) ? proto::connections::RESULT_CANCELLED
+ : proto::connections::RESULT_ERROR;
+ std::unique_ptr<ConnectionAttemptMetadataParams>
+ connections_attempt_metadata_params;
+ if (endpoint_channel != nullptr) {
+ connections_attempt_metadata_params =
+ client->GetAnalyticsRecorder().BuildConnectionAttemptMetadataParams(
+ endpoint_channel->GetTechnology(), endpoint_channel->GetBand(),
+ endpoint_channel->GetFrequency(), endpoint_channel->GetTryCount());
+ }
+ if (is_incoming) {
+ client->GetAnalyticsRecorder().OnIncomingConnectionAttempt(
+ proto::connections::INITIAL, medium, result,
+ SystemClock::ElapsedRealtime() - start_time,
+ /* connection_token= */ "", connections_attempt_metadata_params.get());
+ } else {
+ client->GetAnalyticsRecorder().OnOutgoingConnectionAttempt(
+ endpoint_id, proto::connections::INITIAL, medium, result,
+ SystemClock::ElapsedRealtime() - start_time,
+ /* connection_token= */ "", connections_attempt_metadata_params.get());
+ }
+}
+
+void BasePcpHandler::LogConnectionAttemptSuccess(
+ const std::string& endpoint_id,
+ const PendingConnectionInfo& connection_info) {
+ std::unique_ptr<ConnectionAttemptMetadataParams>
+ connections_attempt_metadata_params;
+ if (connection_info.channel != nullptr) {
+ connections_attempt_metadata_params =
+ connection_info.client->GetAnalyticsRecorder()
+ .BuildConnectionAttemptMetadataParams(
+ connection_info.channel->GetTechnology(),
+ connection_info.channel->GetBand(),
+ connection_info.channel->GetFrequency(),
+ connection_info.channel->GetTryCount());
+ } else {
+ NEARBY_LOG(ERROR,
+ "PendingConnectionInfo channel is null for "
+ "LogConnectionAttemptSuccess. Bail out.");
+ return;
+ }
+ if (connection_info.is_incoming) {
+ connection_info.client->GetAnalyticsRecorder().OnIncomingConnectionAttempt(
+ proto::connections::INITIAL, connection_info.channel->GetMedium(),
+ proto::connections::RESULT_SUCCESS,
+ SystemClock::ElapsedRealtime() - connection_info.start_time,
+ connection_info.connection_token,
+ connections_attempt_metadata_params.get());
+ } else {
+ connection_info.client->GetAnalyticsRecorder().OnOutgoingConnectionAttempt(
+ endpoint_id, proto::connections::INITIAL,
+ connection_info.channel->GetMedium(),
+ proto::connections::RESULT_SUCCESS,
+ SystemClock::ElapsedRealtime() - connection_info.start_time,
+ connection_info.connection_token,
+ connections_attempt_metadata_params.get());
+ }
+}
+
+bool BasePcpHandler::Cancelled(ClientProxy* client,
+ const std::string& endpoint_id) {
+ if (endpoint_id.empty()) {
+ return false;
+ }
+
+ return client->GetCancellationFlag(endpoint_id)->Cancelled();
+}
+
+///////////////////// BasePcpHandler::PendingConnectionInfo ///////////////////
+
+void BasePcpHandler::PendingConnectionInfo::SetCryptoContext(
+ std::unique_ptr<UKey2Handshake> ukey2) {
+ this->ukey2 = std::move(ukey2);
+}
+
+BasePcpHandler::PendingConnectionInfo::~PendingConnectionInfo() {
+ auto future_status = result.lock();
+ if (future_status && !future_status->IsSet()) {
+ NEARBY_LOG(INFO, "Future was not set; destroying info");
+ future_status->Set({Status::kError});
+ }
+
+ if (channel != nullptr) {
+ channel->Close(proto::connections::DisconnectionReason::SHUTDOWN);
+ }
+
+ // Destroy crypto context now; for some reason, crypto context destructor
+ // segfaults if it is not destroyed here.
+ this->ukey2.reset();
+}
+
+void BasePcpHandler::PendingConnectionInfo::LocalEndpointAcceptedConnection(
+ const std::string& endpoint_id, const PayloadListener& payload_listener) {
+ client->LocalEndpointAcceptedConnection(endpoint_id, payload_listener);
+}
+
+void BasePcpHandler::PendingConnectionInfo::LocalEndpointRejectedConnection(
+ const std::string& endpoint_id) {
+ client->LocalEndpointRejectedConnection(endpoint_id);
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/base_pcp_handler.h b/chromium/third_party/nearby/src/connections/implementation/base_pcp_handler.h
new file mode 100644
index 00000000000..f60147d8310
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/base_pcp_handler.h
@@ -0,0 +1,538 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_BASE_PCP_HANDLER_H_
+#define CORE_INTERNAL_BASE_PCP_HANDLER_H_
+
+#include <cstdint>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "securegcm/d2d_connection_context_v1.h"
+#include "securegcm/ukey2_handshake.h"
+#include "absl/container/btree_map.h"
+#include "absl/container/flat_hash_map.h"
+#include "absl/time/time.h"
+#include "connections/implementation/bwu_manager.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/encryption_runner.h"
+#include "connections/implementation/endpoint_channel_manager.h"
+#include "connections/implementation/endpoint_manager.h"
+#include "connections/implementation/mediums/mediums.h"
+#ifdef NO_WEBRTC
+#include "connections/implementation/mediums/webrtc_stub.h"
+#else
+#include "connections/implementation/mediums/webrtc.h"
+#endif
+#include "connections/implementation/pcp.h"
+#include "connections/implementation/pcp_handler.h"
+#include "connections/listeners.h"
+#include "connections/status.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/prng.h"
+#include "internal/platform/atomic_boolean.h"
+#include "internal/platform/atomic_reference.h"
+#include "internal/platform/cancelable_alarm.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/future.h"
+#include "internal/platform/scheduled_executor.h"
+#include "internal/platform/single_thread_executor.h"
+#include "internal/platform/system_clock.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Represents the WebRtc state that mediums are connectable or not.
+enum class WebRtcState {
+ kUndefined = 0,
+ kConnectable = 1,
+ kUnconnectable = 2,
+};
+
+// Annotations for methods that need to run on PCP handler thread.
+// Use only in BasePcpHandler and derived classes.
+#define RUN_ON_PCP_HANDLER_THREAD() \
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(GetPcpHandlerThread())
+
+// A base implementation of the PcpHandler interface that takes care of all
+// bookkeeping and handshake protocols that are common across all PcpHandler
+// implementations -- thus, every concrete PcpHandler implementation must extend
+// this class, so that they can focus exclusively on the medium-specific
+// operations.
+class BasePcpHandler : public PcpHandler,
+ public EndpointManager::FrameProcessor {
+ public:
+ using FrameProcessor = EndpointManager::FrameProcessor;
+
+ // TODO(apolyudov): Add SecureRandom.
+ BasePcpHandler(Mediums* mediums, EndpointManager* endpoint_manager,
+ EndpointChannelManager* channel_manager,
+ BwuManager* bwu_manager, Pcp pcp);
+ ~BasePcpHandler() override;
+ BasePcpHandler(BasePcpHandler&&) = delete;
+ BasePcpHandler& operator=(BasePcpHandler&&) = delete;
+
+ // Starts advertising. Once successfully started, changes ClientProxy's state.
+ // Notifies ConnectionListener (info.listener) in case of any event.
+ // See
+ // cpp/core/listeners.h
+ Status StartAdvertising(ClientProxy* client, const std::string& service_id,
+ const AdvertisingOptions& advertising_options,
+ const ConnectionRequestInfo& info) override;
+
+ // Stops Advertising is active, and changes CLientProxy state,
+ // otherwise does nothing.
+ void StopAdvertising(ClientProxy* client) override;
+
+ // Starts discovery of endpoints that may be advertising.
+ // Updates ClientProxy state once discovery started.
+ // DiscoveryListener will get called in case of any event.
+ Status StartDiscovery(ClientProxy* client, const std::string& service_id,
+ const DiscoveryOptions& discovery_options,
+ const DiscoveryListener& listener) override;
+
+ // Stops Discovery if it is active, and changes CLientProxy state,
+ // otherwise does nothing.
+ void StopDiscovery(ClientProxy* client) override;
+
+ void InjectEndpoint(ClientProxy* client, const std::string& service_id,
+ const OutOfBandConnectionMetadata& metadata) override;
+
+ // Requests a newly discovered remote endpoint it to form a connection.
+ // Updates state on ClientProxy.
+ Status RequestConnection(
+ ClientProxy* client, const std::string& endpoint_id,
+ const ConnectionRequestInfo& info,
+ const ConnectionOptions& connection_options) override;
+
+ // Called by either party to accept connection on their part.
+ // Until both parties call it, connection will not reach a data phase.
+ // Updates state in ClientProxy.
+ Status AcceptConnection(ClientProxy* client, const std::string& endpoint_id,
+ const PayloadListener& payload_listener) override;
+
+ // Called by either party to reject connection on their part.
+ // If either party does call it, connection will terminate.
+ // Updates state in ClientProxy.
+ Status RejectConnection(ClientProxy* client,
+ const std::string& endpoint_id) override;
+
+ // @EndpointManagerReaderThread
+ void OnIncomingFrame(OfflineFrame& frame, const std::string& endpoint_id,
+ ClientProxy* client,
+ proto::connections::Medium medium) override;
+
+ // Called when an endpoint disconnects while we're waiting for both sides to
+ // approve/reject the connection.
+ // @EndpointManagerThread
+ void OnEndpointDisconnect(ClientProxy* client, const std::string& endpoint_id,
+ CountDownLatch barrier) override;
+
+ Pcp GetPcp() const override { return pcp_; }
+ Strategy GetStrategy() const override { return strategy_; }
+ void DisconnectFromEndpointManager();
+
+ protected:
+ // The result of a call to startAdvertisingImpl() or startDiscoveryImpl().
+ struct StartOperationResult {
+ Status status;
+ // If success, the mediums on which we are now advertising/discovering, for
+ // analytics.
+ std::vector<proto::connections::Medium> mediums;
+ };
+
+ // Represents an endpoint that we've discovered. Typically, the implementation
+ // will know how to connect to this endpoint if asked. (eg. It holds on to a
+ // BluetoothDevice)
+ //
+ // NOTE(DiscoveredEndpoint):
+ // Specific protocol is expected to derive from it, as follows:
+ // struct ProtocolEndpoint : public DiscoveredEndpoint {
+ // ProtocolContext context;
+ // };
+ // Protocol then allocates instance with std::make_shared<ProtocolEndpoint>(),
+ // and passes this instance to OnEndpointFound() method.
+ // When calling OnEndpointLost(), protocol does not need to pass the same
+ // instance (but it can if implementation desires to do so).
+ // BasePcpHandler will hold on to the shared_ptr<DiscoveredEndpoint>.
+ struct DiscoveredEndpoint {
+ DiscoveredEndpoint(std::string endpoint_id, ByteArray endpoint_info,
+ std::string service_id,
+ proto::connections::Medium medium,
+ WebRtcState web_rtc_state)
+ : endpoint_id(std::move(endpoint_id)),
+ endpoint_info(std::move(endpoint_info)),
+ service_id(std::move(service_id)),
+ medium(medium),
+ web_rtc_state(web_rtc_state) {}
+ virtual ~DiscoveredEndpoint() = default;
+
+ std::string endpoint_id;
+ ByteArray endpoint_info;
+ std::string service_id;
+ proto::connections::Medium medium;
+ WebRtcState web_rtc_state;
+ };
+
+ struct BluetoothEndpoint : public DiscoveredEndpoint {
+ BluetoothEndpoint(DiscoveredEndpoint endpoint, BluetoothDevice device)
+ : DiscoveredEndpoint(std::move(endpoint)),
+ bluetooth_device(std::move(device)) {}
+
+ BluetoothDevice bluetooth_device;
+ };
+
+ struct BleEndpoint : public BasePcpHandler::DiscoveredEndpoint {
+ BleEndpoint(DiscoveredEndpoint endpoint, BlePeripheral peripheral)
+ : DiscoveredEndpoint(std::move(endpoint)),
+ ble_peripheral(std::move(peripheral)) {}
+ BlePeripheral ble_peripheral;
+ };
+
+ struct WifiLanEndpoint : public DiscoveredEndpoint {
+ WifiLanEndpoint(DiscoveredEndpoint endpoint,
+ const NsdServiceInfo& service_info)
+ : DiscoveredEndpoint(std::move(endpoint)), service_info(service_info) {}
+
+ NsdServiceInfo service_info;
+ };
+
+ struct WebRtcEndpoint : public DiscoveredEndpoint {
+ WebRtcEndpoint(DiscoveredEndpoint endpoint, mediums::WebrtcPeerId peer_id)
+ : DiscoveredEndpoint(std::move(endpoint)),
+ peer_id(std::move(peer_id)) {}
+
+ mediums::WebrtcPeerId peer_id;
+ };
+
+ struct ConnectImplResult {
+ proto::connections::Medium medium =
+ proto::connections::Medium::UNKNOWN_MEDIUM;
+ Status status = {Status::kError};
+ std::unique_ptr<EndpointChannel> endpoint_channel;
+ };
+
+ void RunOnPcpHandlerThread(const std::string& name, Runnable runnable);
+
+ BluetoothDevice GetRemoteBluetoothDevice(
+ const std::string& remote_bluetooth_mac_address);
+
+ void OnEndpointFound(ClientProxy* client,
+ std::shared_ptr<DiscoveredEndpoint> endpoint)
+ RUN_ON_PCP_HANDLER_THREAD();
+
+ void OnEndpointLost(ClientProxy* client, const DiscoveredEndpoint& endpoint)
+ RUN_ON_PCP_HANDLER_THREAD();
+
+ Exception OnIncomingConnection(
+ ClientProxy* client, const ByteArray& remote_endpoint_info,
+ std::unique_ptr<EndpointChannel> endpoint_channel,
+ proto::connections::Medium medium); // throws Exception::IO
+
+ virtual bool HasOutgoingConnections(ClientProxy* client) const;
+ virtual bool HasIncomingConnections(ClientProxy* client) const;
+
+ virtual bool CanSendOutgoingConnection(ClientProxy* client) const;
+ virtual bool CanReceiveIncomingConnection(ClientProxy* client) const;
+
+ virtual StartOperationResult StartAdvertisingImpl(
+ ClientProxy* client, const std::string& service_id,
+ const std::string& local_endpoint_id,
+ const ByteArray& local_endpoint_info,
+ const AdvertisingOptions& advertising_options)
+ RUN_ON_PCP_HANDLER_THREAD() = 0;
+
+ virtual Status StopAdvertisingImpl(ClientProxy* client)
+ RUN_ON_PCP_HANDLER_THREAD() = 0;
+
+ virtual StartOperationResult StartDiscoveryImpl(
+ ClientProxy* client, const std::string& service_id,
+ const DiscoveryOptions& discovery_options)
+ RUN_ON_PCP_HANDLER_THREAD() = 0;
+
+ virtual Status StopDiscoveryImpl(ClientProxy* client)
+ RUN_ON_PCP_HANDLER_THREAD() = 0;
+
+ virtual Status InjectEndpointImpl(ClientProxy* client,
+ const std::string& service_id,
+ const OutOfBandConnectionMetadata& metadata)
+ RUN_ON_PCP_HANDLER_THREAD() = 0;
+
+ virtual ConnectImplResult ConnectImpl(ClientProxy* client,
+ DiscoveredEndpoint* endpoint)
+ RUN_ON_PCP_HANDLER_THREAD() = 0;
+
+ virtual std::vector<proto::connections::Medium>
+ GetConnectionMediumsByPriority() = 0;
+ virtual proto::connections::Medium GetDefaultUpgradeMedium() = 0;
+
+ // Returns the first discovered endpoint for the given endpoint_id.
+ DiscoveredEndpoint* GetDiscoveredEndpoint(const std::string& endpoint_id);
+
+ // Returns a vector of discovered endpoints, sorted in order of decreasing
+ // preference.
+ std::vector<BasePcpHandler::DiscoveredEndpoint*> GetDiscoveredEndpoints(
+ const std::string& endpoint_id);
+
+ // Returns a vector of discovered endpoints that share a given Medium.
+ std::vector<BasePcpHandler::DiscoveredEndpoint*> GetDiscoveredEndpoints(
+ const proto::connections::Medium medium);
+
+ mediums::WebrtcPeerId CreatePeerIdFromAdvertisement(
+ const string& service_id, const string& endpoint_id,
+ const ByteArray& endpoint_info);
+
+ SingleThreadExecutor* GetPcpHandlerThread()
+ ABSL_LOCK_RETURNED(serial_executor_) {
+ return &serial_executor_;
+ }
+
+ Mediums* mediums_;
+ EndpointManager* endpoint_manager_;
+ EndpointChannelManager* channel_manager_;
+
+ private:
+ struct PendingConnectionInfo {
+ PendingConnectionInfo() = default;
+ PendingConnectionInfo(PendingConnectionInfo&& other) = default;
+ PendingConnectionInfo& operator=(PendingConnectionInfo&&) = default;
+ ~PendingConnectionInfo();
+
+ // Passes crypto context that we acquired in DH session for temporary
+ // ownership here.
+ void SetCryptoContext(std::unique_ptr<securegcm::UKey2Handshake> ukey2);
+
+ // Pass Accept notification to client.
+ void LocalEndpointAcceptedConnection(
+ const std::string& endpoint_id,
+ const PayloadListener& payload_listener);
+
+ // Pass Reject notification to client.
+ void LocalEndpointRejectedConnection(const std::string& endpoint_id);
+
+ // Client state tracker to report events to. Never changes. Always valid.
+ ClientProxy* client = nullptr;
+ // Peer endpoint info, or empty, if not discovered yet. May change.
+ ByteArray remote_endpoint_info;
+ std::int32_t nonce = 0;
+ bool is_incoming = false;
+ absl::Time start_time{absl::InfinitePast()};
+ // Client callbacks. Always valid.
+ ConnectionListener listener;
+ ConnectionOptions connection_options;
+
+ // Only set for outgoing connections. If set, we must call
+ // result->Set() when connection is established, or rejected.
+ std::weak_ptr<Future<Status>> result;
+
+ // Only (possibly) vector for incoming connections.
+ std::vector<proto::connections::Medium> supported_mediums;
+
+ // Keep track of a channel before we pass it to EndpointChannelManager.
+ std::unique_ptr<EndpointChannel> channel;
+
+ // Crypto context; initially empty; established first thing after channel
+ // creation by running UKey2 session. While it is in progress, we keep track
+ // of channel ourselves. Once it is done, we pass channel over to
+ // EndpointChannelManager. We keep crypto context until connection is
+ // accepted. Crypto context is passed over to channel_manager_ before
+ // switching to connected state, where Payload may be exchanged.
+ std::unique_ptr<securegcm::UKey2Handshake> ukey2;
+
+ // Used in AnalyticsRecorder for devices connection tracking.
+ std::string connection_token;
+ };
+
+ // @EncryptionRunnerThread
+ // Called internally when DH session has negotiated a key successfully.
+ void OnEncryptionSuccessImpl(const std::string& endpoint_id,
+ std::unique_ptr<securegcm::UKey2Handshake> ukey2,
+ const std::string& auth_token,
+ const ByteArray& raw_auth_token);
+
+ // @EncryptionRunnerThread
+ // Called internally when DH session was not able to negotiate a key.
+ void OnEncryptionFailureImpl(const std::string& endpoint_id,
+ EndpointChannel* channel);
+
+ EncryptionRunner::ResultListener GetResultListener();
+
+ void OnEncryptionSuccessRunnable(
+ const std::string& endpoint_id,
+ std::unique_ptr<securegcm::UKey2Handshake> ukey2,
+ const std::string& auth_token, const ByteArray& raw_auth_token);
+ void OnEncryptionFailureRunnable(const std::string& endpoint_id,
+ EndpointChannel* endpoint_channel);
+
+ static Exception WriteConnectionRequestFrame(
+ EndpointChannel* endpoint_channel, const std::string& local_endpoint_id,
+ const ByteArray& local_endpoint_info, std::int32_t nonce,
+ const std::vector<proto::connections::Medium>& supported_mediums,
+ std::int32_t keep_alive_interval_millis,
+ std::int32_t keep_alive_timeout_millis);
+
+ static constexpr absl::Duration kConnectionRequestReadTimeout =
+ absl::Seconds(2);
+ static constexpr absl::Duration kRejectedConnectionCloseDelay =
+ absl::Seconds(2);
+ static constexpr int kConnectionTokenLength = 8;
+
+ // Returns true if the new endpoint is preferred over the old endpoint.
+ bool IsPreferred(const BasePcpHandler::DiscoveredEndpoint& new_endpoint,
+ const BasePcpHandler::DiscoveredEndpoint& old_endpoint);
+
+ // Returns true, if connection party should respect the specified topology.
+ bool ShouldEnforceTopologyConstraints(
+ const AdvertisingOptions& local_advertising_options) const;
+
+ // Returns true, if connection party should attempt to upgrade itself to
+ // use a higher bandwidth medium, if it is available.
+ bool AutoUpgradeBandwidth(
+ const AdvertisingOptions& local_advertising_options) const;
+
+ // Returns true if the incoming connection should be killed. This only
+ // happens when an incoming connection arrives while we have an outgoing
+ // connection to the same endpoint and we need to stop one connection.
+ bool BreakTie(ClientProxy* client, const std::string& endpoint_id,
+ std::int32_t incoming_nonce, EndpointChannel* channel);
+ // We're not sure how far our outgoing connection has gotten. We may (or may
+ // not) have called ClientProxy::OnConnectionInitiated. Therefore, we'll
+ // call both preInit and preResult failures.
+ void ProcessTieBreakLoss(ClientProxy* client, const std::string& endpoint_id,
+ PendingConnectionInfo* info);
+
+ // Returns true if the bluetooth endpoint based on remote bluetooth mac
+ // address is created and appended into discovered_endpoints_ with key
+ // endpoint_id.
+ bool AppendRemoteBluetoothMacAddressEndpoint(
+ const std::string& endpoint_id,
+ const std::string& remote_bluetooth_mac_address,
+ const DiscoveryOptions& local_discovery_options);
+
+ // Returns true if the webrtc endpoint is created and appended into
+ // discovered_endpoints_ with key endpoint_id.
+ bool AppendWebRTCEndpoint(const std::string& endpoint_id,
+ const DiscoveryOptions& local_discovery_options);
+
+ void ProcessPreConnectionInitiationFailure(
+ ClientProxy* client, Medium medium, const std::string& endpoint_id,
+ EndpointChannel* channel, bool is_incoming, absl::Time start_time,
+ Status status, Future<Status>* result);
+ void ProcessPreConnectionResultFailure(ClientProxy* client,
+ const std::string& endpoint_id);
+
+ // Called when either side accepts/rejects the connection, but only takes
+ // effect after both have accepted or one side has rejected.
+ //
+ // NOTE: We also take in a 'can_close_immediately' variable. This is because
+ // any writes in transit are dropped when we close. To avoid having a reject
+ // write being dropped (which causes the other side to report
+ // onResult(DISCONNECTED) instead of onResult(REJECTED)), we delay our
+ // close. If the other side behaves properly, we shouldn't even see the
+ // delay (because they will also close the connection).
+ void EvaluateConnectionResult(ClientProxy* client,
+ const std::string& endpoint_id,
+ bool can_close_immediately);
+
+ ExceptionOr<OfflineFrame> ReadConnectionRequestFrame(
+ EndpointChannel* channel);
+
+ // Returns an 8 characters length hashed string generated via a token byte
+ // array.
+ std::string GetHashedConnectionToken(const ByteArray& token_bytes);
+
+ static void LogConnectionAttemptFailure(ClientProxy* client, Medium medium,
+ const std::string& endpoint_id,
+ bool is_incoming,
+ absl::Time start_time,
+ EndpointChannel* endpoint_channel);
+
+ static void LogConnectionAttemptSuccess(
+ const std::string& endpoint_id,
+ const PendingConnectionInfo& connection_info);
+
+ // Returns true if the client cancels the operation in progress through the
+ // endpoint id. This is done by CancellationFlag.
+ static bool Cancelled(ClientProxy* client, const std::string& endpoint_id);
+
+ void WaitForLatch(const std::string& method_name, CountDownLatch* latch);
+ Status WaitForResult(const std::string& method_name, std::int64_t client_id,
+ Future<Status>* future);
+ bool MediumSupportedByClientOptions(
+ const proto::connections::Medium& medium,
+ const ConnectionOptions& connection_options) const;
+ std::vector<proto::connections::Medium>
+ GetSupportedConnectionMediumsByPriority(
+ const ConnectionOptions& local_option);
+ std::string GetStringValueOfSupportedMediums(
+ const ConnectionOptions& connection_options) const;
+ std::string GetStringValueOfSupportedMediums(
+ const AdvertisingOptions& advertising_options) const;
+ std::string GetStringValueOfSupportedMediums(
+ const DiscoveryOptions& discovery_options) const;
+
+ // The endpoint id in high visibility mode is stable for 30 seconds, while in
+ // low visibility mode it always rotates. We assume a client is trying to
+ // rotate endpoint id when the advertising options is "low power" (3P) or
+ // "disable Bluetooth classic" (1P).
+ bool ShouldEnterHighVisibilityMode(
+ const AdvertisingOptions& advertising_options);
+
+ // Returns the intersection of supported mediums based on the mediums reported
+ // by the remote client and the local client's advertising options.
+ BooleanMediumSelector ComputeIntersectionOfSupportedMediums(
+ const PendingConnectionInfo& connection_info);
+
+ void OptionsAllowed(const BooleanMediumSelector& allowed,
+ std::ostringstream& result) const;
+
+ ScheduledExecutor alarm_executor_;
+ SingleThreadExecutor serial_executor_;
+
+ // A map of endpoint id -> PendingConnectionInfo. Entries in this map imply
+ // that there is an active connection to the endpoint and we're waiting for
+ // both sides to accept before allowing payloads through. Once the fate of
+ // the connection is decided (either accepted or rejected), it should be
+ // removed from this map.
+ absl::flat_hash_map<std::string, PendingConnectionInfo> pending_connections_;
+ // A map of endpoint id -> DiscoveredEndpoint.
+ absl::btree_multimap<std::string, std::shared_ptr<DiscoveredEndpoint>>
+ discovered_endpoints_;
+ // A map of endpoint id -> alarm. These alarms delay closing the
+ // EndpointChannel to give the other side enough time to read the rejection
+ // message. It's expected that the other side will close the connection
+ // after reading the message (in which case, this alarm should be cancelled
+ // as it's no longer needed), but this alarm is the fallback in case that
+ // doesn't happen.
+ absl::flat_hash_map<std::string, CancelableAlarm> pending_alarms_;
+
+ // The active ClientProxy's connection lifecycle listener. Non-null while
+ // advertising.
+ ConnectionListener advertising_listener_;
+
+ AtomicBoolean stop_{false};
+ Pcp pcp_;
+ Strategy strategy_{PcpToStrategy(pcp_)};
+ Prng prng_;
+ EncryptionRunner encryption_runner_;
+ BwuManager* bwu_manager_;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_BASE_PCP_HANDLER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/base_pcp_handler_test.cc b/chromium/third_party/nearby/src/connections/implementation/base_pcp_handler_test.cc
new file mode 100644
index 00000000000..8f8e46f088d
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/base_pcp_handler_test.cc
@@ -0,0 +1,796 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/base_pcp_handler.h"
+
+#include <array>
+#include <atomic>
+#include <memory>
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "absl/time/time.h"
+#include "connections/implementation/proto/offline_wire_formats.pb.h"
+#include "connections/implementation/base_endpoint_channel.h"
+#include "connections/implementation/bwu_manager.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/encryption_runner.h"
+#include "connections/implementation/offline_frames.h"
+#include "connections/listeners.h"
+#include "connections/params.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/medium_environment.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/pipe.h"
+#include "proto/connections_enums.pb.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+
+using ::location::nearby::proto::connections::Medium;
+using ::testing::_;
+using ::testing::AtLeast;
+using ::testing::Invoke;
+using ::testing::MockFunction;
+using ::testing::Return;
+using ::testing::StrictMock;
+
+constexpr std::array<char, 6> kFakeMacAddress = {'a', 'b', 'c', 'd', 'e', 'f'};
+
+constexpr BooleanMediumSelector kTestCases[] = {
+ BooleanMediumSelector{},
+ BooleanMediumSelector{
+ .bluetooth = true,
+ },
+ BooleanMediumSelector{
+ .wifi_lan = true,
+ },
+ BooleanMediumSelector{
+ .bluetooth = true,
+ .wifi_lan = true,
+ },
+};
+
+class MockEndpointChannel : public BaseEndpointChannel {
+ public:
+ explicit MockEndpointChannel(Pipe* reader, Pipe* writer)
+ : BaseEndpointChannel("channel", &reader->GetInputStream(),
+ &writer->GetOutputStream()) {}
+
+ ExceptionOr<ByteArray> DoRead() { return BaseEndpointChannel::Read(); }
+ Exception DoWrite(const ByteArray& data) {
+ if (broken_write_) {
+ return {Exception::kFailed};
+ }
+ return BaseEndpointChannel::Write(data);
+ }
+ absl::Time DoGetLastReadTimestamp() {
+ return BaseEndpointChannel::GetLastReadTimestamp();
+ }
+
+ MOCK_METHOD(ExceptionOr<ByteArray>, Read, (), (override));
+ MOCK_METHOD(Exception, Write, (const ByteArray& data), (override));
+ MOCK_METHOD(void, CloseImpl, (), (override));
+ MOCK_METHOD(proto::connections::Medium, GetMedium, (), (const override));
+ MOCK_METHOD(std::string, GetType, (), (const override));
+ MOCK_METHOD(std::string, GetName, (), (const override));
+ MOCK_METHOD(bool, IsPaused, (), (const override));
+ MOCK_METHOD(void, Pause, (), (override));
+ MOCK_METHOD(void, Resume, (), (override));
+ MOCK_METHOD(absl::Time, GetLastReadTimestamp, (), (const override));
+
+ bool broken_write_{false};
+};
+
+class MockPcpHandler : public BasePcpHandler {
+ public:
+ using DiscoveredEndpoint = BasePcpHandler::DiscoveredEndpoint;
+
+ MockPcpHandler(Mediums* m, EndpointManager* em, EndpointChannelManager* ecm,
+ BwuManager* bwu)
+ : BasePcpHandler(m, em, ecm, bwu, Pcp::kP2pCluster) {}
+
+ // Expose protected inner types of a base type for mocking.
+ using BasePcpHandler::ConnectImplResult;
+ using BasePcpHandler::DiscoveredEndpoint;
+ using BasePcpHandler::StartOperationResult;
+
+ MOCK_METHOD(Strategy, GetStrategy, (), (const override));
+ MOCK_METHOD(Pcp, GetPcp, (), (const override));
+
+ MOCK_METHOD(bool, HasOutgoingConnections, (ClientProxy * client),
+ (const, override));
+ MOCK_METHOD(bool, HasIncomingConnections, (ClientProxy * client),
+ (const, override));
+
+ MOCK_METHOD(bool, CanSendOutgoingConnection, (ClientProxy * client),
+ (const, override));
+ MOCK_METHOD(bool, CanReceiveIncomingConnection, (ClientProxy * client),
+ (const, override));
+
+ MOCK_METHOD(StartOperationResult, StartAdvertisingImpl,
+ (ClientProxy * client, const std::string& service_id,
+ const std::string& local_endpoint_id,
+ const ByteArray& local_endpoint_info,
+ const AdvertisingOptions& advertising_options),
+ (override));
+ MOCK_METHOD(Status, StopAdvertisingImpl, (ClientProxy * client), (override));
+ MOCK_METHOD(StartOperationResult, StartDiscoveryImpl,
+ (ClientProxy * client, const std::string& service_id,
+ const DiscoveryOptions& discovery_options),
+ (override));
+ MOCK_METHOD(Status, StopDiscoveryImpl, (ClientProxy * client), (override));
+ MOCK_METHOD(Status, InjectEndpointImpl,
+ (ClientProxy * client, const std::string& service_id,
+ const OutOfBandConnectionMetadata& metadata),
+ (override));
+ MOCK_METHOD(ConnectImplResult, ConnectImpl,
+ (ClientProxy * client, DiscoveredEndpoint* endpoint), (override));
+ MOCK_METHOD(proto::connections::Medium, GetDefaultUpgradeMedium, (),
+ (override));
+
+ std::vector<proto::connections::Medium> GetConnectionMediumsByPriority()
+ override {
+ return std::vector<proto::connections::Medium>{
+ proto::connections::WIFI_LAN, proto::connections::WEB_RTC,
+ proto::connections::BLUETOOTH, proto::connections::BLE};
+ }
+
+ // Mock adapters for protected non-virtual methods of a base class.
+ void OnEndpointFound(ClientProxy* client,
+ std::shared_ptr<DiscoveredEndpoint> endpoint)
+ ABSL_NO_THREAD_SAFETY_ANALYSIS {
+ BasePcpHandler::OnEndpointFound(client, std::move(endpoint));
+ }
+ void OnEndpointLost(ClientProxy* client, const DiscoveredEndpoint& endpoint)
+ ABSL_NO_THREAD_SAFETY_ANALYSIS {
+ BasePcpHandler::OnEndpointLost(client, endpoint);
+ }
+ std::vector<BasePcpHandler::DiscoveredEndpoint*> GetDiscoveredEndpoints(
+ const std::string& endpoint_id) {
+ return BasePcpHandler::GetDiscoveredEndpoints(endpoint_id);
+ }
+
+ std::vector<proto::connections::Medium> GetDiscoveryMediums(
+ ClientProxy* client) {
+ auto allowed = client->GetDiscoveryOptions().CompatibleOptions().allowed;
+ return GetMediumsFromSelector(allowed);
+ }
+
+ std::vector<proto::connections::Medium> GetMediumsFromSelector(
+ BooleanMediumSelector allowed) {
+ return allowed.GetMediums(true);
+ }
+};
+
+class MockContext {
+ public:
+ explicit MockContext(std::atomic_int* destroyed = nullptr)
+ : destroyed_{destroyed} {}
+ MockContext(MockContext&& other) { *this = std::move(other); }
+ MockContext& operator=(MockContext&& other) {
+ destroyed_ = other.destroyed_;
+ other.destroyed_ = nullptr;
+ return *this;
+ }
+
+ ~MockContext() {
+ if (destroyed_) (*destroyed_)++;
+ }
+
+ private:
+ std::atomic_int* destroyed_;
+};
+
+struct MockDiscoveredEndpoint : public MockPcpHandler::DiscoveredEndpoint {
+ MockDiscoveredEndpoint(DiscoveredEndpoint endpoint, MockContext context)
+ : DiscoveredEndpoint(std::move(endpoint)), context(std::move(context)) {}
+
+ MockContext context;
+};
+
+class BasePcpHandlerTest
+ : public ::testing::TestWithParam<BooleanMediumSelector> {
+ protected:
+ struct MockConnectionListener {
+ StrictMock<MockFunction<void(const std::string& endpoint_id,
+ const ConnectionResponseInfo& info)>>
+ initiated_cb;
+ StrictMock<MockFunction<void(const std::string& endpoint_id)>> accepted_cb;
+ StrictMock<MockFunction<void(const std::string& endpoint_id,
+ const Status& status)>>
+ rejected_cb;
+ StrictMock<MockFunction<void(const std::string& endpoint_id)>>
+ disconnected_cb;
+ StrictMock<MockFunction<void(const std::string& endpoint_id,
+ std::int32_t quality)>>
+ bandwidth_changed_cb;
+ };
+ struct MockDiscoveryListener {
+ StrictMock<MockFunction<void(const std::string& endpoint_id,
+ const ByteArray& endpoint_info,
+ const std::string& service_id)>>
+ endpoint_found_cb;
+ StrictMock<MockFunction<void(const std::string& endpoint_id)>>
+ endpoint_lost_cb;
+ StrictMock<
+ MockFunction<void(const std::string& endpoint_id, DistanceInfo info)>>
+ endpoint_distance_changed_cb;
+ };
+
+ void StartAdvertising(ClientProxy* client, MockPcpHandler* pcp_handler,
+ BooleanMediumSelector allowed = GetParam()) {
+ std::string service_id{"service"};
+ AdvertisingOptions advertising_options{
+ {
+ Strategy::kP2pCluster,
+ allowed,
+ },
+ true, // auto_upgrade_bandwidth
+ true, // enforce_topology_constraints
+ };
+ ConnectionRequestInfo info{
+ .endpoint_info = ByteArray{"remote_endpoint_name"},
+ .listener = connection_listener_,
+ };
+ EXPECT_CALL(*pcp_handler, StartAdvertisingImpl(client, service_id, _,
+ info.endpoint_info, _))
+ .WillOnce(Return(MockPcpHandler::StartOperationResult{
+ .status = {Status::kSuccess},
+ .mediums = pcp_handler->GetMediumsFromSelector(allowed),
+ }));
+ EXPECT_EQ(pcp_handler->StartAdvertising(client, service_id,
+ advertising_options, info),
+ Status{Status::kSuccess});
+ EXPECT_TRUE(client->IsAdvertising());
+ }
+
+ void StartDiscovery(ClientProxy* client, MockPcpHandler* pcp_handler,
+ BooleanMediumSelector allowed = GetParam()) {
+ std::string service_id{"service"};
+ DiscoveryOptions discovery_options{
+ {
+ Strategy::kP2pCluster,
+ allowed,
+ },
+ true, // auto_upgrade_bandwidth
+ true, // enforce_topology_constraints
+ 5000, // keep_alive_interval_millis
+ 3000, // keep_alive_timeout_millis
+ };
+ EXPECT_CALL(*pcp_handler, StartDiscoveryImpl(client, service_id, _))
+ .WillOnce(Return(MockPcpHandler::StartOperationResult{
+ .status = {Status::kSuccess},
+ .mediums = pcp_handler->GetMediumsFromSelector(allowed),
+ }));
+ EXPECT_EQ(pcp_handler->StartDiscovery(client, service_id, discovery_options,
+ discovery_listener_),
+ Status{Status::kSuccess});
+ EXPECT_TRUE(client->IsDiscovering());
+ }
+
+ std::pair<std::unique_ptr<MockEndpointChannel>,
+ std::unique_ptr<MockEndpointChannel>>
+ SetupConnection(Pipe& pipe_a, Pipe& pipe_b,
+ proto::connections::Medium medium) { // NOLINT
+ auto channel_a = std::make_unique<MockEndpointChannel>(&pipe_b, &pipe_a);
+ auto channel_b = std::make_unique<MockEndpointChannel>(&pipe_a, &pipe_b);
+ // On initiator (A) side, we drop the first write, since this is a
+ // connection establishment packet, and we don't have the peer entity, just
+ // the peer channel. The rest of the exchange must happen for the benefit of
+ // DH key exchange.
+ EXPECT_CALL(*channel_a, Read())
+ .WillRepeatedly(Invoke(
+ [channel = channel_a.get()]() { return channel->DoRead(); }));
+ EXPECT_CALL(*channel_a, Write(_))
+ .WillOnce(Return(Exception{Exception::kSuccess}))
+ .WillRepeatedly(
+ Invoke([channel = channel_a.get()](const ByteArray& data) {
+ return channel->DoWrite(data);
+ }));
+ EXPECT_CALL(*channel_a, GetMedium).WillRepeatedly(Return(medium));
+ EXPECT_CALL(*channel_a, GetLastReadTimestamp)
+ .WillRepeatedly(Return(absl::Now()));
+ EXPECT_CALL(*channel_a, IsPaused).WillRepeatedly(Return(false));
+ EXPECT_CALL(*channel_b, Read())
+ .WillRepeatedly(Invoke(
+ [channel = channel_b.get()]() { return channel->DoRead(); }));
+ EXPECT_CALL(*channel_b, Write(_))
+ .WillRepeatedly(
+ Invoke([channel = channel_b.get()](const ByteArray& data) {
+ return channel->DoWrite(data);
+ }));
+ EXPECT_CALL(*channel_b, GetMedium).WillRepeatedly(Return(medium));
+ EXPECT_CALL(*channel_b, GetLastReadTimestamp)
+ .WillRepeatedly(Return(absl::Now()));
+ EXPECT_CALL(*channel_b, IsPaused).WillRepeatedly(Return(false));
+ return std::make_pair(std::move(channel_a), std::move(channel_b));
+ }
+
+ void RequestConnection(const std::string& endpoint_id,
+ std::unique_ptr<MockEndpointChannel> channel_a,
+ MockEndpointChannel* channel_b, ClientProxy* client,
+ MockPcpHandler* pcp_handler,
+ proto::connections::Medium connect_medium,
+ std::atomic_int* flag = nullptr,
+ Status expected_result = {Status::kSuccess}) {
+ ConnectionRequestInfo info{
+ .endpoint_info = ByteArray{"ABCD"},
+ .listener = connection_listener_,
+ };
+ ConnectionOptions connection_options{
+ .remote_bluetooth_mac_address =
+ ByteArray{std::string("\x12\x34\x56\x78\x9a\xbc")},
+ .keep_alive_interval_millis =
+ FeatureFlags::GetInstance().GetFlags().keep_alive_interval_millis,
+ .keep_alive_timeout_millis =
+ FeatureFlags::GetInstance().GetFlags().keep_alive_timeout_millis,
+ };
+ EXPECT_CALL(mock_discovery_listener_.endpoint_found_cb, Call);
+ EXPECT_CALL(*pcp_handler, CanSendOutgoingConnection)
+ .WillRepeatedly(Return(true));
+ EXPECT_CALL(*pcp_handler, GetStrategy)
+ .WillRepeatedly(Return(Strategy::kP2pCluster));
+ if (expected_result == Status{Status::kSuccess}) {
+ EXPECT_CALL(mock_connection_listener_.initiated_cb, Call).Times(1);
+ }
+ // Simulate successful discovery.
+ auto encryption_runner = std::make_unique<EncryptionRunner>();
+ auto allowed_mediums = pcp_handler->GetDiscoveryMediums(client);
+
+ EXPECT_CALL(*pcp_handler, ConnectImpl)
+ .WillOnce(Invoke([&channel_a, connect_medium](
+ ClientProxy* client,
+ MockPcpHandler::DiscoveredEndpoint* endpoint) {
+ return MockPcpHandler::ConnectImplResult{
+ .medium = connect_medium,
+ .status = {Status::kSuccess},
+ .endpoint_channel = std::move(channel_a),
+ };
+ }));
+
+ for (const auto& discovered_medium : allowed_mediums) {
+ pcp_handler->OnEndpointFound(
+ client,
+ std::make_shared<MockDiscoveredEndpoint>(MockDiscoveredEndpoint{
+ {
+ endpoint_id,
+ info.endpoint_info,
+ "service",
+ discovered_medium,
+ WebRtcState::kUndefined,
+ },
+ MockContext{flag},
+ }));
+ }
+ auto other_client = std::make_unique<ClientProxy>();
+
+ // Run peer crypto in advance, if channel_b is provided.
+ // Otherwise stay in not-encrypted state.
+ if (channel_b != nullptr) {
+ encryption_runner->StartServer(other_client.get(), endpoint_id, channel_b,
+ {});
+ }
+ EXPECT_EQ(pcp_handler->RequestConnection(client, endpoint_id, info,
+ connection_options),
+ expected_result);
+ NEARBY_LOG(INFO, "Stopping Encryption Runner");
+ }
+
+ Pipe pipe_a_;
+ Pipe pipe_b_;
+ MockConnectionListener mock_connection_listener_;
+ MockDiscoveryListener mock_discovery_listener_;
+ ConnectionListener connection_listener_{
+ .initiated_cb = mock_connection_listener_.initiated_cb.AsStdFunction(),
+ .accepted_cb = mock_connection_listener_.accepted_cb.AsStdFunction(),
+ .rejected_cb = mock_connection_listener_.rejected_cb.AsStdFunction(),
+ .disconnected_cb =
+ mock_connection_listener_.disconnected_cb.AsStdFunction(),
+ .bandwidth_changed_cb =
+ mock_connection_listener_.bandwidth_changed_cb.AsStdFunction(),
+ };
+ DiscoveryListener discovery_listener_{
+ .endpoint_found_cb =
+ mock_discovery_listener_.endpoint_found_cb.AsStdFunction(),
+ .endpoint_lost_cb =
+ mock_discovery_listener_.endpoint_lost_cb.AsStdFunction(),
+ .endpoint_distance_changed_cb =
+ mock_discovery_listener_.endpoint_distance_changed_cb.AsStdFunction(),
+ };
+ MediumEnvironment& env_ = MediumEnvironment::Instance();
+};
+
+TEST_P(BasePcpHandlerTest, ConstructorDestructorWorks) {
+ env_.Start();
+ Mediums m;
+ EndpointChannelManager ecm;
+ EndpointManager em(&ecm);
+ BwuManager bwu(m, em, ecm, {}, {});
+ MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
+ SUCCEED();
+ bwu.Shutdown();
+ env_.Stop();
+}
+
+TEST_P(BasePcpHandlerTest, StartAdvertisingChangesState) {
+ env_.Start();
+ ClientProxy client;
+ Mediums m;
+ EndpointChannelManager ecm;
+ EndpointManager em(&ecm);
+ BwuManager bwu(m, em, ecm, {}, {});
+ MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
+ StartAdvertising(&client, &pcp_handler);
+ bwu.Shutdown();
+ env_.Stop();
+}
+
+TEST_P(BasePcpHandlerTest, StopAdvertisingChangesState) {
+ env_.Start();
+ ClientProxy client;
+ Mediums m;
+ EndpointChannelManager ecm;
+ EndpointManager em(&ecm);
+ BwuManager bwu(m, em, ecm, {}, {});
+ MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
+ StartAdvertising(&client, &pcp_handler);
+ EXPECT_CALL(pcp_handler, StopAdvertisingImpl(&client)).Times(1);
+ EXPECT_TRUE(client.IsAdvertising());
+ pcp_handler.StopAdvertising(&client);
+ EXPECT_FALSE(client.IsAdvertising());
+ bwu.Shutdown();
+ env_.Stop();
+}
+
+TEST_P(BasePcpHandlerTest, StartDiscoveryChangesState) {
+ env_.Start();
+ ClientProxy client;
+ Mediums m;
+ EndpointChannelManager ecm;
+ EndpointManager em(&ecm);
+ BwuManager bwu(m, em, ecm, {}, {});
+ MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
+ StartDiscovery(&client, &pcp_handler);
+ bwu.Shutdown();
+ env_.Stop();
+}
+
+TEST_P(BasePcpHandlerTest, StopDiscoveryChangesState) {
+ env_.Start();
+ ClientProxy client;
+ Mediums m;
+ EndpointChannelManager ecm;
+ EndpointManager em(&ecm);
+ BwuManager bwu(m, em, ecm, {}, {});
+ MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
+ StartDiscovery(&client, &pcp_handler);
+ EXPECT_CALL(pcp_handler, StopDiscoveryImpl(&client)).Times(1);
+ EXPECT_TRUE(client.IsDiscovering());
+ pcp_handler.StopDiscovery(&client);
+ EXPECT_FALSE(client.IsDiscovering());
+ bwu.Shutdown();
+ env_.Stop();
+}
+
+TEST_P(BasePcpHandlerTest, RequestConnectionChangesState) {
+ env_.Start();
+ std::string endpoint_id{"1234"};
+ ClientProxy client;
+ Mediums m;
+ EndpointChannelManager ecm;
+ EndpointManager em(&ecm);
+ BwuManager bwu(m, em, ecm, {}, {});
+ MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
+ StartDiscovery(&client, &pcp_handler);
+ auto mediums = pcp_handler.GetDiscoveryMediums(&client);
+ auto connect_medium = mediums[mediums.size() - 1];
+ auto channel_pair = SetupConnection(pipe_a_, pipe_b_, connect_medium);
+ auto& channel_a = channel_pair.first;
+ auto& channel_b = channel_pair.second;
+ EXPECT_CALL(*channel_a, CloseImpl).Times(1);
+ EXPECT_CALL(*channel_b, CloseImpl).Times(1);
+ EXPECT_CALL(mock_connection_listener_.rejected_cb, Call).Times(AtLeast(0));
+ RequestConnection(endpoint_id, std::move(channel_a), channel_b.get(), &client,
+ &pcp_handler, connect_medium);
+ NEARBY_LOG(INFO, "RequestConnection complete");
+ channel_b->Close();
+ bwu.Shutdown();
+ pcp_handler.DisconnectFromEndpointManager();
+ env_.Stop();
+}
+
+TEST_P(BasePcpHandlerTest, IoError_RequestConnectionFails) {
+ env_.Start();
+ std::string endpoint_id{"1234"};
+ ClientProxy client;
+ Mediums m;
+ EndpointChannelManager ecm;
+ EndpointManager em(&ecm);
+ BwuManager bwu(m, em, ecm, {}, {});
+ MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
+ StartDiscovery(&client, &pcp_handler);
+ auto mediums = pcp_handler.GetDiscoveryMediums(&client);
+ auto connect_medium = mediums[mediums.size() - 1];
+ auto channel_pair = SetupConnection(pipe_a_, pipe_b_, connect_medium);
+ auto& channel_a = channel_pair.first;
+ auto& channel_b = channel_pair.second;
+ EXPECT_CALL(*channel_a, CloseImpl).Times(AtLeast(1));
+ EXPECT_CALL(*channel_b, CloseImpl).Times(AtLeast(1));
+ channel_b->broken_write_ = true;
+ EXPECT_CALL(mock_connection_listener_.rejected_cb, Call).Times(AtLeast(0));
+ RequestConnection(endpoint_id, std::move(channel_a), channel_b.get(), &client,
+ &pcp_handler, connect_medium, nullptr,
+ {Status::kEndpointIoError});
+ NEARBY_LOG(INFO, "RequestConnection complete");
+ channel_b->Close();
+ bwu.Shutdown();
+ pcp_handler.DisconnectFromEndpointManager();
+ env_.Stop();
+}
+
+TEST_P(BasePcpHandlerTest, AcceptConnectionChangesState) {
+ env_.Start();
+ std::string endpoint_id{"1234"};
+ ClientProxy client;
+ Mediums m;
+ EndpointChannelManager ecm;
+ EndpointManager em(&ecm);
+ BwuManager bwu(m, em, ecm, {}, {});
+ MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
+ StartDiscovery(&client, &pcp_handler);
+ auto mediums = pcp_handler.GetDiscoveryMediums(&client);
+ auto connect_medium = mediums[mediums.size() - 1];
+ auto channel_pair = SetupConnection(pipe_a_, pipe_b_, connect_medium);
+ auto& channel_a = channel_pair.first;
+ auto& channel_b = channel_pair.second;
+ EXPECT_CALL(*channel_a, CloseImpl).Times(1);
+ EXPECT_CALL(*channel_b, CloseImpl).Times(1);
+ RequestConnection(endpoint_id, std::move(channel_a), channel_b.get(), &client,
+ &pcp_handler, connect_medium);
+ NEARBY_LOG(INFO, "Attempting to accept connection: id=%s",
+ endpoint_id.c_str());
+ EXPECT_EQ(pcp_handler.AcceptConnection(&client, endpoint_id, {}),
+ Status{Status::kSuccess});
+ EXPECT_CALL(mock_connection_listener_.rejected_cb, Call).Times(AtLeast(0));
+ NEARBY_LOGS(INFO) << "Closing connection: id=" << endpoint_id;
+ channel_b->Close();
+ bwu.Shutdown();
+ pcp_handler.DisconnectFromEndpointManager();
+ env_.Stop();
+}
+
+TEST_P(BasePcpHandlerTest, RejectConnectionChangesState) {
+ env_.Start();
+ std::string endpoint_id{"1234"};
+ ClientProxy client;
+ Mediums m;
+ EndpointChannelManager ecm;
+ EndpointManager em(&ecm);
+ BwuManager bwu(m, em, ecm, {}, {});
+ MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
+ StartDiscovery(&client, &pcp_handler);
+ auto mediums = pcp_handler.GetDiscoveryMediums(&client);
+ auto connect_medium = mediums[mediums.size() - 1];
+ auto channel_pair = SetupConnection(pipe_a_, pipe_b_, connect_medium);
+ auto& channel_b = channel_pair.second;
+ EXPECT_CALL(mock_connection_listener_.rejected_cb, Call).Times(1);
+ RequestConnection(endpoint_id, std::move(channel_pair.first), channel_b.get(),
+ &client, &pcp_handler, connect_medium);
+ NEARBY_LOGS(INFO) << "Attempting to reject connection: id=" << endpoint_id;
+ EXPECT_EQ(pcp_handler.RejectConnection(&client, endpoint_id),
+ Status{Status::kSuccess});
+ NEARBY_LOGS(INFO) << "Closing connection: id=" << endpoint_id;
+ channel_b->Close();
+ bwu.Shutdown();
+ pcp_handler.DisconnectFromEndpointManager();
+ env_.Stop();
+}
+
+TEST_P(BasePcpHandlerTest, OnIncomingFrameChangesState) {
+ env_.Start();
+ std::string endpoint_id{"1234"};
+ ClientProxy client;
+ Mediums m;
+ EndpointChannelManager ecm;
+ EndpointManager em(&ecm);
+ BwuManager bwu(m, em, ecm, {}, {});
+ MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
+ StartDiscovery(&client, &pcp_handler);
+ auto mediums = pcp_handler.GetDiscoveryMediums(&client);
+ auto connect_medium = mediums[mediums.size() - 1];
+ auto channel_pair = SetupConnection(pipe_a_, pipe_b_, connect_medium);
+ auto& channel_a = channel_pair.first;
+ auto& channel_b = channel_pair.second;
+ EXPECT_CALL(*channel_a, CloseImpl).Times(1);
+ EXPECT_CALL(*channel_b, CloseImpl).Times(1);
+ RequestConnection(endpoint_id, std::move(channel_a), channel_b.get(), &client,
+ &pcp_handler, connect_medium);
+ NEARBY_LOGS(INFO) << "Attempting to accept connection: id=" << endpoint_id;
+ EXPECT_CALL(mock_connection_listener_.accepted_cb, Call).Times(1);
+ EXPECT_CALL(mock_connection_listener_.disconnected_cb, Call)
+ .Times(AtLeast(0));
+ EXPECT_EQ(pcp_handler.AcceptConnection(&client, endpoint_id, {}),
+ Status{Status::kSuccess});
+ NEARBY_LOG(INFO, "Simulating remote accept: id=%s", endpoint_id.c_str());
+ auto frame =
+ parser::FromBytes(parser::ForConnectionResponse(Status::kSuccess));
+ pcp_handler.OnIncomingFrame(frame.result(), endpoint_id, &client,
+ connect_medium);
+ NEARBY_LOGS(INFO) << "Closing connection: id=" << endpoint_id;
+ channel_b->Close();
+ bwu.Shutdown();
+ pcp_handler.DisconnectFromEndpointManager();
+ env_.Stop();
+}
+
+TEST_P(BasePcpHandlerTest, DestructorIsCalledOnProtocolEndpoint) {
+ env_.Start();
+ std::atomic_int destroyed_flag = 0;
+ int mediums_count = 0;
+ {
+ std::string endpoint_id{"1234"};
+ ClientProxy client;
+ Mediums m;
+ EndpointChannelManager ecm;
+ EndpointManager em(&ecm);
+ BwuManager bwu(m, em, ecm, {}, {});
+ MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
+ StartDiscovery(&client, &pcp_handler);
+ auto mediums = pcp_handler.GetDiscoveryMediums(&client);
+ auto connect_medium = mediums[mediums.size() - 1];
+ auto channel_pair = SetupConnection(pipe_a_, pipe_b_, connect_medium);
+ auto& channel_a = channel_pair.first;
+ auto& channel_b = channel_pair.second;
+ EXPECT_CALL(*channel_a, CloseImpl).Times(1);
+ EXPECT_CALL(*channel_b, CloseImpl).Times(1);
+ RequestConnection(endpoint_id, std::move(channel_a), channel_b.get(),
+ &client, &pcp_handler, connect_medium, &destroyed_flag);
+ mediums_count = mediums.size();
+ NEARBY_LOG(INFO, "Attempting to accept connection: id=%s",
+ endpoint_id.c_str());
+ EXPECT_EQ(pcp_handler.AcceptConnection(&client, endpoint_id, {}),
+ Status{Status::kSuccess});
+ EXPECT_CALL(mock_connection_listener_.rejected_cb, Call).Times(AtLeast(0));
+ NEARBY_LOG(INFO, "Closing connection: id=%s", endpoint_id.c_str());
+ channel_b->Close();
+ bwu.Shutdown();
+ pcp_handler.DisconnectFromEndpointManager();
+ }
+ EXPECT_EQ(destroyed_flag.load(), mediums_count);
+ env_.Stop();
+}
+
+TEST_P(BasePcpHandlerTest, MultipleMediumsProduceSingleEndpointLostEvent) {
+ env_.Start();
+ BooleanMediumSelector allowed = GetParam();
+ if (allowed.Count(true) < 2) {
+ // Ignore single-medium test cases, and implicit "all mediums" case.
+ SUCCEED();
+ return;
+ }
+ std::atomic_int destroyed_flag = 0;
+ int mediums_count = 0;
+ {
+ std::string endpoint_id{"1234"};
+ ClientProxy client;
+ Mediums m;
+ EndpointChannelManager ecm;
+ EndpointManager em(&ecm);
+ BwuManager bwu(m, em, ecm, {}, {});
+ MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
+ StartDiscovery(&client, &pcp_handler);
+ auto mediums = pcp_handler.GetDiscoveryMediums(&client);
+ auto connect_medium = mediums[mediums.size() - 1];
+ auto channel_pair = SetupConnection(pipe_a_, pipe_b_, connect_medium);
+ auto& channel_a = channel_pair.first;
+ auto& channel_b = channel_pair.second;
+ EXPECT_CALL(*channel_a, CloseImpl).Times(1);
+ EXPECT_CALL(*channel_b, CloseImpl).Times(1);
+ EXPECT_CALL(mock_discovery_listener_.endpoint_lost_cb, Call).Times(1);
+ RequestConnection(endpoint_id, std::move(channel_a), channel_b.get(),
+ &client, &pcp_handler, connect_medium, &destroyed_flag);
+ auto allowed_mediums = pcp_handler.GetDiscoveryMediums(&client);
+ mediums_count = allowed_mediums.size();
+ NEARBY_LOG(INFO, "Attempting to accept connection: id=%s",
+ endpoint_id.c_str());
+ EXPECT_EQ(pcp_handler.AcceptConnection(&client, endpoint_id, {}),
+ Status{Status::kSuccess});
+ EXPECT_CALL(mock_connection_listener_.rejected_cb, Call).Times(AtLeast(0));
+ for (const auto* endpoint :
+ pcp_handler.GetDiscoveredEndpoints(endpoint_id)) {
+ pcp_handler.OnEndpointLost(&client, *endpoint);
+ }
+ NEARBY_LOG(INFO, "Closing connection: id=%s", endpoint_id.c_str());
+ channel_b->Close();
+ bwu.Shutdown();
+ pcp_handler.DisconnectFromEndpointManager();
+ }
+ EXPECT_EQ(destroyed_flag.load(), mediums_count);
+ env_.Stop();
+}
+
+INSTANTIATE_TEST_SUITE_P(ParameterizedBasePcpHandlerTest, BasePcpHandlerTest,
+ ::testing::ValuesIn(kTestCases));
+
+TEST_F(BasePcpHandlerTest, InjectEndpoint) {
+ env_.Start();
+ std::string service_id{"service"};
+ std::string endpoint_id{"ABCD"};
+ ClientProxy client;
+ Mediums m;
+ EndpointChannelManager ecm;
+ EndpointManager em(&ecm);
+ BwuManager bwu(m, em, ecm, {}, {});
+ MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
+ BooleanMediumSelector allowed{
+ .bluetooth = true,
+ };
+ DiscoveryOptions discovery_options{
+ {
+ Strategy::kP2pPointToPoint,
+ allowed,
+ },
+ false, // auto_upgrade_bandwidth;
+ false, // enforce_topology_constraints;
+ 0, // keep_alive_interval_millis;
+ 0, // keep_alive_timeout_millis;
+ };
+ EXPECT_CALL(mock_discovery_listener_.endpoint_found_cb, Call);
+ EXPECT_CALL(pcp_handler, StartDiscoveryImpl(&client, service_id, _))
+ .WillOnce(Return(MockPcpHandler::StartOperationResult{
+ .status = {Status::kSuccess},
+ .mediums = allowed.GetMediums(true),
+ }));
+ EXPECT_EQ(pcp_handler.StartDiscovery(&client, service_id, discovery_options,
+ discovery_listener_),
+ Status{Status::kSuccess});
+ EXPECT_TRUE(client.IsDiscovering());
+
+ EXPECT_CALL(pcp_handler, InjectEndpointImpl(&client, service_id, _))
+ .WillOnce(Invoke([&pcp_handler, &endpoint_id](
+ ClientProxy* client, const std::string& service_id,
+ const OutOfBandConnectionMetadata& metadata) {
+ pcp_handler.OnEndpointFound(
+ client,
+ std::make_shared<MockDiscoveredEndpoint>(MockDiscoveredEndpoint{
+ {
+ endpoint_id,
+ /*endpoint_info=*/ByteArray{"ABCD"},
+ service_id,
+ Medium::BLUETOOTH,
+ WebRtcState::kUndefined,
+ },
+ MockContext{nullptr},
+ }));
+ return Status{Status::kSuccess};
+ }));
+ pcp_handler.InjectEndpoint(
+ &client, service_id,
+ OutOfBandConnectionMetadata{
+ .medium = Medium::BLUETOOTH,
+ .remote_bluetooth_mac_address = ByteArray(kFakeMacAddress),
+ });
+ bwu.Shutdown();
+ env_.Stop();
+}
+
+} // namespace
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/ble_advertisement.cc b/chromium/third_party/nearby/src/connections/implementation/ble_advertisement.cc
new file mode 100644
index 00000000000..d016b400150
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/ble_advertisement.cc
@@ -0,0 +1,278 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/ble_advertisement.h"
+
+#include <inttypes.h>
+
+#include "absl/strings/escaping.h"
+#include "connections/implementation/base_pcp_handler.h"
+#include "internal/platform/base_input_stream.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+BleAdvertisement::BleAdvertisement(Version version, Pcp pcp,
+ const ByteArray& service_id_hash,
+ const std::string& endpoint_id,
+ const ByteArray& endpoint_info,
+ const std::string& bluetooth_mac_address,
+ const ByteArray& uwb_address,
+ WebRtcState web_rtc_state) {
+ DoInitialize(/*fast_advertisement=*/false, version, pcp, service_id_hash,
+ endpoint_id, endpoint_info, bluetooth_mac_address, uwb_address,
+ web_rtc_state);
+}
+
+BleAdvertisement::BleAdvertisement(Version version, Pcp pcp,
+ const std::string& endpoint_id,
+ const ByteArray& endpoint_info,
+ const ByteArray& uwb_address) {
+ DoInitialize(/*fast_advertisement=*/true, version, pcp, {}, endpoint_id,
+ endpoint_info, {}, uwb_address, WebRtcState::kUndefined);
+}
+
+void BleAdvertisement::DoInitialize(bool fast_advertisement, Version version,
+ Pcp pcp, const ByteArray& service_id_hash,
+ const std::string& endpoint_id,
+ const ByteArray& endpoint_info,
+ const std::string& bluetooth_mac_address,
+ const ByteArray& uwb_address,
+ WebRtcState web_rtc_state) {
+ fast_advertisement_ = fast_advertisement;
+ if (!fast_advertisement_) {
+ if (service_id_hash.size() != kServiceIdHashLength) return;
+ }
+ int max_endpoint_info_length =
+ fast_advertisement_ ? kMaxFastEndpointInfoLength : kMaxEndpointInfoLength;
+ if (version != Version::kV1 || endpoint_id.empty() ||
+ endpoint_id.length() != kEndpointIdLength ||
+ endpoint_info.size() > max_endpoint_info_length) {
+ return;
+ }
+
+ switch (pcp) {
+ case Pcp::kP2pCluster: // Fall through
+ case Pcp::kP2pStar: // Fall through
+ case Pcp::kP2pPointToPoint:
+ break;
+ default:
+ return;
+ }
+
+ version_ = version;
+ pcp_ = pcp;
+ service_id_hash_ = service_id_hash;
+ endpoint_id_ = endpoint_id;
+ endpoint_info_ = endpoint_info;
+ uwb_address_ = uwb_address;
+ if (!fast_advertisement_) {
+ if (!BluetoothUtils::FromString(bluetooth_mac_address).Empty()) {
+ bluetooth_mac_address_ = bluetooth_mac_address;
+ }
+
+ web_rtc_state_ = web_rtc_state;
+ }
+}
+
+BleAdvertisement::BleAdvertisement(bool fast_advertisement,
+ const ByteArray& ble_advertisement_bytes) {
+ fast_advertisement_ = fast_advertisement;
+
+ if (ble_advertisement_bytes.Empty()) {
+ NEARBY_LOG(ERROR,
+ "Cannot deserialize BleAdvertisement: null bytes passed in.");
+ return;
+ }
+
+ int min_advertisement_length = fast_advertisement_
+ ? kMinFastAdvertisementLength
+ : kMinAdvertisementLength;
+
+ if (ble_advertisement_bytes.size() < min_advertisement_length) {
+ NEARBY_LOG(ERROR,
+ "Cannot deserialize BleAdvertisement: expecting min %d raw "
+ "bytes, got %" PRIu64,
+ kMinAdvertisementLength, ble_advertisement_bytes.size());
+ return;
+ }
+
+ ByteArray advertisement_bytes{ble_advertisement_bytes};
+ BaseInputStream base_input_stream{advertisement_bytes};
+ // The first 1 byte is supposed to be the version and pcp.
+ auto version_and_pcp_byte = static_cast<char>(base_input_stream.ReadUint8());
+ // The upper 3 bits are supposed to be the version.
+ version_ =
+ static_cast<Version>((version_and_pcp_byte & kVersionBitmask) >> 5);
+ if (version_ != Version::kV1) {
+ NEARBY_LOG(INFO,
+ "Cannot deserialize BleAdvertisement: unsupported Version %d",
+ version_);
+ return;
+ }
+ // The lower 5 bits are supposed to be the Pcp.
+ pcp_ = static_cast<Pcp>(version_and_pcp_byte & kPcpBitmask);
+ switch (pcp_) {
+ case Pcp::kP2pCluster: // Fall through
+ case Pcp::kP2pStar: // Fall through
+ case Pcp::kP2pPointToPoint:
+ break;
+ default:
+ NEARBY_LOG(INFO,
+ "Cannot deserialize BleAdvertisement: uunsupported V1 PCP %d",
+ pcp_);
+ }
+
+ // The next 3 bytes are supposed to be the service_id_hash if not fast
+ // advertisment.
+ if (!fast_advertisement_)
+ service_id_hash_ = base_input_stream.ReadBytes(kServiceIdHashLength);
+
+ // The next 4 bytes are supposed to be the endpoint_id.
+ endpoint_id_ = std::string{base_input_stream.ReadBytes(kEndpointIdLength)};
+
+ // The next 1 byte is supposed to be the length of the endpoint_info.
+ std::uint32_t expected_endpoint_info_length = base_input_stream.ReadUint8();
+
+ // The next x bytes are the endpoint info. (Max length is 131 bytes or 17
+ // bytes as fast_advertisement being true).
+ endpoint_info_ = base_input_stream.ReadBytes(expected_endpoint_info_length);
+ const int max_endpoint_info_length =
+ fast_advertisement_ ? kMaxFastEndpointInfoLength : kMaxEndpointInfoLength;
+ if (endpoint_info_.Empty() ||
+ endpoint_info_.size() != expected_endpoint_info_length ||
+ endpoint_info_.size() > max_endpoint_info_length) {
+ NEARBY_LOG(INFO,
+ "Cannot deserialize BleAdvertisement(fast advertisement=%d): "
+ "expected endpointInfo to be %d bytes, got %" PRIu64,
+ fast_advertisement_, expected_endpoint_info_length,
+ endpoint_info_.size());
+
+ // Clear enpoint_id for validity.
+ endpoint_id_.clear();
+ return;
+ }
+
+ // The next 6 bytes are the bluetooth mac address if not fast advertisment.
+ if (!fast_advertisement_) {
+ auto bluetooth_mac_address_bytes =
+ base_input_stream.ReadBytes(BluetoothUtils::kBluetoothMacAddressLength);
+ bluetooth_mac_address_ =
+ BluetoothUtils::ToString(bluetooth_mac_address_bytes);
+ }
+
+ // The next 1 byte is supposed to be the length of the uwb_address. If the
+ // next byte is not available then it should be a fast advertisement and skip
+ // it for remaining bytes.
+ if (base_input_stream.IsAvailable(1)) {
+ std::uint32_t expected_uwb_address_length = base_input_stream.ReadUint8();
+ // If the length of uwb_address is not zero, then retrieve it.
+ if (expected_uwb_address_length != 0) {
+ uwb_address_ = base_input_stream.ReadBytes(expected_uwb_address_length);
+ if (uwb_address_.Empty() ||
+ uwb_address_.size() != expected_uwb_address_length) {
+ NEARBY_LOG(INFO,
+ "Cannot deserialize BleAdvertisement: "
+ "expected uwbAddress size to be %d bytes, got %" PRIu64,
+ expected_uwb_address_length, uwb_address_.size());
+
+ // Clear enpoint_id for validity.
+ endpoint_id_.clear();
+ return;
+ }
+ }
+
+ // The next 1 byte is extra field.
+ if (!fast_advertisement_) {
+ if (base_input_stream.IsAvailable(kExtraFieldLength)) {
+ auto extra_field = static_cast<char>(base_input_stream.ReadUint8());
+ web_rtc_state_ = (extra_field & kWebRtcConnectableFlagBitmask) == 1
+ ? WebRtcState::kConnectable
+ : WebRtcState::kUnconnectable;
+ }
+ }
+ }
+
+ base_input_stream.Close();
+}
+
+BleAdvertisement::operator ByteArray() const {
+ if (!IsValid()) {
+ return ByteArray();
+ }
+
+ // The first 3 bits are the Version.
+ char version_and_pcp_byte =
+ (static_cast<char>(version_) << 5) & kVersionBitmask;
+ // The next 5 bits are the Pcp.
+ version_and_pcp_byte |= static_cast<char>(pcp_) & kPcpBitmask;
+
+ std::string out;
+ if (fast_advertisement_) {
+ // clang-format off
+ out = absl::StrCat(std::string(1, version_and_pcp_byte),
+ endpoint_id_,
+ std::string(1, endpoint_info_.size()),
+ std::string(endpoint_info_));
+ // clang-format on
+ } else {
+ // clang-format off
+ out = absl::StrCat(std::string(1, version_and_pcp_byte),
+ std::string(service_id_hash_),
+ endpoint_id_,
+ std::string(1, endpoint_info_.size()),
+ std::string(endpoint_info_));
+ // clang-format on
+
+ // The next 6 bytes are the bluetooth mac address. If bluetooth_mac_address
+ // is invalid or empty, we get back an empty byte array.
+ auto bluetooth_mac_address_bytes{
+ BluetoothUtils::FromString(bluetooth_mac_address_)};
+ if (!bluetooth_mac_address_bytes.Empty()) {
+ absl::StrAppend(&out, std::string(bluetooth_mac_address_bytes));
+ } else {
+ // If bluetooth MAC address is invalid, then reserve the bytes.
+ auto fake_bt_mac_address_bytes =
+ ByteArray(BluetoothUtils::kBluetoothMacAddressLength);
+ absl::StrAppend(&out, std::string(fake_bt_mac_address_bytes));
+ }
+ }
+
+ // The next bytes are UWB address field.
+ if (!uwb_address_.Empty()) {
+ absl::StrAppend(&out, std::string(1, uwb_address_.size()));
+ absl::StrAppend(&out, std::string(uwb_address_));
+ } else if (!fast_advertisement_) {
+ // Write UWB address with length 0 to be able to read the next field when
+ // decode.
+ absl::StrAppend(&out, std::string(1, uwb_address_.size()));
+ }
+
+ // The next 1 byte is extra field.
+ if (!fast_advertisement_) {
+ int web_rtc_connectable_flag =
+ (web_rtc_state_ == WebRtcState::kConnectable) ? 1 : 0;
+ char extra_field_byte = static_cast<char>(web_rtc_connectable_flag) &
+ kWebRtcConnectableFlagBitmask;
+ absl::StrAppend(&out, std::string(1, extra_field_byte));
+ }
+
+ return ByteArray(std::move(out));
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/ble_advertisement.h b/chromium/third_party/nearby/src/connections/implementation/ble_advertisement.h
new file mode 100644
index 00000000000..579e5af8d4b
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/ble_advertisement.h
@@ -0,0 +1,126 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_BLE_ADVERTISEMENT_H_
+#define CORE_INTERNAL_BLE_ADVERTISEMENT_H_
+
+#include "connections/implementation/base_pcp_handler.h"
+#include "connections/implementation/pcp.h"
+#include "internal/platform/bluetooth_utils.h"
+#include "internal/platform/byte_array.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Represents the format of the Connections Ble Advertisement used in
+// Advertising + Discovery.
+//
+// <p>[VERSION][PCP][SERVICE_ID_HASH][ENDPOINT_ID][ENDPOINT_INFO_SIZE]
+// [ENDPOINT_INFO][BLUETOOTH_MAC][UWB_ADDRESS_SIZE][UWB_ADDRESS][EXTRA_FIELD]
+//
+// <p>The fast version of this advertisement simply omits SERVICE_ID_HASH and
+// the Bluetooth MAC address.
+//
+// <p>See go/connections-ble-advertisement for more information.
+class BleAdvertisement {
+ public:
+ // Versions of the BleAdvertisement.
+ enum class Version {
+ kUndefined = 0,
+ kV1 = 1,
+ // Version is only allocated 3 bits in the BleAdvertisement, so this
+ // can never go beyond V7.
+ };
+
+ static constexpr int kVersionAndPcpLength = 1;
+ static constexpr int kVersionBitmask = 0x0E0;
+ static constexpr int kPcpBitmask = 0x01F;
+ static constexpr int kServiceIdHashLength = 3;
+ static constexpr int kEndpointIdLength = 4;
+ static constexpr int kEndpointInfoSizeLength = 1;
+ static constexpr int kBluetoothMacAddressLength =
+ BluetoothUtils::kBluetoothMacAddressLength;
+ static constexpr int kUwbAddressSizeLength = 1;
+ static constexpr int kExtraFieldLength = 1;
+ static constexpr int kEndpointInfoLengthBitmask = 0x0FF;
+ static constexpr int kWebRtcConnectableFlagBitmask = 0x01;
+ static constexpr int kMinAdvertisementLength =
+ kVersionAndPcpLength + kServiceIdHashLength + kEndpointIdLength +
+ kEndpointInfoSizeLength + kBluetoothMacAddressLength;
+
+ // The difference between normal and fast advertisements is that the fast one
+ // omits the SERVICE_ID_HASH and Bluetooth MAC address. This is done to save
+ // space.
+ static constexpr int kMinFastAdvertisementLength = kMinAdvertisementLength -
+ kServiceIdHashLength -
+ kBluetoothMacAddressLength;
+ static constexpr int kMaxEndpointInfoLength = 131;
+ static constexpr int kMaxFastEndpointInfoLength = 17;
+
+ BleAdvertisement() = default;
+ BleAdvertisement(Version version, Pcp pcp, const std::string& endpoint_id,
+ const ByteArray& endpoint_info,
+ const ByteArray& uwb_address);
+ BleAdvertisement(Version version, Pcp pcp, const ByteArray& service_id_hash,
+ const std::string& endpoint_id,
+ const ByteArray& endpoint_info,
+ const std::string& bluetooth_mac_address,
+ const ByteArray& uwb_address, WebRtcState web_rtc_state);
+ BleAdvertisement(bool fast_advertisement,
+ const ByteArray& ble_advertisement_bytes);
+ BleAdvertisement(const BleAdvertisement&) = default;
+ BleAdvertisement& operator=(const BleAdvertisement&) = default;
+ BleAdvertisement(BleAdvertisement&&) = default;
+ BleAdvertisement& operator=(BleAdvertisement&&) = default;
+ ~BleAdvertisement() = default;
+
+ explicit operator ByteArray() const;
+
+ bool IsValid() const { return !endpoint_id_.empty(); }
+ bool IsFastAdvertisement() const { return fast_advertisement_; }
+ Version GetVersion() const { return version_; }
+ Pcp GetPcp() const { return pcp_; }
+ ByteArray GetServiceIdHash() const { return service_id_hash_; }
+ std::string GetEndpointId() const { return endpoint_id_; }
+ ByteArray GetEndpointInfo() const { return endpoint_info_; }
+ std::string GetBluetoothMacAddress() const { return bluetooth_mac_address_; }
+ ByteArray GetUwbAddress() const { return uwb_address_; }
+ WebRtcState GetWebRtcState() const { return web_rtc_state_; }
+
+ private:
+ void DoInitialize(bool fast_advertisement, Version version, Pcp pcp,
+ const ByteArray& service_id_hash,
+ const std::string& endpoint_id,
+ const ByteArray& endpoint_info,
+ const std::string& bluetooth_mac_address,
+ const ByteArray& uwb_address, WebRtcState web_rtc_state);
+
+ bool fast_advertisement_ = false;
+ Version version_{Version::kUndefined};
+ Pcp pcp_{Pcp::kUnknown};
+ ByteArray service_id_hash_;
+ std::string endpoint_id_;
+ ByteArray endpoint_info_;
+ std::string bluetooth_mac_address_;
+ // TODO(b/169550050): Define UWB address field.
+ ByteArray uwb_address_;
+ WebRtcState web_rtc_state_{WebRtcState::kUndefined};
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_BLE_ADVERTISEMENT_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/ble_advertisement_test.cc b/chromium/third_party/nearby/src/connections/implementation/ble_advertisement_test.cc
new file mode 100644
index 00000000000..d7dcaafb47a
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/ble_advertisement_test.cc
@@ -0,0 +1,436 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/ble_advertisement.h"
+
+#include "gtest/gtest.h"
+#include "connections/implementation/base_pcp_handler.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+
+constexpr BleAdvertisement::Version kVersion = BleAdvertisement::Version::kV1;
+constexpr Pcp kPcp = Pcp::kP2pCluster;
+constexpr absl::string_view kServiceIdHashBytes{"\x0a\x0b\x0c"};
+constexpr absl::string_view kEndpointId{"AB12"};
+constexpr absl::string_view kEndpointName{
+ "How much wood can a woodchuck chuck if a wood chuck would chuck wood?"};
+constexpr absl::string_view kFastAdvertisementEndpointName{"Fast Advertise"};
+constexpr absl::string_view kBluetoothMacAddress{"00:00:E6:88:64:13"};
+constexpr WebRtcState kWebRtcState = WebRtcState::kConnectable;
+
+// TODO(b/169550050): Implement UWBAddress.
+TEST(BleAdvertisementTest, ConstructionWorks) {
+ ByteArray service_id_hash{std::string(kServiceIdHashBytes)};
+ ByteArray endpoint_info{std::string(kEndpointName)};
+ BleAdvertisement ble_advertisement{
+ kVersion, kPcp,
+ service_id_hash, std::string(kEndpointId),
+ endpoint_info, std::string(kBluetoothMacAddress),
+ ByteArray{}, kWebRtcState};
+
+ EXPECT_TRUE(ble_advertisement.IsValid());
+ EXPECT_FALSE(ble_advertisement.IsFastAdvertisement());
+ EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
+ EXPECT_EQ(kPcp, ble_advertisement.GetPcp());
+ EXPECT_EQ(service_id_hash, ble_advertisement.GetServiceIdHash());
+ EXPECT_EQ(kEndpointId, ble_advertisement.GetEndpointId());
+ EXPECT_EQ(endpoint_info, ble_advertisement.GetEndpointInfo());
+ EXPECT_EQ(kBluetoothMacAddress, ble_advertisement.GetBluetoothMacAddress());
+ EXPECT_EQ(kWebRtcState, ble_advertisement.GetWebRtcState());
+}
+
+TEST(BleAdvertisementTest, ConstructionWorksForFastAdvertisement) {
+ ByteArray fast_endpoint_info{std::string(kFastAdvertisementEndpointName)};
+ BleAdvertisement ble_advertisement{kVersion, kPcp, std::string(kEndpointId),
+ fast_endpoint_info, ByteArray{}};
+
+ EXPECT_TRUE(ble_advertisement.IsValid());
+ EXPECT_TRUE(ble_advertisement.IsFastAdvertisement());
+ EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
+ EXPECT_EQ(kPcp, ble_advertisement.GetPcp());
+ EXPECT_EQ(kEndpointId, ble_advertisement.GetEndpointId());
+ EXPECT_EQ(fast_endpoint_info, ble_advertisement.GetEndpointInfo());
+ EXPECT_EQ(WebRtcState::kUndefined, ble_advertisement.GetWebRtcState());
+}
+
+TEST(BleAdvertisementTest, ConstructionWorksWithEmptyEndpointInfo) {
+ ByteArray empty_endpoint_info;
+
+ ByteArray service_id_hash{std::string(kServiceIdHashBytes)};
+ BleAdvertisement ble_advertisement{kVersion,
+ kPcp,
+ service_id_hash,
+ std::string(kEndpointId),
+ empty_endpoint_info,
+ std::string(kBluetoothMacAddress),
+ ByteArray{},
+ kWebRtcState};
+
+ EXPECT_TRUE(ble_advertisement.IsValid());
+ EXPECT_FALSE(ble_advertisement.IsFastAdvertisement());
+ EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
+ EXPECT_EQ(kPcp, ble_advertisement.GetPcp());
+ EXPECT_EQ(service_id_hash, ble_advertisement.GetServiceIdHash());
+ EXPECT_EQ(kEndpointId, ble_advertisement.GetEndpointId());
+ EXPECT_EQ(empty_endpoint_info, ble_advertisement.GetEndpointInfo());
+ EXPECT_EQ(kBluetoothMacAddress, ble_advertisement.GetBluetoothMacAddress());
+ EXPECT_EQ(kWebRtcState, ble_advertisement.GetWebRtcState());
+}
+
+TEST(BleAdvertisementTest,
+ ConstructionWorksWithEmptyEndpointInfoForFastAdvertisement) {
+ ByteArray empty_endpoint_info;
+
+ BleAdvertisement ble_advertisement{kVersion, kPcp, std::string(kEndpointId),
+ empty_endpoint_info, ByteArray{}};
+
+ EXPECT_TRUE(ble_advertisement.IsValid());
+ EXPECT_TRUE(ble_advertisement.IsFastAdvertisement());
+ EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
+ EXPECT_EQ(kPcp, ble_advertisement.GetPcp());
+ EXPECT_EQ(kEndpointId, ble_advertisement.GetEndpointId());
+ EXPECT_EQ(empty_endpoint_info, ble_advertisement.GetEndpointInfo());
+ EXPECT_EQ(WebRtcState::kUndefined, ble_advertisement.GetWebRtcState());
+}
+
+TEST(BleAdvertisementTest, ConstructionWorksWithEmojiEndpointInfo) {
+ ByteArray emoji_endpoint_info{std::string("\u0001F450 \u0001F450")};
+
+ ByteArray service_id_hash{std::string(kServiceIdHashBytes)};
+ BleAdvertisement ble_advertisement{kVersion,
+ kPcp,
+ service_id_hash,
+ std::string(kEndpointId),
+ emoji_endpoint_info,
+ std::string(kBluetoothMacAddress),
+ ByteArray{},
+ kWebRtcState};
+
+ EXPECT_TRUE(ble_advertisement.IsValid());
+ EXPECT_FALSE(ble_advertisement.IsFastAdvertisement());
+ EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
+ EXPECT_EQ(kPcp, ble_advertisement.GetPcp());
+ EXPECT_EQ(service_id_hash, ble_advertisement.GetServiceIdHash());
+ EXPECT_EQ(kEndpointId, ble_advertisement.GetEndpointId());
+ EXPECT_EQ(emoji_endpoint_info, ble_advertisement.GetEndpointInfo());
+ EXPECT_EQ(kBluetoothMacAddress, ble_advertisement.GetBluetoothMacAddress());
+ EXPECT_EQ(kWebRtcState, ble_advertisement.GetWebRtcState());
+}
+
+TEST(BleAdvertisementTest,
+ ConstructionWorksWithEmojiEndpointInfoForFastAdvertisement) {
+ ByteArray emoji_endpoint_info{std::string("\u0001F450 \u0001F450")};
+
+ BleAdvertisement ble_advertisement{kVersion, kPcp, std::string(kEndpointId),
+ emoji_endpoint_info, ByteArray{}};
+
+ EXPECT_TRUE(ble_advertisement.IsValid());
+ EXPECT_TRUE(ble_advertisement.IsFastAdvertisement());
+ EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
+ EXPECT_EQ(kPcp, ble_advertisement.GetPcp());
+ EXPECT_EQ(kEndpointId, ble_advertisement.GetEndpointId());
+ EXPECT_EQ(emoji_endpoint_info, ble_advertisement.GetEndpointInfo());
+ EXPECT_EQ(WebRtcState::kUndefined, ble_advertisement.GetWebRtcState());
+}
+
+TEST(BleAdvertisementTest, ConstructionFailsWithLongEndpointInfo) {
+ std::string long_endpoint_name(BleAdvertisement::kMaxEndpointInfoLength + 1,
+ 'x');
+ ByteArray long_endpoint_info{long_endpoint_name};
+
+ ByteArray service_id_hash{std::string(kServiceIdHashBytes)};
+ BleAdvertisement ble_advertisement{
+ kVersion, kPcp,
+ service_id_hash, std::string(kEndpointId),
+ long_endpoint_info, std::string(kBluetoothMacAddress),
+ ByteArray{}, kWebRtcState};
+
+ EXPECT_FALSE(ble_advertisement.IsValid());
+}
+
+TEST(BleAdvertisementTest,
+ ConstructionFailsWithLongEndpointInfoForFastAdvertisement) {
+ std::string long_endpoint_name(
+ BleAdvertisement::kMaxFastEndpointInfoLength + 1, 'x');
+ ByteArray long_endpoint_info{long_endpoint_name};
+
+ BleAdvertisement ble_advertisement{kVersion, kPcp, std::string(kEndpointId),
+ long_endpoint_info, ByteArray{}};
+
+ EXPECT_FALSE(ble_advertisement.IsValid());
+}
+
+TEST(BleAdvertisementTest, ConstructionFailsWithBadVersion) {
+ auto bad_version = static_cast<BleAdvertisement::Version>(666);
+
+ ByteArray service_id_hash{std::string(kServiceIdHashBytes)};
+ ByteArray endpoint_info{std::string(kEndpointName)};
+ BleAdvertisement ble_advertisement{
+ bad_version, kPcp,
+ service_id_hash, std::string(kEndpointId),
+ endpoint_info, std::string(kBluetoothMacAddress),
+ ByteArray{}, kWebRtcState};
+
+ EXPECT_FALSE(ble_advertisement.IsValid());
+}
+
+TEST(BleAdvertisementTest,
+ ConstructionFailsWithBadVersionForFastAdvertisement) {
+ auto bad_version = static_cast<BleAdvertisement::Version>(666);
+
+ ByteArray fast_endpoint_info{std::string(kFastAdvertisementEndpointName)};
+ BleAdvertisement ble_advertisement{bad_version, kPcp,
+ std::string(kEndpointId),
+ fast_endpoint_info, ByteArray{}};
+
+ EXPECT_FALSE(ble_advertisement.IsValid());
+}
+
+TEST(BleAdvertisementTest, ConstructionFailsWithBadPCP) {
+ auto bad_pcp = static_cast<Pcp>(666);
+
+ ByteArray service_id_hash{std::string(kServiceIdHashBytes)};
+ ByteArray endpoint_info{std::string(kEndpointName)};
+ BleAdvertisement ble_advertisement{
+ kVersion, bad_pcp,
+ service_id_hash, std::string(kEndpointId),
+ endpoint_info, std::string(kBluetoothMacAddress),
+ ByteArray{}, kWebRtcState};
+
+ EXPECT_FALSE(ble_advertisement.IsValid());
+}
+
+TEST(BleAdvertisementTest, ConstructionFailsWithBadPCPForFastAdvertisement) {
+ auto bad_pcp = static_cast<Pcp>(666);
+
+ ByteArray fast_endpoint_info{std::string(kFastAdvertisementEndpointName)};
+ BleAdvertisement ble_advertisement{kVersion, bad_pcp,
+ std::string(kEndpointId),
+ fast_endpoint_info, ByteArray{}};
+
+ EXPECT_FALSE(ble_advertisement.IsValid());
+}
+
+TEST(BleAdvertisementTest, ConstructionSucceedsWithEmptyBluetoothMacAddress) {
+ std::string empty_bluetooth_mac_address = "";
+
+ ByteArray service_id_hash{std::string(kServiceIdHashBytes)};
+ ByteArray endpoint_info{std::string(kEndpointName)};
+ BleAdvertisement ble_advertisement{
+ kVersion, kPcp,
+ service_id_hash, std::string(kEndpointId),
+ endpoint_info, empty_bluetooth_mac_address,
+ ByteArray{}, kWebRtcState};
+
+ EXPECT_TRUE(ble_advertisement.IsValid());
+}
+
+TEST(BleAdvertisementTest, ConstructionSucceedsWithInvalidBluetoothMacAddress) {
+ std::string bad_bluetooth_mac_address = "022:00";
+
+ ByteArray service_id_hash{std::string(kServiceIdHashBytes)};
+ ByteArray endpoint_info{std::string(kEndpointName)};
+ BleAdvertisement ble_advertisement{kVersion, kPcp,
+ service_id_hash, std::string(kEndpointId),
+ endpoint_info, bad_bluetooth_mac_address,
+ ByteArray{}, kWebRtcState};
+
+ EXPECT_TRUE(ble_advertisement.IsValid());
+ EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
+ EXPECT_EQ(kPcp, ble_advertisement.GetPcp());
+ EXPECT_EQ(service_id_hash, ble_advertisement.GetServiceIdHash());
+ EXPECT_EQ(kEndpointId, ble_advertisement.GetEndpointId());
+ EXPECT_EQ(endpoint_info, ble_advertisement.GetEndpointInfo());
+ EXPECT_TRUE(ble_advertisement.GetBluetoothMacAddress().empty());
+ EXPECT_EQ(kWebRtcState, ble_advertisement.GetWebRtcState());
+}
+
+TEST(BleAdvertisementTest, ConstructionFromBytesWorks) {
+ // Serialize good data into a good Ble Advertisement.
+ ByteArray service_id_hash{std::string(kServiceIdHashBytes)};
+ ByteArray endpoint_info{std::string(kEndpointName)};
+ BleAdvertisement org_ble_advertisement{
+ kVersion, kPcp,
+ service_id_hash, std::string(kEndpointId),
+ endpoint_info, std::string(kBluetoothMacAddress),
+ ByteArray{}, kWebRtcState};
+ ByteArray ble_advertisement_bytes(org_ble_advertisement);
+
+ BleAdvertisement ble_advertisement{false, ble_advertisement_bytes};
+
+ EXPECT_TRUE(ble_advertisement.IsValid());
+ EXPECT_FALSE(ble_advertisement.IsFastAdvertisement());
+ EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
+ EXPECT_EQ(kPcp, ble_advertisement.GetPcp());
+ EXPECT_EQ(service_id_hash, ble_advertisement.GetServiceIdHash());
+ EXPECT_EQ(kEndpointId, ble_advertisement.GetEndpointId());
+ EXPECT_EQ(endpoint_info, ble_advertisement.GetEndpointInfo());
+ EXPECT_EQ(kBluetoothMacAddress, ble_advertisement.GetBluetoothMacAddress());
+ EXPECT_EQ(kWebRtcState, ble_advertisement.GetWebRtcState());
+}
+
+TEST(BleAdvertisementTest, ConstructionFromBytesWorksForFastAdvertisement) {
+ // Serialize good data into a good Ble Advertisement.
+ ByteArray fast_endpoint_info{std::string(kFastAdvertisementEndpointName)};
+ BleAdvertisement org_ble_advertisement{kVersion, kPcp,
+ std::string(kEndpointId),
+ fast_endpoint_info, ByteArray{}};
+ ByteArray ble_advertisement_bytes(org_ble_advertisement);
+
+ BleAdvertisement ble_advertisement{true, ble_advertisement_bytes};
+
+ EXPECT_TRUE(ble_advertisement.IsValid());
+ EXPECT_TRUE(ble_advertisement.IsFastAdvertisement());
+ EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
+ EXPECT_EQ(kPcp, ble_advertisement.GetPcp());
+ EXPECT_EQ(kEndpointId, ble_advertisement.GetEndpointId());
+ EXPECT_EQ(fast_endpoint_info, ble_advertisement.GetEndpointInfo());
+ EXPECT_EQ(WebRtcState::kUndefined, ble_advertisement.GetWebRtcState());
+}
+
+// Bytes at the end should be ignored so that they can be used as reserve bytes
+// in the future.
+TEST(BleAdvertisementTest, ConstructionFromLongLengthBytesWorks) {
+ // Serialize good data into a good Ble Advertisement.
+ ByteArray service_id_hash{std::string(kServiceIdHashBytes)};
+ ByteArray endpoint_info{std::string(kEndpointName)};
+ BleAdvertisement ble_advertisement{
+ kVersion, kPcp,
+ service_id_hash, std::string(kEndpointId),
+ endpoint_info, std::string(kBluetoothMacAddress),
+ ByteArray{}, kWebRtcState};
+ ByteArray ble_advertisement_bytes(ble_advertisement);
+
+ // Add bytes to the end of the valid Ble advertisement.
+ ByteArray long_ble_advertisement_bytes(
+ BleAdvertisement::kMinAdvertisementLength + 1000);
+ ASSERT_LE(ble_advertisement_bytes.size(),
+ long_ble_advertisement_bytes.size());
+ memcpy(long_ble_advertisement_bytes.data(), ble_advertisement_bytes.data(),
+ ble_advertisement_bytes.size());
+
+ BleAdvertisement long_ble_advertisement{false, long_ble_advertisement_bytes};
+
+ EXPECT_TRUE(long_ble_advertisement.IsValid());
+ EXPECT_EQ(kVersion, long_ble_advertisement.GetVersion());
+ EXPECT_EQ(kPcp, long_ble_advertisement.GetPcp());
+ EXPECT_EQ(service_id_hash, long_ble_advertisement.GetServiceIdHash());
+ EXPECT_EQ(kEndpointId, long_ble_advertisement.GetEndpointId());
+ EXPECT_EQ(endpoint_info, long_ble_advertisement.GetEndpointInfo());
+ EXPECT_EQ(kBluetoothMacAddress,
+ long_ble_advertisement.GetBluetoothMacAddress());
+ EXPECT_EQ(kWebRtcState, ble_advertisement.GetWebRtcState());
+}
+
+TEST(BleAdvertisementTest, ConstructionFromNullBytesFails) {
+ BleAdvertisement ble_advertisement{false, ByteArray{}};
+
+ EXPECT_FALSE(ble_advertisement.IsValid());
+}
+
+TEST(BleAdvertisementTest, ConstructionFromNullBytesFailsForFastAdvertisement) {
+ BleAdvertisement ble_advertisement{true, ByteArray{}};
+
+ EXPECT_FALSE(ble_advertisement.IsValid());
+}
+
+TEST(BleAdvertisementTest, ConstructionFromShortLengthBytesFails) {
+ // Serialize good data into a good Ble Advertisement.
+ ByteArray service_id_hash{std::string(kServiceIdHashBytes)};
+ ByteArray endpoint_info{std::string(kEndpointName)};
+ BleAdvertisement ble_advertisement{
+ kVersion, kPcp,
+ service_id_hash, std::string(kEndpointId),
+ endpoint_info, std::string(kBluetoothMacAddress),
+ ByteArray{}, kWebRtcState};
+ ByteArray ble_advertisement_bytes(ble_advertisement);
+
+ // Shorten the valid Ble Advertisement.
+ ByteArray short_ble_advertisement_bytes{
+ ble_advertisement_bytes.data(),
+ BleAdvertisement::kMinAdvertisementLength - 1};
+
+ BleAdvertisement short_ble_advertisement{false,
+ short_ble_advertisement_bytes};
+
+ EXPECT_FALSE(short_ble_advertisement.IsValid());
+}
+
+TEST(BleAdvertisementTest,
+ ConstructionFromShortLengthBytesFailsForFastAdvertisement) {
+ // Serialize good data into a good Ble Advertisement.
+ ByteArray fast_endpoint_info{std::string(kFastAdvertisementEndpointName)};
+ BleAdvertisement ble_advertisement{kVersion, kPcp, std::string(kEndpointId),
+ fast_endpoint_info, ByteArray{}};
+ ByteArray ble_advertisement_bytes(ble_advertisement);
+
+ // Shorten the valid Ble Advertisement.
+ ByteArray short_ble_advertisement_bytes{
+ ble_advertisement_bytes.data(),
+ BleAdvertisement::kMinAdvertisementLength - 1};
+
+ BleAdvertisement short_ble_advertisement{true, short_ble_advertisement_bytes};
+
+ EXPECT_FALSE(short_ble_advertisement.IsValid());
+}
+
+TEST(BleAdvertisementTest,
+ ConstructionFromByesWithWrongEndpointInfoLengthFails) {
+ // Serialize good data into a good Ble Advertisement.
+ ByteArray service_id_hash{std::string(kServiceIdHashBytes)};
+ ByteArray endpoint_info{std::string(kEndpointName)};
+ BleAdvertisement ble_advertisement{
+ kVersion, kPcp,
+ service_id_hash, std::string(kEndpointId),
+ endpoint_info, std::string(kBluetoothMacAddress),
+ ByteArray{}, kWebRtcState};
+ ByteArray ble_advertisement_bytes(ble_advertisement);
+
+ // Corrupt the EndpointNameLength bits.
+ std::string corrupt_ble_advertisement_string(ble_advertisement_bytes);
+ corrupt_ble_advertisement_string[8] ^= 0x0FF;
+ ByteArray corrupt_ble_advertisement_bytes(corrupt_ble_advertisement_string);
+
+ BleAdvertisement corrupt_ble_advertisement{false,
+ corrupt_ble_advertisement_bytes};
+
+ EXPECT_FALSE(corrupt_ble_advertisement.IsValid());
+}
+
+TEST(BleAdvertisementTest,
+ ConstructionFromByesWithWrongEndpointInfoLengthFailsForFastAdvertisement) {
+ // Serialize good data into a good Ble Advertisement.
+ ByteArray fast_endpoint_info{std::string(kFastAdvertisementEndpointName)};
+ BleAdvertisement ble_advertisement{kVersion, kPcp, std::string(kEndpointId),
+ fast_endpoint_info, ByteArray{}};
+ ByteArray ble_advertisement_bytes = ByteArray(ble_advertisement);
+
+ // Corrupt the EndpointInfoLength bits.
+ std::string corrupt_ble_advertisement_string(ble_advertisement_bytes);
+ corrupt_ble_advertisement_string[5] ^= 0x0FF;
+ ByteArray corrupt_ble_advertisement_bytes(corrupt_ble_advertisement_string);
+
+ BleAdvertisement corrupt_ble_advertisement{true,
+ corrupt_ble_advertisement_bytes};
+
+ EXPECT_FALSE(corrupt_ble_advertisement.IsValid());
+}
+
+} // namespace
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/ble_endpoint_channel.cc b/chromium/third_party/nearby/src/connections/implementation/ble_endpoint_channel.cc
new file mode 100644
index 00000000000..58b026c95e9
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/ble_endpoint_channel.cc
@@ -0,0 +1,65 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/ble_endpoint_channel.h"
+
+#include <string>
+
+#include "internal/platform/ble.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+namespace {
+
+OutputStream* GetOutputStreamOrNull(BleSocket& socket) {
+ if (socket.GetRemotePeripheral().IsValid()) return &socket.GetOutputStream();
+ return nullptr;
+}
+
+InputStream* GetInputStreamOrNull(BleSocket& socket) {
+ if (socket.GetRemotePeripheral().IsValid()) return &socket.GetInputStream();
+ return nullptr;
+}
+
+} // namespace
+
+BleEndpointChannel::BleEndpointChannel(const std::string& channel_name,
+ BleSocket socket)
+ : BaseEndpointChannel(channel_name, GetInputStreamOrNull(socket),
+ GetOutputStreamOrNull(socket)),
+ ble_socket_(std::move(socket)) {}
+
+proto::connections::Medium BleEndpointChannel::GetMedium() const {
+ return proto::connections::Medium::BLE;
+}
+
+int BleEndpointChannel::GetMaxTransmitPacketSize() const {
+ return kDefaultBleMaxTransmitPacketSize;
+}
+
+void BleEndpointChannel::CloseImpl() {
+ auto status = ble_socket_.Close();
+ if (!status.Ok()) {
+ NEARBY_LOGS(INFO)
+ << "Failed to close underlying socket for BleEndpointChannel "
+ << GetName() << ": exception=" << status.value;
+ }
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/ble_endpoint_channel.h b/chromium/third_party/nearby/src/connections/implementation/ble_endpoint_channel.h
new file mode 100644
index 00000000000..5d756a001c6
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/ble_endpoint_channel.h
@@ -0,0 +1,46 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_BLE_ENDPOINT_CHANNEL_H_
+#define CORE_INTERNAL_BLE_ENDPOINT_CHANNEL_H_
+
+#include "connections/implementation/base_endpoint_channel.h"
+#include "internal/platform/ble.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+class BleEndpointChannel final : public BaseEndpointChannel {
+ public:
+ // Creates both outgoing and incoming Ble channels.
+ BleEndpointChannel(const std::string& channel_name, BleSocket socket);
+
+ proto::connections::Medium GetMedium() const override;
+
+ int GetMaxTransmitPacketSize() const override;
+
+ private:
+ static constexpr int kDefaultBleMaxTransmitPacketSize = 512; // 512 bytes
+
+ void CloseImpl() override;
+
+ BleSocket ble_socket_;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_BLE_ENDPOINT_CHANNEL_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/bluetooth_bwu_handler.cc b/chromium/third_party/nearby/src/connections/implementation/bluetooth_bwu_handler.cc
new file mode 100644
index 00000000000..2a8ec0dfad3
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/bluetooth_bwu_handler.cc
@@ -0,0 +1,165 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/bluetooth_bwu_handler.h"
+
+#include "absl/functional/bind_front.h"
+#include "connections/implementation/bluetooth_endpoint_channel.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/offline_frames.h"
+
+// Manages the Bluetooth-specific methods needed to upgrade an {@link
+// EndpointChannel}.
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+BluetoothBwuHandler::BluetoothBwuHandler(
+ Mediums& mediums, EndpointChannelManager& channel_manager,
+ BwuNotifications notifications)
+ : BaseBwuHandler(channel_manager, std::move(notifications)),
+ mediums_(mediums) {}
+
+void BluetoothBwuHandler::Revert() {
+ for (const std::string& service_id : active_service_ids_) {
+ bluetooth_medium_.StopAcceptingConnections(service_id);
+ }
+ active_service_ids_.clear();
+ NEARBY_LOG(INFO,
+ "BluetoothBwuHandler successfully reverted all Bluetooth state.");
+}
+
+// Accept Connection Callback.
+// Notifies that the remote party called BluetoothClassic::Connect()
+// for this socket.
+void BluetoothBwuHandler::OnIncomingBluetoothConnection(
+ ClientProxy* client, const std::string& service_id,
+ BluetoothSocket socket) {
+ auto channel =
+ absl::make_unique<BluetoothEndpointChannel>(service_id, socket);
+ std::unique_ptr<IncomingSocketConnection> connection{
+ new IncomingSocketConnection{
+ .socket =
+ std::make_unique<BluetoothIncomingSocket>(service_id, socket),
+ .channel = std::move(channel),
+ }};
+ bwu_notifications_.incoming_connection_cb(client, std::move(connection));
+}
+
+// Called by BWU initiator. BT Medium is set up, and BWU request is prepared,
+// with necessary info (service_id, MAC address) for remote party to perform
+// discovery.
+ByteArray BluetoothBwuHandler::InitializeUpgradedMediumForEndpoint(
+ ClientProxy* client, const std::string& service_id,
+ const std::string& endpoint_id) {
+ std::string upgrade_service_id = Utils::WrapUpgradeServiceId(service_id);
+
+ std::string mac_address = bluetooth_medium_.GetMacAddress();
+ if (mac_address.empty()) {
+ return {};
+ }
+
+ if (!bluetooth_medium_.IsAcceptingConnections(upgrade_service_id)) {
+ if (!bluetooth_medium_.StartAcceptingConnections(
+ upgrade_service_id,
+ {
+ .accepted_cb = absl::bind_front(
+ &BluetoothBwuHandler::OnIncomingBluetoothConnection, this,
+ client, service_id),
+ })) {
+ NEARBY_LOGS(ERROR) << "BluetoothBwuHandler couldn't initiate the "
+ "BLUETOOTH upgrade for endpoint "
+ << endpoint_id
+ << " because it failed to start listening for "
+ "incoming Bluetooth connections.";
+
+ return {};
+ }
+ NEARBY_LOGS(VERBOSE)
+ << "BluetoothBwuHandler successfully started listening for incoming "
+ "Bluetooth connections on serviceid="
+ << upgrade_service_id << " while upgrading endpoint " << endpoint_id;
+ }
+ // cache service ID to revert
+ active_service_ids_.emplace(upgrade_service_id);
+
+ return parser::ForBwuBluetoothPathAvailable(upgrade_service_id, mac_address);
+}
+
+// Called by BWU target. Retrieves a new medium info from incoming message,
+// and establishes connection over BT using this info.
+// Returns a channel ready to exchange data or nullptr on error.
+std::unique_ptr<EndpointChannel>
+BluetoothBwuHandler::CreateUpgradedEndpointChannel(
+ ClientProxy* client, const std::string& service_id,
+ const std::string& endpoint_id, const UpgradePathInfo& upgrade_path_info) {
+ const UpgradePathInfo::BluetoothCredentials& bluetooth_credentials =
+ upgrade_path_info.bluetooth_credentials();
+ if (!bluetooth_credentials.has_service_name() ||
+ !bluetooth_credentials.has_mac_address()) {
+ NEARBY_LOG(ERROR, "BluetoothBwuHandler failed to parse UpgradePathInfo.");
+ return nullptr;
+ }
+
+ const std::string& service_name = bluetooth_credentials.service_name();
+ const std::string& mac_address = bluetooth_credentials.mac_address();
+
+ NEARBY_LOGS(VERBOSE) << "BluetoothBwuHandler is attempting to connect to "
+ "available Bluetooth device "
+ << service_name << ", " << mac_address
+ << ") for endpoint " << endpoint_id;
+
+ BluetoothDevice device = bluetooth_medium_.GetRemoteDevice(mac_address);
+ if (!device.IsValid()) {
+ NEARBY_LOGS(ERROR)
+ << "BluetoothBwuHandler failed to derive a valid Bluetooth device "
+ "from the MAC address ("
+ << mac_address << ") for endpoint " << endpoint_id;
+ return nullptr;
+ }
+
+ BluetoothSocket socket = bluetooth_medium_.Connect(
+ device, service_name, client->GetCancellationFlag(endpoint_id));
+ if (!socket.IsValid()) {
+ NEARBY_LOGS(ERROR)
+ << "BluetoothBwuHandler failed to connect to the Bluetooth device ("
+ << service_name << ", " << mac_address << ") for endpoint "
+ << endpoint_id;
+ return nullptr;
+ }
+
+ NEARBY_LOGS(VERBOSE)
+ << "BluetoothBwuHandler successfully connected to Bluetooth device ("
+ << service_name << ", " << mac_address << ") while upgrading endpoint "
+ << endpoint_id;
+
+ auto channel =
+ std::make_unique<BluetoothEndpointChannel>(service_name, socket);
+ if (channel == nullptr) {
+ NEARBY_LOGS(ERROR)
+ << "BluetoothBwuHandler failed to create Bluetooth endpoint "
+ "channel to the Bluetooth device ("
+ << service_name << ", " << mac_address << ") for endpoint "
+ << endpoint_id;
+ socket.Close();
+ return nullptr;
+ }
+
+ return channel;
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/bluetooth_bwu_handler.h b/chromium/third_party/nearby/src/connections/implementation/bluetooth_bwu_handler.h
new file mode 100644
index 00000000000..b7cd3b4ef90
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/bluetooth_bwu_handler.h
@@ -0,0 +1,95 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_BLUETOOTH_BWU_HANDLER_H_
+#define CORE_INTERNAL_BLUETOOTH_BWU_HANDLER_H_
+
+#include <string>
+
+#include "connections/implementation/base_bwu_handler.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/mediums/mediums.h"
+#include "connections/implementation/mediums/utils.h"
+#include "internal/platform/bluetooth_classic.h"
+#include "internal/platform/count_down_latch.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Defines the set of methods that need to be implemented to handle the
+// per-Medium-specific operations needed to upgrade an EndpointChannel.
+class BluetoothBwuHandler : public BaseBwuHandler {
+ public:
+ BluetoothBwuHandler(Mediums& mediums, EndpointChannelManager& channel_manager,
+ BwuNotifications notifications);
+ ~BluetoothBwuHandler() override = default;
+
+ private:
+ constexpr static const int kServiceIdLength = 10;
+
+ // Implements BaseBwuHandler:
+ // Reverts any changes made to the device in the process of upgrading
+ // endpoints.
+ void Revert() override;
+
+ // Cleans up in-progress upgrades after endpoint disconnection.
+ void OnEndpointDisconnect(ClientProxy* client,
+ const std::string& endpoint_id) override {}
+
+ void OnIncomingBluetoothConnection(ClientProxy* client,
+ const std::string& service_id,
+ BluetoothSocket socket);
+
+ class BluetoothIncomingSocket : public IncomingSocket {
+ public:
+ explicit BluetoothIncomingSocket(const std::string& name,
+ BluetoothSocket socket)
+ : name_(name), socket_(socket) {}
+ ~BluetoothIncomingSocket() override = default;
+ std::string ToString() override { return name_; }
+ void Close() override { socket_.Close(); }
+
+ private:
+ std::string name_;
+ BluetoothSocket socket_;
+ };
+
+ // First part of InitiateBwuForEndpoint implementation;
+ // returns a BWU request to remote party as byte array.
+ ByteArray InitializeUpgradedMediumForEndpoint(
+ ClientProxy* client, const std::string& service_id,
+ const std::string& endpoint_id) override;
+
+ // Invoked from OnBwuNegotiationFrame.
+ std::unique_ptr<EndpointChannel> CreateUpgradedEndpointChannel(
+ ClientProxy* client, const std::string& service_id,
+ const std::string& endpoint_id,
+ const UpgradePathInfo& upgrade_path_info) override;
+
+ // Returns the upgrade medium of the BwuHandler.
+ // @BwuHandlerThread
+ Medium GetUpgradeMedium() const override { return Medium::BLUETOOTH; }
+
+ Mediums& mediums_;
+ absl::flat_hash_set<std::string> active_service_ids_;
+ BluetoothRadio& bluetooth_radio_{mediums_.GetBluetoothRadio()};
+ BluetoothClassic& bluetooth_medium_{mediums_.GetBluetoothClassic()};
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_BLUETOOTH_BWU_HANDLER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/bluetooth_device_name.cc b/chromium/third_party/nearby/src/connections/implementation/bluetooth_device_name.cc
new file mode 100644
index 00000000000..bb58d0d2fb2
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/bluetooth_device_name.cc
@@ -0,0 +1,212 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/bluetooth_device_name.h"
+
+#include <inttypes.h>
+
+#include <cstring>
+#include <utility>
+
+#include "absl/strings/escaping.h"
+#include "absl/strings/str_cat.h"
+#include "internal/platform/base64_utils.h"
+#include "internal/platform/base_input_stream.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+BluetoothDeviceName::BluetoothDeviceName(Version version, Pcp pcp,
+ absl::string_view endpoint_id,
+ const ByteArray& service_id_hash,
+ const ByteArray& endpoint_info,
+ const ByteArray& uwb_address,
+ WebRtcState web_rtc_state) {
+ if (version != Version::kV1 || endpoint_id.empty() ||
+ endpoint_id.length() != kEndpointIdLength ||
+ service_id_hash.size() != kServiceIdHashLength) {
+ return;
+ }
+ switch (pcp) {
+ case Pcp::kP2pCluster: // Fall through
+ case Pcp::kP2pStar: // Fall through
+ case Pcp::kP2pPointToPoint:
+ break;
+ default:
+ return;
+ }
+
+ version_ = version;
+ pcp_ = pcp;
+ endpoint_id_ = std::string(endpoint_id);
+ service_id_hash_ = service_id_hash;
+ endpoint_info_ = endpoint_info;
+ uwb_address_ = uwb_address;
+ web_rtc_state_ = web_rtc_state;
+}
+
+BluetoothDeviceName::BluetoothDeviceName(
+ absl::string_view bluetooth_device_name_string) {
+ ByteArray bluetooth_device_name_bytes =
+ Base64Utils::Decode(bluetooth_device_name_string);
+ if (bluetooth_device_name_bytes.Empty()) {
+ return;
+ }
+
+ if (bluetooth_device_name_bytes.size() < kMinBluetoothDeviceNameLength) {
+ NEARBY_LOG(INFO,
+ "Cannot deserialize BluetoothDeviceName: expecting min %d raw "
+ "bytes, got %" PRIu64,
+ kMinBluetoothDeviceNameLength,
+ bluetooth_device_name_bytes.size());
+ return;
+ }
+
+ BaseInputStream base_input_stream{bluetooth_device_name_bytes};
+ // The first 1 byte is supposed to be the version and pcp.
+ auto version_and_pcp_byte = static_cast<char>(base_input_stream.ReadUint8());
+ // The upper 3 bits are supposed to be the version.
+ version_ =
+ static_cast<Version>((version_and_pcp_byte & kVersionBitmask) >> 5);
+ if (version_ != Version::kV1) {
+ NEARBY_LOG(INFO,
+ "Cannot deserialize BluetoothDeviceName: unsupported version=%d",
+ version_);
+ return;
+ }
+ // The lower 5 bits are supposed to be the Pcp.
+ pcp_ = static_cast<Pcp>(version_and_pcp_byte & kPcpBitmask);
+ switch (pcp_) {
+ case Pcp::kP2pCluster: // Fall through
+ case Pcp::kP2pStar: // Fall through
+ case Pcp::kP2pPointToPoint:
+ break;
+ default:
+ NEARBY_LOG(
+ INFO, "Cannot deserialize BluetoothDeviceName: unsupported V1 PCP %d",
+ pcp_);
+ return;
+ }
+
+ // The next 4 bytes are supposed to be the endpoint_id.
+ endpoint_id_ = std::string{base_input_stream.ReadBytes(kEndpointIdLength)};
+
+ // The next 3 bytes are supposed to be the service_id_hash.
+ service_id_hash_ = base_input_stream.ReadBytes(kServiceIdHashLength);
+
+ // The next 1 byte is field containning WebRtc state.
+ auto field_byte = static_cast<char>(base_input_stream.ReadUint8());
+ web_rtc_state_ = (field_byte & kWebRtcConnectableFlagBitmask) == 1
+ ? WebRtcState::kConnectable
+ : WebRtcState::kUnconnectable;
+
+ // The next 6 bytes are supposed to be reserved, and can be left
+ // untouched.
+ base_input_stream.ReadBytes(kReservedLength);
+
+ // The next 1 byte is supposed to be the length of the endpoint_info.
+ std::uint32_t expected_endpoint_info_length = base_input_stream.ReadUint8();
+
+ // The rest bytes are supposed to be the endpoint_info
+ endpoint_info_ = base_input_stream.ReadBytes(expected_endpoint_info_length);
+ if (endpoint_info_.Empty() ||
+ endpoint_info_.size() != expected_endpoint_info_length) {
+ NEARBY_LOG(INFO,
+ "Cannot deserialize BluetoothDeviceName: expected "
+ "endpoint info to be %d bytes, got %" PRIu64,
+ expected_endpoint_info_length, endpoint_info_.size());
+
+ // Clear enpoint_id for validadity.
+ endpoint_id_.clear();
+ return;
+ }
+
+ // If the input stream has extra bytes, it's for UWB address. The first byte
+ // is the address length. It can be 2-byte short address or 8-byte extended
+ // address.
+ if (base_input_stream.IsAvailable(1)) {
+ // The next 1 byte is supposed to be the length of the uwb_address.
+ std::uint32_t expected_uwb_address_length = base_input_stream.ReadUint8();
+ // If the length of usb_address is not zero, then retrieve it.
+ if (expected_uwb_address_length != 0) {
+ uwb_address_ = base_input_stream.ReadBytes(expected_uwb_address_length);
+ if (uwb_address_.Empty() ||
+ uwb_address_.size() != expected_uwb_address_length) {
+ NEARBY_LOG(INFO,
+ "Cannot deserialize BluetoothDeviceName: "
+ "expected uwbAddress size to be %d bytes, got %" PRIu64,
+ expected_uwb_address_length, uwb_address_.size());
+
+ // Clear enpoint_id for validadity.
+ endpoint_id_.clear();
+ return;
+ }
+ }
+ }
+}
+
+BluetoothDeviceName::operator std::string() const {
+ if (!IsValid()) {
+ return "";
+ }
+
+ // The upper 3 bits are the Version.
+ auto version_and_pcp_byte = static_cast<char>(
+ (static_cast<uint32_t>(Version::kV1) << 5) & kVersionBitmask);
+ // The lower 5 bits are the PCP.
+ version_and_pcp_byte |=
+ static_cast<char>(static_cast<uint32_t>(pcp_) & kPcpBitmask);
+
+ // A byte contains WebRtcState state.
+ int web_rtc_connectable_flag =
+ (web_rtc_state_ == WebRtcState::kConnectable) ? 1 : 0;
+ char field_byte = static_cast<char>(web_rtc_connectable_flag) &
+ kWebRtcConnectableFlagBitmask;
+
+ ByteArray reserved_bytes{kReservedLength};
+
+ ByteArray usable_endpoint_info(endpoint_info_);
+ if (endpoint_info_.size() > kMaxEndpointInfoLength) {
+ NEARBY_LOG(INFO,
+ "While serializing Advertisement, truncating Endpoint Name %s "
+ "(%lu bytes) down to %d bytes",
+ absl::BytesToHexString(endpoint_info_.data()).c_str(),
+ endpoint_info_.size(), kMaxEndpointInfoLength);
+ usable_endpoint_info.SetData(endpoint_info_.data(), kMaxEndpointInfoLength);
+ }
+
+ // clang-format off
+ std::string out = absl::StrCat(std::string(1, version_and_pcp_byte),
+ endpoint_id_,
+ std::string(service_id_hash_),
+ std::string(1, field_byte),
+ std::string(reserved_bytes),
+ std::string(1, usable_endpoint_info.size()),
+ std::string(usable_endpoint_info));
+ // clang-format on
+
+ // If UWB address is available, attach it at the end.
+ if (!uwb_address_.Empty()) {
+ absl::StrAppend(&out, std::string(1, uwb_address_.size()));
+ absl::StrAppend(&out, std::string(uwb_address_));
+ }
+
+ return Base64Utils::Encode(ByteArray{std::move(out)});
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/bluetooth_device_name.h b/chromium/third_party/nearby/src/connections/implementation/bluetooth_device_name.h
new file mode 100644
index 00000000000..fe10956ba4b
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/bluetooth_device_name.h
@@ -0,0 +1,93 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_BLUETOOTH_DEVICE_NAME_H_
+#define CORE_INTERNAL_BLUETOOTH_DEVICE_NAME_H_
+
+#include <cstdint>
+
+#include "absl/strings/string_view.h"
+#include "connections/implementation/base_pcp_handler.h"
+#include "connections/implementation/pcp.h"
+#include "internal/platform/byte_array.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Represents the format of the Bluetooth device name used in Advertising +
+// Discovery.
+//
+// <p>See go/nearby-offline-data-interchange-formats for the specification.
+class BluetoothDeviceName {
+ public:
+ // Versions of the BluetoothDeviceName.
+ enum class Version {
+ kUndefined = 0,
+ kV1 = 1,
+ // Version is only allocated 3 bits in the BluetoothDeviceName, so this
+ // can never go beyond V7.
+ };
+
+ static constexpr int kServiceIdHashLength = 3;
+
+ BluetoothDeviceName() = default;
+ BluetoothDeviceName(Version version, Pcp pcp, absl::string_view endpoint_id,
+ const ByteArray& service_id_hash,
+ const ByteArray& endpoint_info,
+ const ByteArray& uwb_address, WebRtcState web_rtc_state);
+ explicit BluetoothDeviceName(absl::string_view bluetooth_device_name_string);
+ BluetoothDeviceName(const BluetoothDeviceName&) = default;
+ BluetoothDeviceName& operator=(const BluetoothDeviceName&) = default;
+ BluetoothDeviceName(BluetoothDeviceName&&) = default;
+ BluetoothDeviceName& operator=(BluetoothDeviceName&&) = default;
+ ~BluetoothDeviceName() = default;
+
+ explicit operator std::string() const;
+
+ bool IsValid() const { return !endpoint_id_.empty(); }
+ Version GetVersion() const { return version_; }
+ Pcp GetPcp() const { return pcp_; }
+ std::string GetEndpointId() const { return endpoint_id_; }
+ ByteArray GetServiceIdHash() const { return service_id_hash_; }
+ ByteArray GetEndpointInfo() const { return endpoint_info_; }
+ ByteArray GetUwbAddress() const { return uwb_address_; }
+ WebRtcState GetWebRtcState() const { return web_rtc_state_; }
+
+ private:
+ static constexpr int kEndpointIdLength = 4;
+ static constexpr int kReservedLength = 6;
+ static constexpr int kMaxEndpointInfoLength = 131;
+ static constexpr int kMinBluetoothDeviceNameLength = 16;
+
+ static constexpr int kVersionBitmask = 0x0E0;
+ static constexpr int kPcpBitmask = 0x01F;
+ static constexpr int kEndpointNameLengthBitmask = 0x0FF;
+ static constexpr int kWebRtcConnectableFlagBitmask = 0x01;
+
+ Version version_{Version::kUndefined};
+ Pcp pcp_{Pcp::kUnknown};
+ std::string endpoint_id_;
+ ByteArray service_id_hash_;
+ ByteArray endpoint_info_;
+ // TODO(b/169550050): Define UWB address field.
+ ByteArray uwb_address_;
+ WebRtcState web_rtc_state_{WebRtcState::kUndefined};
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_BLUETOOTH_DEVICE_NAME_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/bluetooth_device_name_test.cc b/chromium/third_party/nearby/src/connections/implementation/bluetooth_device_name_test.cc
new file mode 100644
index 00000000000..4419451e3a2
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/bluetooth_device_name_test.cc
@@ -0,0 +1,207 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/bluetooth_device_name.h"
+
+#include <cstring>
+#include <memory>
+
+#include "gtest/gtest.h"
+#include "internal/platform/base64_utils.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+
+constexpr BluetoothDeviceName::Version kVersion =
+ BluetoothDeviceName::Version::kV1;
+constexpr Pcp kPcp = Pcp::kP2pCluster;
+constexpr absl::string_view kEndPointID{"AB12"};
+constexpr absl::string_view kServiceIDHashBytes{"\x0a\x0b\x0c"};
+constexpr absl::string_view kEndPointName{"RAWK + ROWL!"};
+constexpr WebRtcState kWebRtcState = WebRtcState::kConnectable;
+
+// TODO(b/169550050): Implement UWBAddress.
+TEST(BluetoothDeviceNameTest, ConstructionWorks) {
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ ByteArray endpoint_info{std::string(kEndPointName)};
+ BluetoothDeviceName bluetooth_device_name{
+ kVersion, kPcp, kEndPointID, service_id_hash,
+ endpoint_info, ByteArray{}, kWebRtcState};
+
+ EXPECT_TRUE(bluetooth_device_name.IsValid());
+ EXPECT_EQ(kVersion, bluetooth_device_name.GetVersion());
+ EXPECT_EQ(kPcp, bluetooth_device_name.GetPcp());
+ EXPECT_EQ(kEndPointID, bluetooth_device_name.GetEndpointId());
+ EXPECT_EQ(service_id_hash, bluetooth_device_name.GetServiceIdHash());
+ EXPECT_EQ(endpoint_info, bluetooth_device_name.GetEndpointInfo());
+ EXPECT_EQ(kWebRtcState, bluetooth_device_name.GetWebRtcState());
+}
+
+TEST(BluetoothDeviceNameTest, ConstructionWorksWithEmptyEndpointName) {
+ ByteArray empty_endpoint_info;
+
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ BluetoothDeviceName bluetooth_device_name{kVersion,
+ kPcp,
+ kEndPointID,
+ service_id_hash,
+ empty_endpoint_info,
+ ByteArray{},
+ kWebRtcState};
+
+ EXPECT_TRUE(bluetooth_device_name.IsValid());
+ EXPECT_EQ(kVersion, bluetooth_device_name.GetVersion());
+ EXPECT_EQ(kPcp, bluetooth_device_name.GetPcp());
+ EXPECT_EQ(kEndPointID, bluetooth_device_name.GetEndpointId());
+ EXPECT_EQ(service_id_hash, bluetooth_device_name.GetServiceIdHash());
+ EXPECT_EQ(empty_endpoint_info, bluetooth_device_name.GetEndpointInfo());
+ EXPECT_EQ(kWebRtcState, bluetooth_device_name.GetWebRtcState());
+}
+
+TEST(BluetoothDeviceNameTest, ConstructionFailsWithBadVersion) {
+ auto bad_version = static_cast<BluetoothDeviceName::Version>(666);
+
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ ByteArray endpoint_info{std::string(kEndPointName)};
+ BluetoothDeviceName bluetooth_device_name{
+ bad_version, kPcp, kEndPointID, service_id_hash,
+ endpoint_info, ByteArray{}, kWebRtcState};
+
+ EXPECT_FALSE(bluetooth_device_name.IsValid());
+}
+
+TEST(BluetoothDeviceNameTest, ConstructionFailsWithBadPcp) {
+ auto bad_pcp = static_cast<Pcp>(666);
+
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ ByteArray endpoint_info{std::string(kEndPointName)};
+ BluetoothDeviceName bluetooth_device_name{
+ kVersion, bad_pcp, kEndPointID, service_id_hash,
+ endpoint_info, ByteArray{}, kWebRtcState};
+
+ EXPECT_FALSE(bluetooth_device_name.IsValid());
+}
+
+TEST(BluetoothDeviceNameTest, ConstructionFailsWithShortEndpointId) {
+ std::string short_endpoint_id("AB1");
+
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ ByteArray endpoint_info{std::string(kEndPointName)};
+ BluetoothDeviceName bluetooth_device_name{
+ kVersion, kPcp, short_endpoint_id, service_id_hash,
+ endpoint_info, ByteArray{}, kWebRtcState};
+
+ EXPECT_FALSE(bluetooth_device_name.IsValid());
+}
+
+TEST(BluetoothDeviceNameTest, ConstructionFailsWithLongEndpointId) {
+ std::string long_endpoint_id("AB12X");
+
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ ByteArray endpoint_info{std::string(kEndPointName)};
+ BluetoothDeviceName bluetooth_device_name{
+ kVersion, kPcp, long_endpoint_id, service_id_hash,
+ endpoint_info, ByteArray{}, kWebRtcState};
+
+ EXPECT_FALSE(bluetooth_device_name.IsValid());
+}
+
+TEST(BluetoothDeviceNameTest, ConstructionFailsWithShortServiceIdHash) {
+ char short_service_id_hash_bytes[] = "\x0a\x0b";
+
+ ByteArray short_service_id_hash{short_service_id_hash_bytes};
+ ByteArray endpoint_info{std::string(kEndPointName)};
+ BluetoothDeviceName bluetooth_device_name{
+ kVersion, kPcp, kEndPointID, short_service_id_hash,
+ endpoint_info, ByteArray{}, kWebRtcState};
+
+ EXPECT_FALSE(bluetooth_device_name.IsValid());
+}
+
+TEST(BluetoothDeviceNameTest, ConstructionFailsWithLongServiceIdHash) {
+ char long_service_id_hash_bytes[] = "\x0a\x0b\x0c\x0d";
+
+ ByteArray long_service_id_hash{long_service_id_hash_bytes};
+ ByteArray endpoint_info{std::string(kEndPointName)};
+ BluetoothDeviceName bluetooth_device_name{
+ kVersion, kPcp, kEndPointID, long_service_id_hash,
+ endpoint_info, ByteArray{}, kWebRtcState};
+
+ EXPECT_FALSE(bluetooth_device_name.IsValid());
+}
+
+TEST(BluetoothDeviceNameTest, ConstructionFailsWithShortStringLength) {
+ char bluetooth_device_name_string[] = "X";
+
+ ByteArray bluetooth_device_name_bytes{bluetooth_device_name_string};
+ BluetoothDeviceName bluetooth_device_name{
+ Base64Utils::Encode(bluetooth_device_name_bytes)};
+
+ EXPECT_FALSE(bluetooth_device_name.IsValid());
+}
+
+TEST(BluetoothDeviceNameTest, ConstructionFailsWithWrongEndpointNameLength) {
+ // Serialize good data into a good Bluetooth Device Name.
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ ByteArray endpoint_info{std::string(kEndPointName)};
+ BluetoothDeviceName bluetooth_device_name{
+ kVersion, kPcp, kEndPointID, service_id_hash,
+ endpoint_info, ByteArray{}, kWebRtcState};
+ auto bluetooth_device_name_string = std::string(bluetooth_device_name);
+
+ // Base64-decode the good Bluetooth Device Name.
+ ByteArray bluetooth_device_name_bytes =
+ Base64Utils::Decode(bluetooth_device_name_string);
+ // Corrupt the EndpointNameLength bits (120-127) by reversing all of them.
+ std::string corrupt_string(bluetooth_device_name_bytes.data(),
+ bluetooth_device_name_bytes.size());
+ corrupt_string[15] ^= 0x0FF;
+ // Base64-encode the corrupted bytes into a corrupt Bluetooth Device Name.
+ ByteArray corrupt_bluetooth_device_name_bytes{corrupt_string.data(),
+ corrupt_string.size()};
+ std::string corrupt_bluetooth_device_name_string(
+ Base64Utils::Encode(corrupt_bluetooth_device_name_bytes));
+
+ // And deserialize the corrupt Bluetooth Device Name.
+ BluetoothDeviceName corrupt_bluetooth_device_name(
+ corrupt_bluetooth_device_name_string);
+
+ EXPECT_FALSE(corrupt_bluetooth_device_name.IsValid());
+}
+
+TEST(BluetoothDeviceNameTest, CanParseGeneratedName) {
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ ByteArray endpoint_info{std::string(kEndPointName)};
+ // Build name1 from scratch.
+ BluetoothDeviceName name1{kVersion, kPcp, kEndPointID,
+ service_id_hash, endpoint_info, ByteArray{},
+ kWebRtcState};
+ // Build name2 from string composed from name1.
+ BluetoothDeviceName name2{std::string(name1)};
+ EXPECT_TRUE(name1.IsValid());
+ EXPECT_TRUE(name2.IsValid());
+ EXPECT_EQ(name1.GetVersion(), name2.GetVersion());
+ EXPECT_EQ(name1.GetPcp(), name2.GetPcp());
+ EXPECT_EQ(name1.GetEndpointId(), name2.GetEndpointId());
+ EXPECT_EQ(name1.GetServiceIdHash(), name2.GetServiceIdHash());
+ EXPECT_EQ(name1.GetEndpointInfo(), name2.GetEndpointInfo());
+ EXPECT_EQ(name1.GetWebRtcState(), name2.GetWebRtcState());
+}
+
+} // namespace
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/bluetooth_endpoint_channel.cc b/chromium/third_party/nearby/src/connections/implementation/bluetooth_endpoint_channel.cc
new file mode 100644
index 00000000000..8d66110dad2
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/bluetooth_endpoint_channel.cc
@@ -0,0 +1,65 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/bluetooth_endpoint_channel.h"
+
+#include <string>
+
+#include "internal/platform/bluetooth_classic.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+namespace {
+
+OutputStream* GetOutputStreamOrNull(BluetoothSocket& socket) {
+ if (socket.GetRemoteDevice().IsValid()) return &socket.GetOutputStream();
+ return nullptr;
+}
+
+InputStream* GetInputStreamOrNull(BluetoothSocket& socket) {
+ if (socket.GetRemoteDevice().IsValid()) return &socket.GetInputStream();
+ return nullptr;
+}
+
+} // namespace
+
+BluetoothEndpointChannel::BluetoothEndpointChannel(
+ const std::string& channel_name, BluetoothSocket socket)
+ : BaseEndpointChannel(channel_name, GetInputStreamOrNull(socket),
+ GetOutputStreamOrNull(socket)),
+ bluetooth_socket_(std::move(socket)) {}
+
+proto::connections::Medium BluetoothEndpointChannel::GetMedium() const {
+ return proto::connections::Medium::BLUETOOTH;
+}
+
+int BluetoothEndpointChannel::GetMaxTransmitPacketSize() const {
+ return kDefaultBTMaxTransmitPacketSize;
+}
+
+void BluetoothEndpointChannel::CloseImpl() {
+ auto status = bluetooth_socket_.Close();
+ if (!status.Ok()) {
+ NEARBY_LOGS(INFO)
+ << "Failed to close underlying socket for BluetoothEndpointChannel "
+ << GetName() << ": exception=" << status.value;
+ }
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/bluetooth_endpoint_channel.h b/chromium/third_party/nearby/src/connections/implementation/bluetooth_endpoint_channel.h
new file mode 100644
index 00000000000..859f3e4ed8b
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/bluetooth_endpoint_channel.h
@@ -0,0 +1,49 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_BLUETOOTH_ENDPOINT_CHANNEL_H_
+#define CORE_INTERNAL_BLUETOOTH_ENDPOINT_CHANNEL_H_
+
+#include <string>
+
+#include "connections/implementation/base_endpoint_channel.h"
+#include "internal/platform/bluetooth_classic.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+class BluetoothEndpointChannel final : public BaseEndpointChannel {
+ public:
+ // Creates both outgoing and incoming BT channels.
+ BluetoothEndpointChannel(const std::string& channel_name,
+ BluetoothSocket bluetooth_socket);
+
+ proto::connections::Medium GetMedium() const override;
+
+ int GetMaxTransmitPacketSize() const override;
+
+ private:
+ static constexpr int kDefaultBTMaxTransmitPacketSize = 1980; // 990 * 2 Bytes
+
+ void CloseImpl() override;
+
+ BluetoothSocket bluetooth_socket_;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_BLUETOOTH_ENDPOINT_CHANNEL_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/bwu_handler.h b/chromium/third_party/nearby/src/connections/implementation/bwu_handler.h
new file mode 100644
index 00000000000..448b333103e
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/bwu_handler.h
@@ -0,0 +1,89 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_BWU_HANDLER_H_
+#define CORE_INTERNAL_BWU_HANDLER_H_
+
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/endpoint_channel.h"
+#include "connections/implementation/offline_frames.h"
+#include "internal/platform/count_down_latch.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+using BwuNegotiationFrame = BandwidthUpgradeNegotiationFrame;
+
+// Defines the set of methods that need to be implemented to handle the
+// per-Medium-specific operations needed to upgrade an EndpointChannel.
+class BwuHandler {
+ public:
+ using UpgradePathInfo = parser::UpgradePathInfo;
+
+ virtual ~BwuHandler() = default;
+
+ // Called by the Initiator to setup the upgraded medium for this endpoint (if
+ // that hasn't already been done), and returns a serialized UpgradePathInfo
+ // that can be sent to the Responder.
+ // @BwuHandlerThread
+ virtual ByteArray InitializeUpgradedMediumForEndpoint(
+ ClientProxy* client, const std::string& service_id,
+ const std::string& endpoint_id) = 0;
+
+ // Called to revert any state changed by the Initiator to setup the upgraded
+ // medium for an endpoint.
+ // @BwuHandlerThread
+ virtual void Revert() = 0;
+
+ // Called by the Responder to setup the upgraded medium for this endpoint (if
+ // that hasn't already been done) using the UpgradePathInfo sent by the
+ // Initiator, and returns a new EndpointChannel for the upgraded medium.
+ // @BwuHandlerThread
+ virtual std::unique_ptr<EndpointChannel> CreateUpgradedEndpointChannel(
+ ClientProxy* client, const std::string& service_id,
+ const std::string& endpoint_id,
+ const UpgradePathInfo& upgrade_path_info) = 0;
+
+ // Returns the upgrade medium of the BwuHandler.
+ // @BwuHandlerThread
+ virtual Medium GetUpgradeMedium() const = 0;
+ virtual void OnEndpointDisconnect(ClientProxy* client,
+ const std::string& endpoint_id) = 0;
+
+ class IncomingSocket {
+ public:
+ virtual ~IncomingSocket() = default;
+
+ virtual std::string ToString() = 0;
+ virtual void Close() = 0;
+ };
+
+ struct IncomingSocketConnection {
+ std::unique_ptr<IncomingSocket> socket;
+ std::unique_ptr<EndpointChannel> channel;
+ };
+
+ struct BwuNotifications {
+ std::function<void(ClientProxy* client,
+ std::unique_ptr<IncomingSocketConnection> connection)>
+ incoming_connection_cb;
+ };
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_BWU_HANDLER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/bwu_manager.cc b/chromium/third_party/nearby/src/connections/implementation/bwu_manager.cc
new file mode 100644
index 00000000000..86ca7c8ceda
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/bwu_manager.cc
@@ -0,0 +1,1221 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/bwu_manager.h"
+
+#include <algorithm>
+#include <memory>
+
+#include "absl/functional/bind_front.h"
+#include "absl/time/time.h"
+#include "connections/implementation/bluetooth_bwu_handler.h"
+#include "connections/implementation/bwu_handler.h"
+#include "connections/implementation/offline_frames.h"
+#include "connections/implementation/webrtc_bwu_handler.h"
+#include "connections/implementation/wifi_lan_bwu_handler.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/feature_flags.h"
+#include "internal/platform/count_down_latch.h"
+#include "proto/connections_enums.pb.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+using ::location::nearby::proto::connections::DisconnectionReason;
+
+// Required for C++ 14 support in Chrome
+constexpr absl::Duration BwuManager::kReadClientIntroductionFrameTimeout;
+
+BwuManager::BwuManager(
+ Mediums& mediums, EndpointManager& endpoint_manager,
+ EndpointChannelManager& channel_manager,
+ absl::flat_hash_map<Medium, std::unique_ptr<BwuHandler>> handlers,
+ Config config)
+ : config_(config),
+ mediums_(&mediums),
+ endpoint_manager_(&endpoint_manager),
+ channel_manager_(&channel_manager) {
+ if (config_.bandwidth_upgrade_retry_delay == absl::ZeroDuration()) {
+ if (FeatureFlags::GetInstance().GetFlags().use_exp_backoff_in_bwu_retry) {
+ config_.bandwidth_upgrade_retry_delay =
+ FeatureFlags::GetInstance()
+ .GetFlags()
+ .bwu_retry_exp_backoff_initial_delay;
+ } else {
+ config_.bandwidth_upgrade_retry_delay = absl::Seconds(5);
+ }
+ }
+ if (config_.bandwidth_upgrade_retry_max_delay == absl::ZeroDuration()) {
+ if (FeatureFlags::GetInstance().GetFlags().use_exp_backoff_in_bwu_retry) {
+ config_.bandwidth_upgrade_retry_max_delay =
+ FeatureFlags::GetInstance()
+ .GetFlags()
+ .bwu_retry_exp_backoff_maximum_delay;
+ } else {
+ config_.bandwidth_upgrade_retry_max_delay = absl::Seconds(10);
+ }
+ }
+ if (config_.allow_upgrade_to.All(false)) {
+ config_.allow_upgrade_to.web_rtc = true;
+ config_.allow_upgrade_to.wifi_lan = true;
+ }
+ if (!handlers.empty()) {
+ handlers_ = std::move(handlers);
+ } else {
+ InitBwuHandlers();
+ }
+
+ // Register the offline frame processor.
+ endpoint_manager_->RegisterFrameProcessor(
+ V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION, this);
+}
+
+BwuManager::~BwuManager() {
+ NEARBY_LOGS(INFO) << "BwuManager going down";
+ Shutdown();
+}
+
+void BwuManager::InitBwuHandlers() {
+ // Register the supported concrete BwuMedium implementations.
+ BwuHandler::BwuNotifications notifications{
+ .incoming_connection_cb =
+ absl::bind_front(&BwuManager::OnIncomingConnection, this),
+ };
+ if (config_.allow_upgrade_to.wifi_lan) {
+ handlers_.emplace(Medium::WIFI_LAN,
+ std::make_unique<WifiLanBwuHandler>(
+ *mediums_, *channel_manager_, notifications));
+ }
+ if (config_.allow_upgrade_to.web_rtc) {
+ handlers_.emplace(Medium::WEB_RTC,
+ std::make_unique<WebrtcBwuHandler>(
+ *mediums_, *channel_manager_, notifications));
+ }
+ if (config_.allow_upgrade_to.bluetooth) {
+ handlers_.emplace(Medium::BLUETOOTH,
+ std::make_unique<BluetoothBwuHandler>(
+ *mediums_, *channel_manager_, notifications));
+ }
+}
+
+void BwuManager::Shutdown() {
+ NEARBY_LOGS(INFO) << "Initiating shutdown of BwuManager.";
+
+ endpoint_manager_->UnregisterFrameProcessor(
+ V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION, this);
+
+ // Stop all the ongoing Runnables (as gracefully as possible).
+ alarm_executor_.Shutdown();
+ serial_executor_.Shutdown();
+
+ // After worker threads are down we became exclusive owners of data and
+ // may access it from current thread.
+ for (auto& item : previous_endpoint_channels_) {
+ EndpointChannel* channel = item.second.get();
+ if (!channel) continue;
+ channel->Close(DisconnectionReason::SHUTDOWN);
+ }
+
+ CancelAllRetryUpgradeAlarms();
+ medium_ = Medium::UNKNOWN_MEDIUM;
+ for (auto& item : handlers_) {
+ BwuHandler& handler = *item.second;
+ handler.Revert();
+ }
+ handlers_.clear();
+
+ NEARBY_LOGS(INFO) << "BwuHandler has shut down.";
+}
+
+// This is the point on the Initiator side where the
+// medium_ is set.
+void BwuManager::InitiateBwuForEndpoint(ClientProxy* client,
+ const std::string& endpoint_id,
+ Medium new_medium) {
+ NEARBY_LOGS(INFO) << "InitiateBwuForEndpoint for endpoint " << endpoint_id
+ << " with medium " << new_medium;
+ RunOnBwuManagerThread("bwu-init", [this, client, endpoint_id, new_medium]() {
+ Medium proposed_medium = ChooseBestUpgradeMedium(
+ client->GetUpgradeMediums(endpoint_id).GetMediums(true));
+ if (new_medium != Medium::UNKNOWN_MEDIUM) {
+ proposed_medium = new_medium;
+ }
+ auto* handler = SetCurrentBwuHandler(proposed_medium);
+ if (!handler) {
+ NEARBY_LOGS(ERROR)
+ << "BwuManager cannot initiate bandwidth upgrade for endpoint "
+ << endpoint_id
+ << " because the current BandwidthUpgradeMedium cannot be deduced.";
+ return;
+ }
+
+ if (in_progress_upgrades_.contains(endpoint_id)) {
+ NEARBY_LOGS(INFO)
+ << "BwuManager is ignoring bandwidth upgrade for endpoint "
+ << endpoint_id
+ << " because we're already upgrading bandwidth for that endpoint.";
+
+ return;
+ }
+ CancelRetryUpgradeAlarm(endpoint_id);
+
+ auto channel = channel_manager_->GetChannelForEndpoint(endpoint_id);
+ Medium channel_medium =
+ channel ? channel->GetMedium() : Medium::UNKNOWN_MEDIUM;
+ client->GetAnalyticsRecorder().OnBandwidthUpgradeStarted(
+ endpoint_id, channel_medium, medium_, proto::connections::INCOMING,
+ client->GetConnectionToken(endpoint_id));
+ if (channel == nullptr) {
+ NEARBY_LOGS(INFO)
+ << "BwuManager couldn't complete the upgrade for endpoint "
+ << endpoint_id
+ << " because it couldn't find an existing EndpointChannel for it.";
+ client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
+ endpoint_id, proto::connections::CHANNEL_ERROR,
+ proto::connections::NETWORK_AVAILABLE);
+ return;
+ }
+
+ // Ignore requests where the medium we're upgrading to is the medium we're
+ // already connected over. This can happen now that Bluetooth is both an
+ // advertising medium and a potential bandwidth upgrade, and will continue
+ // to be possible as we add other new advertising mediums like mDNS (WiFi
+ // LAN). Very specifically, this happens now when a device uses P2P_CLUSTER,
+ // connects over Bluetooth, and is not connected to LAN. Bluetooth is the
+ // best medium, and we attempt to upgrade from Bluetooth to Bluetooth.
+ // if (medium_ == channel->GetMedium()) {
+ NEARBY_LOGS(INFO) << "BwuManager ignoring the upgrade for endpoint "
+ << endpoint_id
+ << " because it is already connected over medium "
+ << proto::connections::Medium_Name(medium_);
+ if (medium_ == channel->GetMedium()) {
+ return;
+ }
+
+ std::string service_id = client->GetServiceId();
+ ByteArray bytes = handler->InitializeUpgradedMediumForEndpoint(
+ client, service_id, endpoint_id);
+
+ // Because we grab the endpointChannel first thing, it is possible the
+ // endpointChannel is stale by the time we attempt to write over it.
+ if (bytes.Empty()) {
+ NEARBY_LOGS(ERROR)
+ << "BwuManager couldn't complete the upgrade for endpoint "
+ << endpoint_id << " to medium "
+ << proto::connections::Medium_Name(medium_)
+ << " because it failed to initialize the "
+ "BWU_NEGOTIATION.UPGRADE_PATH_AVAILABLE OfflineFrame.";
+ UpgradePathInfo info;
+ info.set_medium(parser::MediumToUpgradePathInfoMedium(medium_));
+
+ ProcessUpgradeFailureEvent(client, endpoint_id, info);
+ client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
+ endpoint_id, proto::connections::RESULT_IO_ERROR,
+ proto::connections::NETWORK_AVAILABLE);
+ return;
+ }
+ if (!channel->Write(bytes).Ok()) {
+ NEARBY_LOGS(ERROR)
+ << "BwuManager couldn't complete the upgrade for endpoint "
+ << endpoint_id << " to medium "
+ << proto::connections::Medium_Name(medium_)
+ << " because it failed to write the "
+ "BWU_NEGOTIATION.UPGRADE_PATH_AVAILABLE OfflineFrame.";
+ return;
+ }
+
+ NEARBY_LOGS(INFO)
+ << "BwuManager successfully wrote the "
+ "BWU_NEGOTIATION.UPGRADE_PATH_AVAILABLE OfflineFrame while "
+ "upgrading endpoint "
+ << endpoint_id << " to medium"
+ << proto::connections::Medium_Name(medium_);
+ in_progress_upgrades_.emplace(endpoint_id, client);
+ });
+}
+
+void BwuManager::OnIncomingFrame(OfflineFrame& frame,
+ const std::string& endpoint_id,
+ ClientProxy* client, Medium medium) {
+ NEARBY_LOGS(INFO) << "OnIncomingFrame for endpoint " << endpoint_id
+ << " with medium "
+ << proto::connections::Medium_Name(medium);
+ if (parser::GetFrameType(frame) != V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION)
+ return;
+ auto bwu_frame = frame.v1().bandwidth_upgrade_negotiation();
+ if (FeatureFlags::GetInstance().GetFlags().enable_async_bandwidth_upgrade) {
+ RunOnBwuManagerThread(
+ "bwu-on-incoming-frame", [this, client, endpoint_id, bwu_frame]() {
+ OnBwuNegotiationFrame(client, bwu_frame, endpoint_id);
+ });
+ } else {
+ CountDownLatch latch(1);
+ RunOnBwuManagerThread("bwu-on-incoming-frame", [this, client, endpoint_id,
+ bwu_frame, &latch]() {
+ OnBwuNegotiationFrame(client, bwu_frame, endpoint_id);
+ latch.CountDown();
+ });
+ latch.Await();
+ }
+}
+
+void BwuManager::OnEndpointDisconnect(ClientProxy* client,
+ const std::string& endpoint_id,
+ CountDownLatch barrier) {
+ NEARBY_LOGS(INFO)
+ << "BwuManager has processed endpoint disconnection for endpoint "
+ << endpoint_id;
+ RunOnBwuManagerThread(
+ "bwu-on-endpoint-disconnect",
+ [this, client, endpoint_id, barrier]() mutable {
+ if (medium_ == Medium::UNKNOWN_MEDIUM) {
+ NEARBY_LOGS(INFO)
+ << "BwuManager has processed endpoint disconnection for endpoint "
+ << endpoint_id
+ << " because there is no current BandwidthUpgradeMedium.";
+ barrier.CountDown();
+ return;
+ }
+
+ if (handler_) {
+ handler_->OnEndpointDisconnect(client, endpoint_id);
+ }
+
+ auto item = previous_endpoint_channels_.extract(endpoint_id);
+
+ if (!item.empty()) {
+ auto old_channel = item.mapped();
+ if (old_channel != nullptr) {
+ old_channel->Close(DisconnectionReason::SHUTDOWN);
+ }
+ }
+ in_progress_upgrades_.erase(endpoint_id);
+ retry_delays_.erase(endpoint_id);
+ CancelRetryUpgradeAlarm(endpoint_id);
+
+ successfully_upgraded_endpoints_.erase(endpoint_id);
+
+ // If this was our very last endpoint:
+ //
+ // a) revert all the changes for currentBwuMedium.
+ // b) reset currentBwuMedium.
+ if (channel_manager_->GetConnectedEndpointsCount() <= 1) {
+ Revert();
+ }
+ barrier.CountDown();
+ });
+}
+
+BwuHandler* BwuManager::SetCurrentBwuHandler(Medium medium) {
+ NEARBY_LOGS(INFO) << "SetCurrentBwuHandler to medium "
+ << proto::connections::Medium_Name(medium);
+ handler_ = nullptr;
+ medium_ = medium;
+ if (medium != Medium::UNKNOWN_MEDIUM) {
+ auto item = handlers_.find(medium);
+ if (item != handlers_.end()) {
+ handler_ = item->second.get();
+ }
+ }
+ return handler_;
+}
+
+void BwuManager::Revert() {
+ NEARBY_LOGS(INFO) << "Revert reseting medium "
+ << proto::connections::Medium_Name(medium_);
+ if (handler_) {
+ handler_->Revert();
+ handler_ = nullptr;
+ }
+ medium_ = Medium::UNKNOWN_MEDIUM;
+}
+
+void BwuManager::OnBwuNegotiationFrame(ClientProxy* client,
+ const BwuNegotiationFrame frame,
+ const string& endpoint_id) {
+ NEARBY_LOGS(INFO) << "BwuManager process incoming OfflineFrame for endpoint "
+ << endpoint_id;
+ switch (frame.event_type()) {
+ case BwuNegotiationFrame::UPGRADE_PATH_AVAILABLE:
+ ProcessBwuPathAvailableEvent(client, endpoint_id,
+ frame.upgrade_path_info());
+ break;
+ case BwuNegotiationFrame::UPGRADE_FAILURE:
+ ProcessUpgradeFailureEvent(client, endpoint_id,
+ frame.upgrade_path_info());
+ break;
+ case BwuNegotiationFrame::LAST_WRITE_TO_PRIOR_CHANNEL:
+ ProcessLastWriteToPriorChannelEvent(client, endpoint_id);
+ break;
+ case BwuNegotiationFrame::SAFE_TO_CLOSE_PRIOR_CHANNEL:
+ ProcessSafeToClosePriorChannelEvent(client, endpoint_id);
+ break;
+ default:
+ NEARBY_LOGS(WARNING)
+ << "BwuManager can't process unknown incoming OfflineFrame of type "
+ << frame.event_type() << ", ignoring it.";
+ break;
+ }
+}
+
+void BwuManager::OnIncomingConnection(
+ ClientProxy* client,
+ std::unique_ptr<BwuHandler::IncomingSocketConnection> mutable_connection) {
+ NEARBY_LOGS(INFO) << "BwuManager process incoming connection service_id="
+ << client->GetServiceId();
+ std::shared_ptr<BwuHandler::IncomingSocketConnection> connection(
+ mutable_connection.release());
+ RunOnBwuManagerThread(
+ "bwu-on-incoming-connection", [this, client, connection]() {
+ absl::Time connection_attempt_start_time =
+ SystemClock::ElapsedRealtime();
+ EndpointChannel* channel = connection->channel.get();
+ if (channel == nullptr) {
+ NEARBY_LOGS(ERROR)
+ << "BwuManager failed to create new EndpointChannel for incoming "
+ "socket.";
+ connection->socket->Close();
+ AttemptToRecordBandwidthUpgradeErrorForUnknownEndpoint(
+ proto::connections::MEDIUM_ERROR,
+ proto::connections::SOCKET_CREATION);
+ return;
+ }
+
+ NEARBY_LOGS(VERBOSE)
+ << "BwuManager successfully created new EndpointChannel for "
+ "incoming socket";
+
+ ClientIntroduction introduction;
+ if (!ReadClientIntroductionFrame(channel, introduction)) {
+ // This was never a fully EstablishedConnection, no need to provide a
+ // closure reason.
+ channel->Close();
+ NEARBY_LOGS(ERROR)
+ << "BwuManager failed to read "
+ "BWU_NEGOTIATION.CLIENT_INTRODUCTION OfflineFrame from "
+ "newly-created EndpointChannel "
+ << channel->GetName()
+ << ", so the EndpointChannel was discarded.";
+ return;
+ }
+
+ if (!WriteClientIntroductionAckFrame(channel)) {
+ // This was never a fully EstablishedConnection, no need to provide a
+ // closure reason.
+ channel->Close();
+ return;
+ }
+
+ NEARBY_LOGS(VERBOSE) << "BwuManager successfully received "
+ "BWU_NEGOTIATION.CLIENT_INTRODUCTION "
+ "OfflineFrame on EndpointChannel "
+ << channel->GetName();
+
+ const std::string& endpoint_id = introduction.endpoint_id();
+ ClientProxy* mapped_client;
+ const auto item = in_progress_upgrades_.find(endpoint_id);
+ if (item == in_progress_upgrades_.end()) return;
+ mapped_client = item->second;
+ CancelRetryUpgradeAlarm(endpoint_id);
+ if (mapped_client == nullptr) {
+ // This was never a fully EstablishedConnection, no need to provide a
+ // closure reason.
+ channel->Close();
+ return;
+ }
+
+ CHECK(client == mapped_client);
+
+ // The ConnectionAttempt has now succeeded, so record it as such.
+ std::unique_ptr<ConnectionAttemptMetadataParams>
+ connections_attempt_metadata_params;
+ if (channel != nullptr) {
+ connections_attempt_metadata_params =
+ client->GetAnalyticsRecorder()
+ .BuildConnectionAttemptMetadataParams(
+ channel->GetTechnology(), channel->GetBand(),
+ channel->GetFrequency(), channel->GetTryCount());
+ }
+ client->GetAnalyticsRecorder().OnIncomingConnectionAttempt(
+ proto::connections::UPGRADE, channel->GetMedium(),
+ proto::connections::RESULT_SUCCESS,
+ SystemClock::ElapsedRealtime() - connection_attempt_start_time,
+ client->GetConnectionToken(endpoint_id),
+ connections_attempt_metadata_params.get());
+
+ // Use the introductory client information sent over to run the upgrade
+ // protocol.
+ RunUpgradeProtocol(mapped_client, endpoint_id,
+ std::move(connection->channel));
+ });
+}
+
+void BwuManager::RunOnBwuManagerThread(const std::string& name,
+ Runnable runnable) {
+ serial_executor_.Execute(name, std::move(runnable));
+}
+
+void BwuManager::RunUpgradeProtocol(
+ ClientProxy* client, const std::string& endpoint_id,
+ std::unique_ptr<EndpointChannel> new_channel) {
+ NEARBY_LOGS(INFO) << "RunUpgradeProtocol new channel @" << new_channel.get()
+ << " name: " << new_channel->GetName()
+ << ", medium: " << new_channel->GetMedium();
+ // First, register this new EndpointChannel as *the* EndpointChannel to use
+ // for this endpoint here onwards. NOTE: We pause this new EndpointChannel
+ // until we've completely drained the old EndpointChannel to avoid out of
+ // order reads on the other side. This is a consequence of using the same
+ // UKEY2 context for both the previous and new EndpointChannels. UKEY2 uses
+ // sequence numbers for writes and reads, and simultaneously sending Payloads
+ // on the new channel and control messages on the old channel cause the other
+ // side to read messages out of sequence
+ new_channel->Pause();
+ auto old_channel = channel_manager_->GetChannelForEndpoint(endpoint_id);
+ if (!old_channel) {
+ NEARBY_LOGS(INFO)
+ << "BwuManager didn't find a previous EndpointChannel for "
+ << endpoint_id
+ << " when registering the new EndpointChannel, short-circuiting the "
+ "upgrade protocol.";
+ client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
+ endpoint_id, proto::connections::CHANNEL_ERROR,
+ proto::connections::PRIOR_ENDPOINT_CHANNEL);
+ return;
+ }
+ channel_manager_->ReplaceChannelForEndpoint(client, endpoint_id,
+ std::move(new_channel));
+
+ // Next, initiate a clean shutdown for the previous EndpointChannel used for
+ // this endpoint by telling the remote device that it will not receive any
+ // more writes over that EndpointChannel.
+ if (!old_channel->Write(parser::ForBwuLastWrite()).Ok()) {
+ NEARBY_LOGS(ERROR)
+ << "BwuManager failed to write "
+ "BWU_NEGOTIATION.LAST_WRITE_TO_PRIOR_CHANNEL OfflineFrame to "
+ "endpoint "
+ << endpoint_id << ", short-circuiting the upgrade protocol.";
+ client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
+ endpoint_id, proto::connections::RESULT_IO_ERROR,
+ proto::connections::LAST_WRITE_TO_PRIOR_CHANNEL);
+ return;
+ }
+ NEARBY_LOGS(VERBOSE) << "BwuManager successfully wrote "
+ "BWU_NEGOTIATION.LAST_WRITE_TO_PRIOR_CHANNEL "
+ "OfflineFrame while upgrading endpoint "
+ << endpoint_id;
+
+ // The remainder of this clean shutdown for the previous EndpointChannel will
+ // continue when we receive a corresponding
+ // BANDWIDTH_UPGRADE_NEGOTIATION.LAST_WRITE_TO_PRIOR_CHANNEL OfflineFrame from
+ // the remote device, so for now, just store that previous EndpointChannel.
+ previous_endpoint_channels_.emplace(endpoint_id, old_channel);
+
+ // If we already read LAST_WRITE on the old endpoint channel, then we can
+ // safely close it now.
+ auto item = successfully_upgraded_endpoints_.extract(endpoint_id);
+ if (!item.empty()) {
+ ProcessLastWriteToPriorChannelEvent(client, endpoint_id);
+ }
+}
+
+// Outgoing BWU session.
+void BwuManager::ProcessBwuPathAvailableEvent(
+ ClientProxy* client, const string& endpoint_id,
+ const UpgradePathInfo& upgrade_path_info) {
+ NEARBY_LOGS(INFO) << "ProcessBwuPathAvailableEvent for endpoint "
+ << endpoint_id << " medium "
+ << parser::UpgradePathInfoMediumToMedium(
+ upgrade_path_info.medium());
+ if (in_progress_upgrades_.contains(endpoint_id)) {
+ NEARBY_LOGS(ERROR)
+ << "BwuManager received a duplicate bandwidth upgrade for endpoint "
+ << endpoint_id
+ << ". We're out of sync with the remote device and cannot recover; "
+ "closing all channels.";
+
+ auto item = previous_endpoint_channels_.extract(endpoint_id);
+ if (!item.empty()) {
+ std::shared_ptr<EndpointChannel> previous_endpoint_channel =
+ item.mapped();
+ if (previous_endpoint_channel) {
+ previous_endpoint_channel->Close(DisconnectionReason::UNFINISHED);
+ }
+ }
+ std::shared_ptr<EndpointChannel> new_channel =
+ channel_manager_->GetChannelForEndpoint(endpoint_id);
+ if (new_channel) {
+ // The upgraded channel never finished upgrading, and therefore is still
+ // paused.
+ new_channel->Resume();
+ new_channel->Close(DisconnectionReason::UNFINISHED);
+ }
+
+ return;
+ }
+ Medium medium =
+ parser::UpgradePathInfoMediumToMedium(upgrade_path_info.medium());
+ if (medium_ == Medium::UNKNOWN_MEDIUM) {
+ SetCurrentBwuHandler(medium);
+ }
+ // Check for the correct medium so we don't process an incorrect OfflineFrame.
+ if (medium != medium_) {
+ NEARBY_LOGS(INFO) << "Medium not matching";
+ RunUpgradeFailedProtocol(client, endpoint_id, upgrade_path_info);
+ return;
+ }
+
+ client->GetAnalyticsRecorder().OnBandwidthUpgradeStarted(
+ endpoint_id, medium, medium_, proto::connections::OUTGOING,
+ client->GetConnectionToken(endpoint_id));
+
+ absl::Time connection_attempt_start_time = SystemClock::ElapsedRealtime();
+ auto channel = ProcessBwuPathAvailableEventInternal(client, endpoint_id,
+ upgrade_path_info);
+ proto::connections::ConnectionAttemptResult connection_attempt_result;
+ if (channel != nullptr) {
+ connection_attempt_result = proto::connections::RESULT_SUCCESS;
+ } else if (client->GetCancellationFlag(endpoint_id)->Cancelled()) {
+ connection_attempt_result = proto::connections::RESULT_CANCELLED;
+ client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
+ endpoint_id, proto::connections::RESULT_REMOTE_ERROR,
+ proto::connections::UPGRADE_CANCEL);
+ } else {
+ connection_attempt_result = proto::connections::RESULT_ERROR;
+ }
+
+ std::unique_ptr<ConnectionAttemptMetadataParams>
+ connections_attempt_metadata_params;
+ if (channel != nullptr) {
+ connections_attempt_metadata_params =
+ client->GetAnalyticsRecorder().BuildConnectionAttemptMetadataParams(
+ channel->GetTechnology(), channel->GetBand(),
+ channel->GetFrequency(), channel->GetTryCount());
+ }
+ client->GetAnalyticsRecorder().OnOutgoingConnectionAttempt(
+ endpoint_id, proto::connections::UPGRADE, medium_,
+ connection_attempt_result,
+ SystemClock::ElapsedRealtime() - connection_attempt_start_time,
+ client->GetConnectionToken(endpoint_id),
+ connections_attempt_metadata_params.get());
+
+ if (channel == nullptr) {
+ NEARBY_LOGS(INFO) << "Failed to get new channel.";
+ RunUpgradeFailedProtocol(client, endpoint_id, upgrade_path_info);
+ return;
+ }
+
+ in_progress_upgrades_.emplace(endpoint_id, client);
+ RunUpgradeProtocol(client, endpoint_id, std::move(channel));
+}
+
+std::unique_ptr<EndpointChannel>
+BwuManager::ProcessBwuPathAvailableEventInternal(
+ ClientProxy* client, const string& endpoint_id,
+ const UpgradePathInfo& upgrade_path_info) {
+ NEARBY_LOGS(INFO) << "ProcessBwuPathAvailableEventInternal for endpoint "
+ << endpoint_id << " medium "
+ << parser::UpgradePathInfoMediumToMedium(
+ upgrade_path_info.medium());
+ std::unique_ptr<EndpointChannel> channel =
+ handler_->CreateUpgradedEndpointChannel(client, client->GetServiceId(),
+ endpoint_id, upgrade_path_info);
+ if (!channel) {
+ NEARBY_LOGS(ERROR)
+ << "BwuManager failed to create an endpoint channel to endpoint"
+ << endpoint_id << ", aborting upgrade.";
+ client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
+ endpoint_id, proto::connections::RESULT_IO_ERROR,
+ proto::connections::SOCKET_CREATION);
+ return nullptr;
+ }
+
+ // Write the requisite BANDWIDTH_UPGRADE_NEGOTIATION.CLIENT_INTRODUCTION as
+ // the first OfflineFrame on this new EndpointChannel.
+ if (!channel->Write(parser::ForBwuIntroduction(client->GetLocalEndpointId()))
+ .Ok()) {
+ // This was never a fully EstablishedConnection, no need to provide a
+ // closure reason.
+ channel->Close();
+
+ NEARBY_LOGS(ERROR)
+ << "BwuManager failed to write BWU_NEGOTIATION.CLIENT_INTRODUCTION "
+ "OfflineFrame to newly-created EndpointChannel "
+ << channel->GetName() << ", aborting upgrade.";
+ client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
+ endpoint_id, proto::connections::RESULT_IO_ERROR,
+ proto::connections::CLIENT_INTRODUCTION);
+ return {};
+ }
+
+ if (upgrade_path_info.supports_client_introduction_ack()) {
+ if (!ReadClientIntroductionAckFrame(channel.get())) {
+ // This was never a fully EstablishedConnection, no need to provide a
+ // closure reason.
+ channel->Close();
+
+ NEARBY_LOGS(ERROR) << "BwuManager failed to read "
+ "BWU_NEGOTIATION.CLIENT_INTRODUCTION_ACK "
+ "OfflineFrame to newly-created EndpointChannel "
+ << channel->GetName() << ", aborting upgrade.";
+
+ return {};
+ }
+ }
+
+ NEARBY_LOGS(INFO) << "BwuManager successfully wrote "
+ "BWU_NEGOTIATION.CLIENT_INTRODUCTION OfflineFrame to "
+ "newly-created EndpointChannel "
+ << channel->GetName() << " while upgrading endpoint "
+ << endpoint_id;
+
+ // Set the AnalyticsRecorder so that the future closure of this
+ // EndpointChannel will be recorded.
+ return channel;
+}
+
+void BwuManager::RunUpgradeFailedProtocol(
+ ClientProxy* client, const std::string& endpoint_id,
+ const UpgradePathInfo& upgrade_path_info) {
+ NEARBY_LOGS(INFO) << "RunUpgradeFailedProtocol for endpoint " << endpoint_id
+ << " medium "
+ << parser::UpgradePathInfoMediumToMedium(
+ upgrade_path_info.medium());
+ // We attempted to connect to the new medium that the remote device has set up
+ // for us but we failed. We need to let the remote device know so that they
+ // can pick another medium for us to try.
+ std::shared_ptr<EndpointChannel> channel =
+ channel_manager_->GetChannelForEndpoint(endpoint_id);
+ if (!channel) {
+ NEARBY_LOGS(ERROR)
+ << "BwuManager didn't find a previous EndpointChannel for "
+ << endpoint_id
+ << " when sending an upgrade failure frame, short-circuiting the "
+ "upgrade protocol.";
+ client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
+ endpoint_id, proto::connections::CHANNEL_ERROR,
+ proto::connections::NETWORK_AVAILABLE);
+ return;
+ }
+
+ // Report UPGRADE_FAILURE to the remote device.
+ if (!channel->Write(parser::ForBwuFailure(upgrade_path_info)).Ok()) {
+ channel->Close(DisconnectionReason::IO_ERROR);
+
+ NEARBY_LOGS(ERROR)
+ << "BwuManager failed to write BWU_NEGOTIATION.UPGRADE_FAILURE "
+ "OfflineFrame to endpoint "
+ << endpoint_id << ", short-circuiting the upgrade protocol.";
+ client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
+ endpoint_id, proto::connections::RESULT_IO_ERROR,
+ proto::connections::NETWORK_AVAILABLE);
+ return;
+ }
+
+ // And lastly, clean up our currentBwuMedium since we failed to
+ // utilize it anyways.
+ if (medium_ != Medium::UNKNOWN_MEDIUM) {
+ Revert();
+ }
+ in_progress_upgrades_.erase(endpoint_id);
+ NEARBY_LOGS(INFO) << "BwuManager has informed endpoint " << endpoint_id
+ << " that the bandwidth upgrade failed.";
+}
+
+bool BwuManager::ReadClientIntroductionFrame(EndpointChannel* channel,
+ ClientIntroduction& introduction) {
+ NEARBY_LOGS(INFO) << "ReadClientIntroductionFrame with channel name: "
+ << channel->GetName()
+ << ", medium: " << channel->GetMedium();
+ CancelableAlarm timeout_alarm(
+ "BwuManager::ReadClientIntroductionFrame",
+ [channel]() {
+ NEARBY_LOGS(ERROR) << "In BwuManager, failed to read the "
+ "ClientIntroductionFrame after "
+ << absl::FormatDuration(
+ kReadClientIntroductionFrameTimeout)
+ << ". Timing out and closing EndpointChannel "
+ << channel->GetType();
+ channel->Close();
+ },
+ kReadClientIntroductionFrameTimeout, &alarm_executor_);
+ auto data = channel->Read();
+ timeout_alarm.Cancel();
+ if (!data.ok()) return false;
+ auto transfer(parser::FromBytes(data.result()));
+ if (!transfer.ok()) {
+ NEARBY_LOGS(ERROR) << "In ReadClientIntroductionFrame, attempted to read a "
+ "ClientIntroductionFrame from EndpointChannel "
+ << channel->GetType()
+ << " but was unable to obtain any OfflineFrame.";
+ return false;
+ }
+ OfflineFrame frame = transfer.result();
+ if (!frame.has_v1() || !frame.v1().has_bandwidth_upgrade_negotiation()) {
+ NEARBY_LOGS(ERROR)
+ << "In ReadClientIntroductionFrame, expected a "
+ "BANDWIDTH_UPGRADE_NEGOTIATION v1 OfflineFrame but got a "
+ << parser::GetFrameType(frame) << " frame instead.";
+ return false;
+ }
+ if (frame.v1().bandwidth_upgrade_negotiation().event_type() !=
+ BandwidthUpgradeNegotiationFrame::CLIENT_INTRODUCTION) {
+ NEARBY_LOGS(ERROR)
+ << "In ReadClientIntroductionFrame, expected a CLIENT_INTRODUCTION "
+ "v1 OfflineFrame but got a BANDWIDTH_UPGRADE_NEGOTIATION frame "
+ "with eventType "
+ << frame.v1().bandwidth_upgrade_negotiation().event_type()
+ << " instead.";
+ return false;
+ }
+ const auto& frame_intro =
+ frame.v1().bandwidth_upgrade_negotiation().client_introduction();
+ introduction = frame_intro;
+ return true;
+}
+
+bool BwuManager::ReadClientIntroductionAckFrame(EndpointChannel* channel) {
+ NEARBY_LOGS(INFO) << "ReadClientIntroductionAckFrame with channel name: "
+ << channel->GetName() << ", medium: "
+ << proto::connections::Medium_Name(channel->GetMedium());
+ CancelableAlarm timeout_alarm(
+ "BwuManager::ReadClientIntroductionAckFrame",
+ [channel]() {
+ NEARBY_LOGS(ERROR)
+ << "In BwuManager, failed to read the ClientIntroductionAckFrame "
+ "after "
+ << absl::FormatDuration(kReadClientIntroductionFrameTimeout)
+ << ". Timing out and closing EndpointChannel "
+ << channel->GetType();
+ channel->Close();
+ },
+ kReadClientIntroductionFrameTimeout, &alarm_executor_);
+ auto data = channel->Read();
+ timeout_alarm.Cancel();
+ if (!data.ok()) return false;
+ auto transfer(parser::FromBytes(data.result()));
+ if (!transfer.ok()) return false;
+ OfflineFrame frame = transfer.result();
+ if (!frame.has_v1() || !frame.v1().has_bandwidth_upgrade_negotiation())
+ return false;
+ if (frame.v1().bandwidth_upgrade_negotiation().event_type() !=
+ BandwidthUpgradeNegotiationFrame::CLIENT_INTRODUCTION_ACK)
+ return false;
+ return true;
+}
+
+bool BwuManager::WriteClientIntroductionAckFrame(EndpointChannel* channel) {
+ NEARBY_LOGS(INFO) << "WriteClientIntroductionAckFrame channel name: "
+ << channel->GetName()
+ << ", medium: " << channel->GetMedium();
+ return channel->Write(parser::ForBwuIntroductionAck()).Ok();
+}
+
+void BwuManager::ProcessLastWriteToPriorChannelEvent(
+ ClientProxy* client, const std::string& endpoint_id) {
+ NEARBY_LOGS(INFO) << "ProcessLastWriteToPriorChannelEvent for endpoint "
+ << endpoint_id;
+ // By this point in the upgrade protocol, there is the guarantee that both
+ // involved endpoints have registered a new EndpointChannel with the
+ // EndpointChannelManager as the official channel for communication; given
+ // the way communication is structured in the EndpointManager, this means
+ // that all new writes are happening over that new EndpointChannel, but
+ // reads are still happening over this prior EndpointChannel (to avoid data
+ // loss). But now that we've received this definitive final write over that
+ // prior EndpointChannel, we can let the remote device that they can safely
+ // close their end of this now-dormant EndpointChannel.
+ EndpointChannel* previous_endpoint_channel =
+ previous_endpoint_channels_[endpoint_id].get();
+ if (!previous_endpoint_channel) {
+ NEARBY_LOGS(ERROR)
+ << "BwuManager received a BWU_NEGOTIATION.LAST_WRITE_TO_PRIOR_CHANNEL "
+ "OfflineFrame for unknown endpoint "
+ << endpoint_id << ", can't complete the upgrade protocol.";
+ successfully_upgraded_endpoints_.emplace(endpoint_id);
+ return;
+ }
+
+ if (!previous_endpoint_channel->Write(parser::ForBwuSafeToClose()).Ok()) {
+ previous_endpoint_channel->Close(DisconnectionReason::IO_ERROR);
+ // Remove this prior EndpointChannel from previous_endpoint_channels to
+ // avoid leaks.
+ previous_endpoint_channels_.erase(endpoint_id);
+
+ NEARBY_LOGS(ERROR) << "BwuManager failed to write "
+ "BWU_NEGOTIATION.SAFE_TO_CLOSE_PRIOR_CHANNEL "
+ "OfflineFrame to endpoint "
+ << endpoint_id
+ << ", short-circuiting the upgrade protocol.";
+ client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
+ endpoint_id, proto::connections::RESULT_IO_ERROR,
+ proto::connections::SAFE_TO_CLOSE_PRIOR_CHANNEL);
+ return;
+ }
+ NEARBY_LOGS(VERBOSE) << "BwuManager successfully wrote "
+ "BWU_NEGOTIATION.SAFE_TO_CLOSE_PRIOR_CHANNEL "
+ "OfflineFrame while trying to upgrade endpoint "
+ << endpoint_id;
+
+ // The upgrade protocol's clean shutdown of the prior EndpointChannel will
+ // conclude when we receive a corresponding
+ // BANDWIDTH_UPGRADE_NEGOTIATION.SAFE_TO_CLOSE_PRIOR_CHANNEL OfflineFrame
+ // from the remote device.
+}
+
+void BwuManager::ProcessSafeToClosePriorChannelEvent(
+ ClientProxy* client, const std::string& endpoint_id) {
+ NEARBY_LOGS(INFO) << "ProcessSafeToClosePriorChannelEvent for endpoint "
+ << endpoint_id;
+ // By this point in the upgrade protocol, there's no more writes happening
+ // over the prior EndpointChannel, and the remote device has given us the
+ // go-ahead to close this EndpointChannel [1], so we can safely close it
+ // (and depend on the EndpointManager querying the EndpointChannelManager to
+ // start reading from the new EndpointChannel).
+ //
+ // [1] Which also implies that they've received our
+ // BANDWIDTH_UPGRADE_NEGOTIATION.LAST_WRITE_TO_PRIOR_CHANNEL OfflineFrame),
+ // so there can be no data loss, regardless of whether the EndpointChannel
+ // allows reads of queued, unread data after the EndpointChannel has been
+ // closed from the other end (as is the case with conventional TCP sockets)
+ // or not (as is the case with Android's Bluetooth sockets, where closing
+ // instantly throws an IOException on the remote device).
+ auto item = previous_endpoint_channels_.extract(endpoint_id);
+ auto& previous_endpoint_channel = item.mapped();
+ if (previous_endpoint_channel == nullptr) {
+ NEARBY_LOGS(ERROR)
+ << "BwuManager received a BWU_NEGOTIATION.SAFE_TO_CLOSE_PRIOR_CHANNEL "
+ "OfflineFrame for unknown endpoint "
+ << endpoint_id << ", can't complete the upgrade protocol.";
+ return;
+ }
+ NEARBY_LOGS(INFO)
+ << "BwuManager successfully received a "
+ << "BWU_NEGOTIATION.SAFE_TO_CLOSE_PRIOR_CHANNEL OfflineFrame while "
+ << "trying to upgrade endpoint " << endpoint_id;
+
+ // Each encrypted message includes the key to decrypt the next message. The
+ // disconnect message is optional and may not be received under normal
+ // circumstances so it is necessary to send it unencrypted. This way the
+ // serial crypto context does not increment here.
+ previous_endpoint_channel->DisableEncryption();
+ previous_endpoint_channel->Write(parser::ForDisconnection());
+
+ // Attempt to read the disconnect message from the previous channel. We don't
+ // care whether we successfully read it or whether we get an exception here.
+ // The idea is just to make sure the other side has had a chance to receive
+ // the full SAFE_TO_CLOSE_PRIOR_CHANNEL message before we actually close the
+ // channel. See b/172380349 for more context.
+ previous_endpoint_channel->Read();
+ previous_endpoint_channel->Close(DisconnectionReason::UPGRADED);
+
+ NEARBY_LOGS(VERBOSE)
+ << "BwuManager cleanly shut down prior "
+ << previous_endpoint_channel->GetType()
+ << " EndpointChannel to conclude upgrade protocol for endpoint "
+ << endpoint_id;
+
+ // Now the upgrade protocol has completed, record analytics for this new
+ // upgraded bandwidth connection...
+ client->GetAnalyticsRecorder().OnConnectionEstablished(
+ endpoint_id, medium_, client->GetConnectionToken(endpoint_id));
+ // ...and the success of the upgrade itself.
+ client->GetAnalyticsRecorder().OnBandwidthUpgradeSuccess(endpoint_id);
+
+ // Now that the old channel has been drained, we can unpause the new channel
+ std::shared_ptr<EndpointChannel> channel =
+ channel_manager_->GetChannelForEndpoint(endpoint_id);
+
+ if (!channel) {
+ NEARBY_LOGS(ERROR) << "BwuManager attempted to resume the current "
+ "EndpointChannel with endpoint "
+ << endpoint_id << ", but none was found.";
+ return;
+ }
+
+ channel->Resume();
+
+ // Report the success to the client
+ client->OnBandwidthChanged(endpoint_id, channel->GetMedium());
+ in_progress_upgrades_.erase(endpoint_id);
+}
+
+void BwuManager::ProcessUpgradeFailureEvent(
+ ClientProxy* client, const std::string& endpoint_id,
+ const UpgradePathInfo& upgrade_info) {
+ NEARBY_LOGS(INFO) << "ProcessUpgradeFailureEvent for endpoint " << endpoint_id
+ << " from medium: "
+ << parser::UpgradePathInfoMediumToMedium(
+ upgrade_info.medium());
+ // The remote device failed to upgrade to the new medium we set up for them.
+ // That's alright! We'll just try the next available medium (if there is
+ // one).
+ in_progress_upgrades_.erase(endpoint_id);
+
+ // The first thing we have to do is to replace our
+ // currentBwuMedium with the next best upgrade medium we share
+ // with the remote device. The catch is that we can only do this if we only
+ // have one connected endpoint. Otherwise, we'll end up disrupting our other
+ // connected peers.
+ if (channel_manager_->GetConnectedEndpointsCount() > 1) {
+ // We can't change the currentBwuMedium, so there are no more
+ // upgrade attempts for this endpoint. Sorry.
+ NEARBY_LOGS(ERROR)
+ << "BwuManager failed to attempt a new bandwidth upgrade for endpoint "
+ << endpoint_id
+ << " because we have other connected endpoints and can't try a new "
+ "upgrade medium.";
+ client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
+ endpoint_id, proto::connections::CHANNEL_ERROR,
+ proto::connections::NETWORK_AVAILABLE);
+ return;
+ }
+
+ // Revert the existing upgrade medium for now.
+ if (medium_ != Medium::UNKNOWN_MEDIUM) {
+ Revert();
+ }
+
+ // Loop through the ordered list of upgrade mediums. One by one, remove the
+ // top element until we get to the medium we last attempted to upgrade to.
+ // The remainder of the list will contain the mediums we haven't attempted
+ // yet.
+ Medium last = parser::UpgradePathInfoMediumToMedium(upgrade_info.medium());
+ std::vector<Medium> all_possible_mediums =
+ client->GetUpgradeMediums(endpoint_id).GetMediums(true);
+ std::vector<Medium> untried_mediums(all_possible_mediums);
+ for (Medium medium : all_possible_mediums) {
+ untried_mediums.erase(untried_mediums.begin());
+ if (medium == last) {
+ break;
+ }
+ }
+
+ RetryUpgradeMediums(client, endpoint_id, untried_mediums);
+}
+
+void BwuManager::RetryUpgradeMediums(ClientProxy* client,
+ const std::string& endpoint_id,
+ std::vector<Medium> upgrade_mediums) {
+ Medium next_medium = ChooseBestUpgradeMedium(upgrade_mediums);
+ NEARBY_LOGS(INFO) << "RetryUpgradeMediums for endpoint " << endpoint_id
+ << " after ChooseBestUpgradeMedium: " << next_medium;
+
+ // If current medium is not WiFi and we have not succeeded with upgrading
+ // yet, retry upgrade.
+ Medium current_medium = GetEndpointMedium(endpoint_id);
+ if (current_medium != Medium::WIFI_LAN &&
+ (next_medium == current_medium || next_medium == Medium::UNKNOWN_MEDIUM ||
+ upgrade_mediums.empty())) {
+ RetryUpgradesAfterDelay(client, endpoint_id);
+ return;
+ }
+
+ // Attempt to set the new upgrade medium.
+ if (!SetCurrentBwuHandler(next_medium)) {
+ NEARBY_LOGS(INFO)
+ << "BwuManager failed to attempt a new bandwidth upgrade for endpoint "
+ << endpoint_id
+ << " because we couldn't set a new bandwidth upgrade medium.";
+ return;
+ }
+
+ // Now that we've successfully picked a new upgrade medium to try,
+ // re-initiate the bandwidth upgrade.
+ NEARBY_LOGS(INFO) << "BwuManager is attempting to upgrade endpoint "
+ << endpoint_id
+ << " again with a new bandwidth upgrade medium.";
+ InitiateBwuForEndpoint(client, endpoint_id, next_medium);
+}
+
+std::vector<Medium> BwuManager::StripOutUnavailableMediums(
+ const std::vector<Medium>& mediums) {
+ std::vector<Medium> available_mediums;
+ for (Medium m : mediums) {
+ bool available = false;
+ switch (m) {
+ case Medium::WIFI_LAN:
+ available = mediums_->GetWifiLan().IsAvailable();
+ break;
+ case Medium::WEB_RTC:
+ available = mediums_->GetWebRtc().IsAvailable();
+ break;
+ case Medium::BLUETOOTH:
+ available = mediums_->GetBluetoothClassic().IsAvailable();
+ break;
+ default:
+ break;
+ }
+ if (available) {
+ available_mediums.push_back(m);
+ }
+ }
+ return available_mediums;
+}
+
+// Returns the optimal medium supported by both devices.
+// Each medium in the passed in list is checked for its availability with the
+// medium_manager_ to ensure that the chosen upgrade medium is supported and
+// available locally before continuing the upgrade. Once we pick a medium, all
+// future connections will use it too. eg. If we chose Wifi LAN, we'll attempt
+// to upgrade the 2nd, 3rd, etc remote endpoints with Wifi LAN even if they're
+// on a different network (or had a better medium). This is a quick and easy
+// way to prevent mediums, like Wifi Hotspot, from interfering with active
+// connections (although it's suboptimal for bandwidth throughput). When all
+// endpoints disconnect, we reset the bandwidth upgrade medium.
+Medium BwuManager::ChooseBestUpgradeMedium(const std::vector<Medium>& mediums) {
+ auto available_mediums = StripOutUnavailableMediums(mediums);
+ if (medium_ == Medium::UNKNOWN_MEDIUM) {
+ if (!available_mediums.empty()) {
+ // Case 1: This is our first time upgrading, and we have at least one
+ // supported medium to choose from. Return the first medium in the list,
+ // since they are ordered by preference.
+ return available_mediums[0];
+ }
+ // Case 2: This is our first time upgrading, but there are no available
+ // upgrade mediums. Fall through to returning UNKNOWN_MEDIUM at the
+ // bottom.
+ NEARBY_LOGS(INFO)
+ << "Current upgrade medium is unset, but there are no common supported "
+ "upgrade mediums.";
+ } else {
+ // Case 3: We have already upgraded, and there is a list of supported
+ // mediums to check against. Return the current upgrade medium if it's in
+ // the supported list.
+ if (std::find(available_mediums.begin(), available_mediums.end(),
+ medium_) != available_mediums.end()) {
+ return medium_;
+ }
+ // Case 4: We have already upgraded, but the current medium is not
+ // supported by the remote endpoint (it's not in the list, or the list is
+ // empty). Fall through and return Medium.UNKNOWN_MEDIUM because we cannot
+ // continue with the current upgrade medium, and we are not allowed to
+ // switch.
+ std::string mediums_string;
+ for (const auto& medium : available_mediums) {
+ absl::StrAppend(&mediums_string, proto::connections::Medium_Name(medium),
+ "; ");
+ }
+ NEARBY_LOGS(INFO)
+ << "Current upgrade medium " << proto::connections::Medium_Name(medium_)
+ << " is not supported by the remote endpoint (supported mediums: "
+ << mediums_string << ")";
+ }
+
+ return Medium::UNKNOWN_MEDIUM;
+}
+
+void BwuManager::RetryUpgradesAfterDelay(ClientProxy* client,
+ const std::string& endpoint_id) {
+ absl::Duration delay = CalculateNextRetryDelay(endpoint_id);
+ CancelRetryUpgradeAlarm(endpoint_id);
+ CancelableAlarm alarm(
+ "BWU alarm",
+ [this, client, endpoint_id]() {
+ RunOnBwuManagerThread(
+ "bwu-retry-upgrade", [this, client, endpoint_id]() {
+ if (!client->IsConnectedToEndpoint(endpoint_id)) {
+ return;
+ }
+ RetryUpgradeMediums(
+ client, endpoint_id,
+ client->GetUpgradeMediums(endpoint_id).GetMediums(true));
+ });
+ },
+ delay, &alarm_executor_);
+
+ retry_upgrade_alarms_.emplace(endpoint_id,
+ std::make_pair(std::move(alarm), delay));
+ retry_delays_[endpoint_id] = delay;
+ NEARBY_LOGS(INFO) << "Retry bandwidth upgrade after "
+ << absl::FormatDuration(delay);
+}
+
+void BwuManager::AttemptToRecordBandwidthUpgradeErrorForUnknownEndpoint(
+ proto::connections::BandwidthUpgradeResult result,
+ proto::connections::BandwidthUpgradeErrorStage error_stage) {
+ if (in_progress_upgrades_.size() == 1) {
+ auto it = in_progress_upgrades_.begin();
+ std::string endpoint_id = it->first;
+ ClientProxy* client = it->second;
+ // Note: Even though we know this is an error, we cannot clear state yet.
+ // We've sent the remote device the credentials they need and it's up to
+ // them if they want to repeatedly attempt to connect or if they want to
+ // give up and have us try a different medium. This isn't a decision we can
+ // make for them.
+ client->GetAnalyticsRecorder().OnBandwidthUpgradeError(endpoint_id, result,
+ error_stage);
+ NEARBY_LOGS(INFO) << "BwuManager got error "
+ << proto::connections::BandwidthUpgradeResult_Name(result)
+ << " at stage "
+ << proto::connections::BandwidthUpgradeErrorStage_Name(
+ error_stage)
+ << " when upgrading endpoint " << endpoint_id;
+ }
+ // Otherwise, we have no way of knowing which endpoint was trying to connect
+ // to us :(
+ NEARBY_LOGS(INFO) << "BwuManager got error "
+ << proto::connections::BandwidthUpgradeResult_Name(result)
+ << " at stage "
+ << proto::connections::BandwidthUpgradeErrorStage_Name(
+ error_stage)
+ << ", but we don't know which endpoint was trying to "
+ "connect to us, so skipping analytics for his error.";
+}
+
+absl::Duration BwuManager::CalculateNextRetryDelay(
+ const std::string& endpoint_id) {
+ auto item = retry_delays_.find(endpoint_id);
+ auto initial_delay = config_.bandwidth_upgrade_retry_delay;
+ if (item == retry_delays_.end()) return initial_delay;
+ /*
+ * Without use_exp_backoff_in_bwu_retry, bwu retry intervals for the same
+ * endpoint_id in seconds will be like: 5, 10, 10, 10...
+ * With use_exp_backoff_in_bwu_retry enabled, bwu retry intervals in seconds
+ * would be like: 3, 6, 12, 24, ... 300, 300, ...
+ */
+ auto delay =
+ FeatureFlags::GetInstance().GetFlags().use_exp_backoff_in_bwu_retry
+ ? item->second * 2
+ : item->second + initial_delay;
+ return std::min(delay, config_.bandwidth_upgrade_retry_max_delay);
+}
+
+void BwuManager::CancelRetryUpgradeAlarm(const std::string& endpoint_id) {
+ NEARBY_LOGS(INFO) << "CancelRetryUpgradeAlarm for endpoint " << endpoint_id;
+ auto item = retry_upgrade_alarms_.extract(endpoint_id);
+ if (item.empty()) return;
+ auto& pair = item.mapped();
+ pair.first.Cancel();
+}
+
+void BwuManager::CancelAllRetryUpgradeAlarms() {
+ NEARBY_LOGS(INFO) << "CancelAllRetryUpgradeAlarms invoked";
+ for (auto& item : retry_upgrade_alarms_) {
+ const std::string& endpoint_id = item.first;
+ CancelableAlarm& cancellable_alarm = item.second.first;
+ NEARBY_LOGS(INFO) << "CancelRetryUpgradeAlarm for endpoint " << endpoint_id;
+ cancellable_alarm.Cancel();
+ }
+ retry_upgrade_alarms_.clear();
+ retry_delays_.clear();
+}
+
+Medium BwuManager::GetEndpointMedium(const std::string& endpoint_id) {
+ auto channel = channel_manager_->GetChannelForEndpoint(endpoint_id);
+ return channel == nullptr ? Medium::UNKNOWN_MEDIUM : channel->GetMedium();
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/bwu_manager.h b/chromium/third_party/nearby/src/connections/implementation/bwu_manager.h
new file mode 100644
index 00000000000..e3c6df74289
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/bwu_manager.h
@@ -0,0 +1,202 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_BWU_MANAGER_H_
+#define CORE_INTERNAL_BWU_MANAGER_H_
+
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "absl/container/flat_hash_map.h"
+#include "absl/container/flat_hash_set.h"
+#include "absl/time/time.h"
+#include "connections/implementation/bwu_handler.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/endpoint_manager.h"
+#include "connections/implementation/mediums/mediums.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/scheduled_executor.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Base class for managing the upgrade of endpoints to a different medium for
+// communication (from whatever they were previously using).
+//
+// The sequencing of the upgrade protocol is as follows:
+// - Initiator sets up an upgrade path, sends
+// BANDWIDTH_UPGRADE_NEGOTIATION.UPGRADE_PATH_AVAILABLE to Responder over
+// the prior EndpointChannel.
+// - Responder joins the upgrade path, sends (possibly without encryption)
+// BANDWIDTH_UPGRADE_NEGOTIATION.CLIENT_INTRODUCTION over the new
+// EndpointChannel, and sends
+// BANDWIDTH_UPGRADE_NEGOTIATION.LAST_WRITE_TO_PRIOR_CHANNEL over the
+// prior EndpointChannel.
+// - Initiator receives BANDWIDTH_UPGRADE_NEGOTIATION.CLIENT_INTRODUCTION
+// over the newly-established EndpointChannel, and sends
+// BANDWIDTH_UPGRADE_NEGOTIATION.LAST_WRITE_TO_PRIOR_CHANNEL over the
+// prior EndpointChannel.
+// - Both wait to receive
+// BANDWIDTH_UPGRADE_NEGOTIATION.LAST_WRITE_TO_PRIOR_CHANNEL from the
+// other, and upon doing so, send
+// BANDWIDTH_UPGRADE_NEGOTIATION.SAFE_TO_CLOSE_PRIOR_CHANNEL to each other
+// - Both then wait to receive
+// BANDWIDTH_UPGRADE_NEGOTIATION.SAFE_TO_CLOSE_PRIOR_CHANNEL from the
+// other, and upon doing so, close the prior EndpointChannel.
+class BwuManager : public EndpointManager::FrameProcessor {
+ public:
+ using UpgradePathInfo = BwuHandler::UpgradePathInfo;
+
+ struct Config {
+ BooleanMediumSelector allow_upgrade_to;
+ absl::Duration bandwidth_upgrade_retry_delay;
+ absl::Duration bandwidth_upgrade_retry_max_delay;
+ };
+
+ BwuManager(Mediums& mediums, EndpointManager& endpoint_manager,
+ EndpointChannelManager& channel_manager,
+ absl::flat_hash_map<Medium, std::unique_ptr<BwuHandler>> handlers,
+ Config config);
+
+ ~BwuManager() override;
+
+ // This is the point on the outbound BWU protocol where the handler_ is set.
+ // Function initiates the bandwidth upgrade and sends an
+ // UPGRADE_PATH_AVAILABLE OfflineFrame.
+ void InitiateBwuForEndpoint(ClientProxy* client_proxy,
+ const std::string& endpoint_id,
+ Medium new_medium = Medium::UNKNOWN_MEDIUM);
+
+ // == EndpointManager::FrameProcessor interface ==.
+ // This is the point on the inbound BWU protocol where the handler_ is set.
+ // This is also an entry point for handling messages for both outbound and
+ // inbound BWU protocol.
+ // @EndpointManagerReaderThread
+ void OnIncomingFrame(OfflineFrame& frame, const std::string& endpoint_id,
+ ClientProxy* client, Medium medium) override;
+
+ // Cleans up in-progress upgrades after endpoint disconnection.
+ // @EndpointManagerReaderThread
+ void OnEndpointDisconnect(ClientProxy* client_proxy,
+ const std::string& endpoint_id,
+ CountDownLatch barrier) override;
+ void Shutdown();
+
+ private:
+ static constexpr absl::Duration kReadClientIntroductionFrameTimeout =
+ absl::Seconds(5);
+ BwuHandler* SetCurrentBwuHandler(Medium medium);
+ void InitBwuHandlers();
+ void RunOnBwuManagerThread(const std::string& name,
+ std::function<void()> runnable);
+ std::vector<Medium> StripOutUnavailableMediums(
+ const std::vector<Medium>& mediums);
+ Medium ChooseBestUpgradeMedium(const std::vector<Medium>& mediums);
+
+ // BaseBwuHandler
+ using ClientIntroduction = BwuNegotiationFrame::ClientIntroduction;
+
+ // Processes the BwuNegotiationFrames that come over the
+ // EndpointChannel on both initiator and responder side of the upgrade.
+ void OnBwuNegotiationFrame(ClientProxy* client,
+ const BwuNegotiationFrame frame,
+ const string& endpoint_id);
+
+ // Called to revert any state changed by the Initiator or Responder in the
+ // course of setting up the upgraded medium for an endpoint.
+ void Revert();
+
+ // Common functionality to take an incoming connection and go through the
+ // upgrade process. This is a callback, invoked by concrete handlers, once
+ // connection is available.
+ void OnIncomingConnection(
+ ClientProxy* client,
+ std::unique_ptr<BwuHandler::IncomingSocketConnection> mutable_connection);
+
+ void RunUpgradeProtocol(ClientProxy* client, const std::string& endpoint_id,
+ std::unique_ptr<EndpointChannel> new_channel);
+ void RunUpgradeFailedProtocol(ClientProxy* client,
+ const std::string& endpoint_id,
+ const UpgradePathInfo& upgrade_path_info);
+ void ProcessBwuPathAvailableEvent(ClientProxy* client,
+ const std::string& endpoint_id,
+ const UpgradePathInfo& upgrade_path_info);
+ std::unique_ptr<EndpointChannel> ProcessBwuPathAvailableEventInternal(
+ ClientProxy* client, const std::string& endpoint_id,
+ const UpgradePathInfo& upgrade_path_info);
+ void ProcessLastWriteToPriorChannelEvent(ClientProxy* client,
+ const std::string& endpoint_id);
+ void ProcessSafeToClosePriorChannelEvent(ClientProxy* client,
+ const std::string& endpoint_id);
+ bool ReadClientIntroductionFrame(EndpointChannel* endpoint_channel,
+ ClientIntroduction& introduction);
+ bool ReadClientIntroductionAckFrame(EndpointChannel* endpoint_channel);
+ bool WriteClientIntroductionAckFrame(EndpointChannel* endpoint_channel);
+ void ProcessEndpointDisconnection(ClientProxy* client,
+ const std::string& endpoint_id,
+ CountDownLatch* barrier);
+ void ProcessUpgradeFailureEvent(ClientProxy* client,
+ const std::string& endpoint_id,
+ const UpgradePathInfo& upgrade_info);
+ void CancelRetryUpgradeAlarm(const std::string& endpoint_id);
+ void CancelAllRetryUpgradeAlarms();
+ void RetryUpgradeMediums(ClientProxy* client, const std::string& endpoint_id,
+ std::vector<Medium> upgrade_mediums);
+ Medium GetEndpointMedium(const std::string& endpoint_id);
+ absl::Duration CalculateNextRetryDelay(const std::string& endpoint_id);
+ void RetryUpgradesAfterDelay(ClientProxy* client,
+ const std::string& endpoint_id);
+ void AttemptToRecordBandwidthUpgradeErrorForUnknownEndpoint(
+ proto::connections::BandwidthUpgradeResult result,
+ proto::connections::BandwidthUpgradeErrorStage error_stage);
+
+ Config config_;
+
+ Medium medium_ = Medium::UNKNOWN_MEDIUM;
+ BwuHandler* handler_ = nullptr;
+ Mediums* mediums_;
+ absl::flat_hash_map<Medium, std::unique_ptr<BwuHandler>> handlers_;
+
+ EndpointManager* endpoint_manager_;
+ EndpointChannelManager* channel_manager_;
+ ScheduledExecutor alarm_executor_;
+ SingleThreadExecutor serial_executor_;
+ // Stores each upgraded endpoint's previous EndpointChannel (that was
+ // displaced in favor of a new EndpointChannel) temporarily, until it can
+ // safely be shut down for good in processLastWriteToPriorChannelEvent().
+ absl::flat_hash_map<std::string, std::shared_ptr<EndpointChannel>>
+ previous_endpoint_channels_;
+ absl::flat_hash_set<std::string> successfully_upgraded_endpoints_;
+ // Maps endpointId -> ClientProxy for which
+ // initiateBwuForEndpoint() has been called but which have not
+ // yet completed the upgrade via onIncomingConnection().
+ absl::flat_hash_map<std::string, ClientProxy*> in_progress_upgrades_;
+ // Maps endpointId -> timestamp of when the SAFE_TO_CLOSE message was written.
+ absl::flat_hash_map<std::string, absl::Time> safe_to_close_write_timestamps_;
+ absl::flat_hash_map<std::string, std::pair<CancelableAlarm, absl::Duration>>
+ retry_upgrade_alarms_;
+ // Maps endpointId -> duration of delay before bwu retry.
+ // When bwu failed, retry_upgrade_alarms_ will clear the entry before the
+ // retry happen, then we can not find the last delay used in the alarm. Thus
+ // using a different map to keep track of the delays per endpoint.
+ absl::flat_hash_map<std::string, absl::Duration> retry_delays_;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_BWU_MANAGER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/bwu_manager_test.cc b/chromium/third_party/nearby/src/connections/implementation/bwu_manager_test.cc
new file mode 100644
index 00000000000..acebaa24e34
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/bwu_manager_test.cc
@@ -0,0 +1,111 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/bwu_manager.h"
+
+#include <string>
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "absl/time/time.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/endpoint_channel_manager.h"
+#include "connections/implementation/endpoint_manager.h"
+#include "connections/implementation/mediums/mediums.h"
+#include "connections/implementation/mediums/utils.h"
+#include "connections/implementation/offline_frames.h"
+#include "internal/platform/system_clock.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+
+TEST(BwuManagerTest, CanCreateInstance) {
+ Mediums mediums;
+ EndpointChannelManager ecm;
+ EndpointManager em{&ecm};
+ BwuManager bwu_manager{mediums, em, ecm, {}, {}};
+
+ SystemClock::Sleep(absl::Seconds(3));
+
+ bwu_manager.Shutdown();
+}
+
+TEST(BwuManagerTest, CanInitiateBwu) {
+ ClientProxy client;
+ std::string endpoint_id("EP_A");
+ Mediums mediums;
+ EndpointChannelManager ecm;
+ EndpointManager em{&ecm};
+ BwuManager bwu_manager{mediums, em, ecm, {}, {}};
+
+ // Method returns void, so we just verify we did not SEGFAULT while calling.
+ bwu_manager.InitiateBwuForEndpoint(&client, endpoint_id);
+ SystemClock::Sleep(absl::Seconds(3));
+
+ bwu_manager.Shutdown();
+}
+
+TEST(BwuManagerTest, CanProcessBandwidthUpgradeFrames) {
+ ClientProxy client;
+ std::string endpoint_id("EP_A");
+ LocationHint location_hint = Utils::BuildLocationHint("US");
+ Mediums mediums;
+ EndpointChannelManager ecm;
+ EndpointManager em{&ecm};
+ BwuManager bwu_manager{mediums, em, ecm, {}, {}};
+
+ ExceptionOr<OfflineFrame> path_available_frame = parser::FromBytes(
+ parser::ForBwuWebrtcPathAvailable("my_id", location_hint));
+ bwu_manager.OnIncomingFrame(path_available_frame.result(), endpoint_id,
+ &client, Medium::WEB_RTC);
+
+ ExceptionOr<OfflineFrame> last_write_frame =
+ parser::FromBytes(parser::ForBwuLastWrite());
+ bwu_manager.OnIncomingFrame(last_write_frame.result(), endpoint_id, &client,
+ Medium::WEB_RTC);
+
+ ExceptionOr<OfflineFrame> safe_to_close_frame =
+ parser::FromBytes(parser::ForBwuSafeToClose());
+ bwu_manager.OnIncomingFrame(safe_to_close_frame.result(), endpoint_id,
+ &client, Medium::WEB_RTC);
+
+ bwu_manager.Shutdown();
+}
+
+TEST(BwuManagerTest, InitiateBwu_UpgradeFails_NoCrash) {
+ ClientProxy client;
+ std::string endpoint_id("EP_A");
+ Mediums mediums;
+ EndpointChannelManager ecm;
+ EndpointManager em{&ecm};
+ BwuManager bwu_manager{mediums, em, ecm, {}, {}};
+ parser::UpgradePathInfo upgrade_path_info;
+ upgrade_path_info.set_medium(parser::UpgradePathInfo::WEB_RTC);
+
+ bwu_manager.InitiateBwuForEndpoint(&client, endpoint_id);
+ ExceptionOr<OfflineFrame> bwu_failed_frame =
+ parser::FromBytes(parser::ForBwuFailure(upgrade_path_info));
+ bwu_manager.OnIncomingFrame(bwu_failed_frame.result(), endpoint_id, &client,
+ Medium::WEB_RTC);
+
+ bwu_manager.Shutdown();
+}
+
+} // namespace
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/client_proxy.cc b/chromium/third_party/nearby/src/connections/implementation/client_proxy.cc
new file mode 100644
index 00000000000..702504ca396
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/client_proxy.cc
@@ -0,0 +1,773 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/client_proxy.h"
+
+#include <cstdlib>
+#include <functional>
+#include <limits>
+#include <string>
+#include <utility>
+
+#include "absl/container/flat_hash_map.h"
+#include "absl/container/flat_hash_set.h"
+#include "absl/strings/escaping.h"
+#include "absl/strings/str_cat.h"
+#include "internal/platform/error_code_recorder.h"
+#include "internal/platform/feature_flags.h"
+#include "internal/platform/prng.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/mutex_lock.h"
+#include "proto/connections_enums.pb.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// The definition is necessary before C++17.
+constexpr absl::Duration
+ ClientProxy::kHighPowerAdvertisementEndpointIdCacheTimeout;
+
+constexpr char kEndpointIdChars[] = {
+ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
+ 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
+ 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
+
+ClientProxy::ClientProxy(analytics::EventLogger* event_logger)
+ : client_id_(Prng().NextInt64()) {
+ NEARBY_LOGS(INFO) << "ClientProxy ctor event_logger=" << event_logger;
+ analytics_recorder_ =
+ std::make_unique<analytics::AnalyticsRecorder>(event_logger);
+ error_code_recorder_ = std::make_unique<ErrorCodeRecorder>(
+ [this](const ErrorCodeParams& params) {
+ analytics_recorder_->OnErrorCode(params);
+ });
+}
+
+ClientProxy::~ClientProxy() { Reset(); }
+
+std::int64_t ClientProxy::GetClientId() const { return client_id_; }
+
+std::string ClientProxy::GetLocalEndpointId() {
+ MutexLock lock(&mutex_);
+ if (local_endpoint_id_.empty()) {
+ local_endpoint_id_ = GenerateLocalEndpointId();
+ NEARBY_LOGS(INFO) << "ClientProxy [Local Endpoint Generated]: client="
+ << GetClientId()
+ << "; endpoint_id=" << local_endpoint_id_;
+ }
+ return local_endpoint_id_;
+}
+
+std::string ClientProxy::GetConnectionToken(const std::string& endpoint_id) {
+ Connection* item = LookupConnection(endpoint_id);
+ if (item != nullptr) {
+ return item->connection_token;
+ }
+ return {};
+}
+
+std::string ClientProxy::GenerateLocalEndpointId() {
+ if (high_vis_mode_) {
+ if (!local_high_vis_mode_cache_endpoint_id_.empty()) {
+ NEARBY_LOGS(INFO)
+ << "ClientProxy [Local Endpoint Re-using cached endpoint id]: client="
+ << GetClientId() << "; local_high_vis_mode_cache_endpoint_id_="
+ << local_high_vis_mode_cache_endpoint_id_;
+ return local_high_vis_mode_cache_endpoint_id_;
+ }
+ }
+ std::string id;
+ for (int i = 0; i < kEndpointIdLength; i++) {
+ id += kEndpointIdChars[prng_.NextUint32() % sizeof(kEndpointIdChars)];
+ }
+ return id;
+}
+
+void ClientProxy::Reset() {
+ MutexLock lock(&mutex_);
+
+ StoppedAdvertising();
+ StoppedDiscovery();
+ RemoveAllEndpoints();
+ ExitHighVisibilityMode();
+ analytics_recorder_->LogSession();
+}
+
+void ClientProxy::StartedAdvertising(
+ const std::string& service_id, Strategy strategy,
+ const ConnectionListener& listener,
+ absl::Span<proto::connections::Medium> mediums,
+ const AdvertisingOptions& advertising_options) {
+ MutexLock lock(&mutex_);
+ NEARBY_LOGS(INFO) << "ClientProxy [StartedAdvertising]: client="
+ << GetClientId();
+
+ if (high_vis_mode_) {
+ local_high_vis_mode_cache_endpoint_id_ = local_endpoint_id_;
+ NEARBY_LOGS(INFO)
+ << "ClientProxy [High Visibility Mode Adv, Cache EndpointId]: client="
+ << GetClientId() << "; local_high_vis_mode_cache_endpoint_id_="
+ << local_high_vis_mode_cache_endpoint_id_;
+ CancelClearLocalHighVisModeCacheEndpointIdAlarm();
+ }
+
+ advertising_info_ = {service_id, listener};
+ advertising_options_ = advertising_options;
+
+ const std::vector<proto::connections::Medium> medium_vector(mediums.begin(),
+ mediums.end());
+ analytics_recorder_->OnStartAdvertising(strategy, medium_vector, false, 0);
+}
+
+void ClientProxy::StoppedAdvertising() {
+ MutexLock lock(&mutex_);
+ NEARBY_LOGS(INFO) << "ClientProxy [StoppedAdvertising]: client="
+ << GetClientId();
+
+ if (IsAdvertising()) {
+ advertising_info_.Clear();
+ analytics_recorder_->OnStopAdvertising();
+ }
+ // advertising_options_ is purposefully not cleared here.
+ ResetLocalEndpointIdIfNeeded();
+
+ ExitHighVisibilityMode();
+}
+
+bool ClientProxy::IsAdvertising() const {
+ MutexLock lock(&mutex_);
+
+ return !advertising_info_.IsEmpty();
+}
+
+std::string ClientProxy::GetAdvertisingServiceId() const {
+ MutexLock lock(&mutex_);
+ return advertising_info_.service_id;
+}
+
+std::string ClientProxy::GetServiceId() const {
+ MutexLock lock(&mutex_);
+ if (IsAdvertising()) return advertising_info_.service_id;
+ if (IsDiscovering()) return discovery_info_.service_id;
+ return "idle_service_id";
+}
+
+void ClientProxy::StartedDiscovery(
+ const std::string& service_id, Strategy strategy,
+ const DiscoveryListener& listener,
+ absl::Span<proto::connections::Medium> mediums,
+ const DiscoveryOptions& discovery_options) {
+ MutexLock lock(&mutex_);
+ discovery_info_ = DiscoveryInfo{service_id, listener};
+ discovery_options_ = discovery_options;
+
+ const std::vector<proto::connections::Medium> medium_vector(mediums.begin(),
+ mediums.end());
+ analytics_recorder_->OnStartDiscovery(strategy, medium_vector, false, 0);
+}
+
+void ClientProxy::StoppedDiscovery() {
+ MutexLock lock(&mutex_);
+
+ if (IsDiscovering()) {
+ discovered_endpoint_ids_.clear();
+ discovery_info_.Clear();
+ analytics_recorder_->OnStopDiscovery();
+ }
+ // discovery_options_ is purposefully not cleared here.
+ ResetLocalEndpointIdIfNeeded();
+}
+
+bool ClientProxy::IsDiscoveringServiceId(const std::string& service_id) const {
+ MutexLock lock(&mutex_);
+
+ return IsDiscovering() && service_id == discovery_info_.service_id;
+}
+
+bool ClientProxy::IsDiscovering() const {
+ MutexLock lock(&mutex_);
+
+ return !discovery_info_.IsEmpty();
+}
+
+std::string ClientProxy::GetDiscoveryServiceId() const {
+ MutexLock lock(&mutex_);
+
+ return discovery_info_.service_id;
+}
+
+void ClientProxy::OnEndpointFound(const std::string& service_id,
+ const std::string& endpoint_id,
+ const ByteArray& endpoint_info,
+ proto::connections::Medium medium) {
+ MutexLock lock(&mutex_);
+
+ NEARBY_LOGS(INFO) << "ClientProxy [Endpoint Found]: [enter] id="
+ << endpoint_id << "; service=" << service_id << "; info="
+ << absl::BytesToHexString(endpoint_info.data());
+ if (!IsDiscoveringServiceId(service_id)) {
+ NEARBY_LOGS(INFO) << "ClientProxy [Endpoint Found]: Ignoring event for id="
+ << endpoint_id
+ << " because this client is not discovering.";
+ return;
+ }
+
+ if (discovered_endpoint_ids_.count(endpoint_id)) {
+ NEARBY_LOGS(WARNING)
+ << "ClientProxy [Endpoint Found]: Ignoring event for id=" << endpoint_id
+ << " because this client has already reported this endpoint as found.";
+ return;
+ }
+
+ discovered_endpoint_ids_.insert(endpoint_id);
+ discovery_info_.listener.endpoint_found_cb(endpoint_id, endpoint_info,
+ service_id);
+ analytics_recorder_->OnEndpointFound(medium);
+}
+
+void ClientProxy::OnEndpointLost(const std::string& service_id,
+ const std::string& endpoint_id) {
+ MutexLock lock(&mutex_);
+
+ NEARBY_LOGS(INFO) << "ClientProxy [Endpoint Lost]: [enter] id=" << endpoint_id
+ << "; service=" << service_id;
+ if (!IsDiscoveringServiceId(service_id)) {
+ NEARBY_LOG(INFO,
+ "ClientProxy [Endpoint Lost]: Ignoring event for id=%s because "
+ "this client is not discovering",
+ endpoint_id.c_str());
+ return;
+ }
+
+ const auto it = discovered_endpoint_ids_.find(endpoint_id);
+ if (it == discovered_endpoint_ids_.end()) {
+ NEARBY_LOGS(WARNING)
+ << "ClientProxy [Endpoint Lost]: Ignoring event for id=" << endpoint_id
+ << " because this client has not yet reported this endpoint as found";
+ return;
+ }
+
+ discovered_endpoint_ids_.erase(it);
+ discovery_info_.listener.endpoint_lost_cb(endpoint_id);
+}
+
+void ClientProxy::OnConnectionInitiated(
+ const std::string& endpoint_id, const ConnectionResponseInfo& info,
+ const ConnectionOptions& connection_options,
+ const ConnectionListener& listener, const std::string& connection_token) {
+ MutexLock lock(&mutex_);
+
+ // Whether this is incoming or outgoing, the local and remote endpoints both
+ // still need to accept this connection, so set its establishment status to
+ // PENDING.
+ auto result = connections_.emplace(
+ endpoint_id, Connection{
+ .is_incoming = info.is_incoming_connection,
+ .connection_listener = listener,
+ .connection_options = connection_options,
+ .connection_token = connection_token,
+ });
+ // Instead of using structured binding which is nice, but banned
+ // (can not use c++17 features, until chromium does) we unpack manually.
+ auto& pair_iter = result.first;
+ bool inserted = result.second;
+ NEARBY_LOGS(INFO)
+ << "ClientProxy [Connection Initiated]: add Connection: client="
+ << GetClientId() << "; endpoint_id=" << endpoint_id
+ << "; inserted=" << inserted;
+ DCHECK(inserted);
+ const Connection& item = pair_iter->second;
+ // Notify the client.
+ //
+ // Note: we allow devices to connect to an advertiser even after it stops
+ // advertising, so no need to check IsAdvertising() here.
+ item.connection_listener.initiated_cb(endpoint_id, info);
+
+ if (info.is_incoming_connection) {
+ // Add CancellationFlag for advertisers once encryption succeeds.
+ AddCancellationFlag(endpoint_id);
+ analytics_recorder_->OnConnectionRequestReceived(endpoint_id);
+ } else {
+ analytics_recorder_->OnConnectionRequestSent(endpoint_id);
+ }
+}
+
+void ClientProxy::OnConnectionAccepted(const std::string& endpoint_id) {
+ MutexLock lock(&mutex_);
+
+ if (!HasPendingConnectionToEndpoint(endpoint_id)) {
+ NEARBY_LOGS(INFO) << "ClientProxy [Connection Accepted]: no pending "
+ "connection; endpoint_id="
+ << endpoint_id;
+ return;
+ }
+
+ // Notify the client.
+ Connection* item = LookupConnection(endpoint_id);
+ if (item != nullptr) {
+ item->connection_listener.accepted_cb(endpoint_id);
+ item->status = Connection::kConnected;
+ }
+}
+
+void ClientProxy::OnConnectionRejected(const std::string& endpoint_id,
+ const Status& status) {
+ MutexLock lock(&mutex_);
+
+ if (!HasPendingConnectionToEndpoint(endpoint_id)) {
+ NEARBY_LOGS(INFO) << "ClientProxy [Connection Rejected]: no pending "
+ "connection; endpoint_id="
+ << endpoint_id;
+ return;
+ }
+
+ // Notify the client.
+ const Connection* item = LookupConnection(endpoint_id);
+ if (item != nullptr) {
+ item->connection_listener.rejected_cb(endpoint_id, status);
+ OnDisconnected(endpoint_id, false /* notify */);
+ }
+}
+
+void ClientProxy::OnBandwidthChanged(const std::string& endpoint_id,
+ Medium new_medium) {
+ MutexLock lock(&mutex_);
+
+ const Connection* item = LookupConnection(endpoint_id);
+ if (item != nullptr) {
+ item->connection_listener.bandwidth_changed_cb(endpoint_id, new_medium);
+ NEARBY_LOGS(INFO) << "ClientProxy [reporting onBandwidthChanged]: client="
+ << GetClientId() << "; endpoint_id=" << endpoint_id;
+ }
+}
+
+void ClientProxy::OnDisconnected(const std::string& endpoint_id, bool notify) {
+ MutexLock lock(&mutex_);
+
+ const Connection* item = LookupConnection(endpoint_id);
+ if (item != nullptr) {
+ if (notify) {
+ item->connection_listener.disconnected_cb({endpoint_id});
+ }
+ connections_.erase(endpoint_id);
+ ResetLocalEndpointIdIfNeeded();
+ }
+
+ CancelEndpoint(endpoint_id);
+}
+
+bool ClientProxy::ConnectionStatusMatches(const std::string& endpoint_id,
+ Connection::Status status) const {
+ MutexLock lock(&mutex_);
+
+ const Connection* item = LookupConnection(endpoint_id);
+ if (item != nullptr) {
+ return item->status == status;
+ }
+ return false;
+}
+
+BooleanMediumSelector ClientProxy::GetUpgradeMediums(
+ const std::string& endpoint_id) const {
+ MutexLock lock(&mutex_);
+
+ const Connection* item = LookupConnection(endpoint_id);
+ if (item != nullptr) {
+ return item->connection_options.allowed;
+ }
+ return {};
+}
+
+bool ClientProxy::IsConnectedToEndpoint(const std::string& endpoint_id) const {
+ return ConnectionStatusMatches(endpoint_id, Connection::kConnected);
+}
+
+std::vector<std::string> ClientProxy::GetMatchingEndpoints(
+ std::function<bool(const Connection&)> pred) const {
+ MutexLock lock(&mutex_);
+
+ std::vector<std::string> connected_endpoints;
+
+ for (const auto& pair : connections_) {
+ const auto& endpoint_id = pair.first;
+ const auto& connection = pair.second;
+ if (pred(connection)) {
+ connected_endpoints.push_back(endpoint_id);
+ }
+ }
+ return connected_endpoints;
+}
+
+std::vector<std::string> ClientProxy::GetPendingConnectedEndpoints() const {
+ return GetMatchingEndpoints([](const Connection& connection) {
+ return connection.status != Connection::kConnected;
+ });
+}
+
+std::vector<std::string> ClientProxy::GetConnectedEndpoints() const {
+ return GetMatchingEndpoints([](const Connection& connection) {
+ return connection.status == Connection::kConnected;
+ });
+}
+
+std::int32_t ClientProxy::GetNumOutgoingConnections() const {
+ return GetMatchingEndpoints([](const Connection& connection) {
+ return connection.status == Connection::kConnected &&
+ !connection.is_incoming;
+ })
+ .size();
+}
+
+std::int32_t ClientProxy::GetNumIncomingConnections() const {
+ return GetMatchingEndpoints([](const Connection& connection) {
+ return connection.status == Connection::kConnected &&
+ connection.is_incoming;
+ })
+ .size();
+}
+
+bool ClientProxy::HasPendingConnectionToEndpoint(
+ const std::string& endpoint_id) const {
+ MutexLock lock(&mutex_);
+
+ const Connection* item = LookupConnection(endpoint_id);
+ if (item != nullptr) {
+ return item->status != Connection::kConnected;
+ }
+ return false;
+}
+
+bool ClientProxy::HasLocalEndpointResponded(
+ const std::string& endpoint_id) const {
+ MutexLock lock(&mutex_);
+
+ return ConnectionStatusesContains(
+ endpoint_id,
+ static_cast<Connection::Status>(Connection::kLocalEndpointAccepted |
+ Connection::kLocalEndpointRejected));
+}
+
+bool ClientProxy::HasRemoteEndpointResponded(
+ const std::string& endpoint_id) const {
+ MutexLock lock(&mutex_);
+
+ return ConnectionStatusesContains(
+ endpoint_id,
+ static_cast<Connection::Status>(Connection::kRemoteEndpointAccepted |
+ Connection::kRemoteEndpointRejected));
+}
+
+void ClientProxy::LocalEndpointAcceptedConnection(
+ const std::string& endpoint_id, const PayloadListener& listener) {
+ MutexLock lock(&mutex_);
+
+ if (HasLocalEndpointResponded(endpoint_id)) {
+ NEARBY_LOGS(INFO)
+ << "ClientProxy [Local Accepted]: local endpoint has responded; id="
+ << endpoint_id;
+ return;
+ }
+
+ AppendConnectionStatus(endpoint_id, Connection::kLocalEndpointAccepted);
+ Connection* item = LookupConnection(endpoint_id);
+ if (item != nullptr) {
+ item->payload_listener = listener;
+ }
+ analytics_recorder_->OnLocalEndpointAccepted(endpoint_id);
+}
+
+void ClientProxy::LocalEndpointRejectedConnection(
+ const std::string& endpoint_id) {
+ MutexLock lock(&mutex_);
+
+ if (HasLocalEndpointResponded(endpoint_id)) {
+ NEARBY_LOGS(INFO)
+ << "ClientProxy [Local Rejected]: local endpoint has responded; id="
+ << endpoint_id;
+ return;
+ }
+
+ AppendConnectionStatus(endpoint_id, Connection::kLocalEndpointRejected);
+ analytics_recorder_->OnLocalEndpointRejected(endpoint_id);
+}
+
+void ClientProxy::RemoteEndpointAcceptedConnection(
+ const std::string& endpoint_id) {
+ MutexLock lock(&mutex_);
+
+ if (HasRemoteEndpointResponded(endpoint_id)) {
+ NEARBY_LOGS(INFO)
+ << "ClientProxy [Remote Accepted]: remote endpoint has responded; id="
+ << endpoint_id;
+ return;
+ }
+
+ AppendConnectionStatus(endpoint_id, Connection::kRemoteEndpointAccepted);
+ analytics_recorder_->OnRemoteEndpointAccepted(endpoint_id);
+}
+
+void ClientProxy::RemoteEndpointRejectedConnection(
+ const std::string& endpoint_id) {
+ MutexLock lock(&mutex_);
+
+ if (HasRemoteEndpointResponded(endpoint_id)) {
+ NEARBY_LOGS(INFO)
+ << "ClientProxy [Remote Rejected]: remote endpoint has responded; id="
+ << endpoint_id;
+ return;
+ }
+
+ AppendConnectionStatus(endpoint_id, Connection::kRemoteEndpointRejected);
+ analytics_recorder_->OnRemoteEndpointRejected(endpoint_id);
+}
+
+bool ClientProxy::IsConnectionAccepted(const std::string& endpoint_id) const {
+ MutexLock lock(&mutex_);
+
+ return ConnectionStatusesContains(endpoint_id,
+ Connection::kLocalEndpointAccepted) &&
+ ConnectionStatusesContains(endpoint_id,
+ Connection::kRemoteEndpointAccepted);
+}
+
+bool ClientProxy::IsConnectionRejected(const std::string& endpoint_id) const {
+ MutexLock lock(&mutex_);
+
+ return ConnectionStatusesContains(
+ endpoint_id,
+ static_cast<Connection::Status>(Connection::kLocalEndpointRejected |
+ Connection::kRemoteEndpointRejected));
+}
+
+bool ClientProxy::LocalConnectionIsAccepted(std::string endpoint_id) const {
+ return ConnectionStatusesContains(
+ endpoint_id, ClientProxy::Connection::kLocalEndpointAccepted);
+}
+
+bool ClientProxy::RemoteConnectionIsAccepted(std::string endpoint_id) const {
+ return ConnectionStatusesContains(
+ endpoint_id, ClientProxy::Connection::kRemoteEndpointAccepted);
+}
+
+void ClientProxy::AddCancellationFlag(const std::string& endpoint_id) {
+ // Don't insert the CancellationFlag to the map if feature flag is disabled.
+ if (!FeatureFlags::GetInstance().GetFlags().enable_cancellation_flag) {
+ return;
+ }
+
+ auto item = cancellation_flags_.find(endpoint_id);
+ if (item != cancellation_flags_.end()) {
+ return;
+ }
+ cancellation_flags_.emplace(endpoint_id,
+ std::make_unique<CancellationFlag>());
+}
+
+CancellationFlag* ClientProxy::GetCancellationFlag(
+ const std::string& endpoint_id) {
+ const auto item = cancellation_flags_.find(endpoint_id);
+ if (item == cancellation_flags_.end()) {
+ return default_cancellation_flag_.get();
+ }
+ return item->second.get();
+}
+
+void ClientProxy::CancelEndpoint(const std::string& endpoint_id) {
+ const auto item = cancellation_flags_.find(endpoint_id);
+ if (item == cancellation_flags_.end()) return;
+ item->second->Cancel();
+ cancellation_flags_.erase(item);
+}
+
+void ClientProxy::CancelAllEndpoints() {
+ for (const auto& item : cancellation_flags_) {
+ CancellationFlag* cancellation_flag = item.second.get();
+ if (cancellation_flag->Cancelled()) {
+ continue;
+ }
+ cancellation_flag->Cancel();
+ }
+ cancellation_flags_.clear();
+}
+
+void ClientProxy::OnPayload(const std::string& endpoint_id, Payload payload) {
+ MutexLock lock(&mutex_);
+
+ if (IsConnectedToEndpoint(endpoint_id)) {
+ const Connection* item = LookupConnection(endpoint_id);
+ if (item != nullptr) {
+ NEARBY_LOGS(INFO) << "ClientProxy [reporting onPayloadReceived]: client="
+ << GetClientId() << "; endpoint_id=" << endpoint_id
+ << " ; payload_id=" << payload.GetId();
+ item->payload_listener.payload_cb(endpoint_id, std::move(payload));
+ }
+ }
+}
+
+const ClientProxy::Connection* ClientProxy::LookupConnection(
+ const std::string& endpoint_id) const {
+ auto item = connections_.find(endpoint_id);
+ return item != connections_.end() ? &item->second : nullptr;
+}
+
+ClientProxy::Connection* ClientProxy::LookupConnection(
+ const std::string& endpoint_id) {
+ auto item = connections_.find(endpoint_id);
+ return item != connections_.end() ? &item->second : nullptr;
+}
+
+void ClientProxy::OnPayloadProgress(const std::string& endpoint_id,
+ const PayloadProgressInfo& info) {
+ MutexLock lock(&mutex_);
+
+ if (IsConnectedToEndpoint(endpoint_id)) {
+ Connection* item = LookupConnection(endpoint_id);
+ if (item != nullptr) {
+ item->payload_listener.payload_progress_cb(endpoint_id, info);
+
+ if (info.status == PayloadProgressInfo::Status::kInProgress) {
+ NEARBY_LOGS(VERBOSE)
+ << "ClientProxy [reporting onPayloadProgress]: client="
+ << GetClientId() << "; endpoint_id=" << endpoint_id
+ << "; payload_id=" << info.payload_id
+ << ", payload_status=" << ToString(info.status);
+ } else {
+ NEARBY_LOGS(INFO)
+ << "ClientProxy [reporting onPayloadProgress]: client="
+ << GetClientId() << "; endpoint_id=" << endpoint_id
+ << "; payload_id=" << info.payload_id
+ << ", payload_status=" << ToString(info.status);
+ }
+ }
+ }
+}
+
+void ClientProxy::RemoveAllEndpoints() {
+ MutexLock lock(&mutex_);
+
+ // Note: we may want to notify the client of onDisconnected() for each
+ // endpoint, in the case when this is called from stopAllEndpoints(). For now,
+ // just remove without notifying.
+ connections_.clear();
+ cancellation_flags_.clear();
+ local_endpoint_id_.clear();
+}
+
+void ClientProxy::ResetLocalEndpointIdIfNeeded() {
+ MutexLock lock(&mutex_);
+ if (connections_.empty() && !IsAdvertising() && !IsDiscovering()) {
+ local_endpoint_id_.clear();
+ }
+}
+
+bool ClientProxy::ConnectionStatusesContains(
+ const std::string& endpoint_id, Connection::Status status_to_match) const {
+ const Connection* item = LookupConnection(endpoint_id);
+ if (item != nullptr) {
+ return (item->status & status_to_match) != 0;
+ }
+ return false;
+}
+
+void ClientProxy::AppendConnectionStatus(const std::string& endpoint_id,
+ Connection::Status status_to_append) {
+ Connection* item = LookupConnection(endpoint_id);
+ if (item != nullptr) {
+ item->status =
+ static_cast<Connection::Status>(item->status | status_to_append);
+ }
+}
+
+AdvertisingOptions ClientProxy::GetAdvertisingOptions() const {
+ return advertising_options_;
+}
+
+DiscoveryOptions ClientProxy::GetDiscoveryOptions() const {
+ return discovery_options_;
+}
+
+void ClientProxy::EnterHighVisibilityMode() {
+ MutexLock lock(&mutex_);
+ NEARBY_LOGS(INFO) << "ClientProxy [EnterHighVisibilityMode]: client="
+ << GetClientId();
+
+ high_vis_mode_ = true;
+}
+
+void ClientProxy::ExitHighVisibilityMode() {
+ MutexLock lock(&mutex_);
+ NEARBY_LOGS(INFO) << "ClientProxy [ExitHighVisibilityMode]: client="
+ << GetClientId();
+
+ high_vis_mode_ = false;
+ ScheduleClearLocalHighVisModeCacheEndpointIdAlarm();
+}
+
+void ClientProxy::ScheduleClearLocalHighVisModeCacheEndpointIdAlarm() {
+ CancelClearLocalHighVisModeCacheEndpointIdAlarm();
+
+ if (local_high_vis_mode_cache_endpoint_id_.empty()) {
+ NEARBY_LOGS(VERBOSE) << "ClientProxy [There is no cached local high power "
+ "advertising endpoint Id]: client="
+ << GetClientId();
+ return;
+ }
+
+ // Schedule to clear cache high visibility mode advertisement endpoint id in
+ // 30s.
+ NEARBY_LOGS(INFO) << "ClientProxy [High Visibility Mode Adv, Schedule to "
+ "Clear Cache EndpointId]: client="
+ << GetClientId()
+ << "; local_high_vis_mode_cache_endpoint_id_="
+ << local_high_vis_mode_cache_endpoint_id_;
+ clear_local_high_vis_mode_cache_endpoint_id_alarm_ =
+ CancelableAlarm(
+ "clear_high_power_endpoint_id_cache",
+ [this]() {
+ MutexLock lock(&mutex_);
+ NEARBY_LOGS(INFO)
+ << "ClientProxy [Cleared cached local high power advertising "
+ "endpoint Id.]: client="
+ << GetClientId() << "; local_high_vis_mode_cache_endpoint_id_="
+ << local_high_vis_mode_cache_endpoint_id_;
+ local_high_vis_mode_cache_endpoint_id_.clear();
+ },
+ kHighPowerAdvertisementEndpointIdCacheTimeout,
+ &single_thread_executor_);
+}
+
+void ClientProxy::CancelClearLocalHighVisModeCacheEndpointIdAlarm() {
+ if (clear_local_high_vis_mode_cache_endpoint_id_alarm_.IsValid()) {
+ clear_local_high_vis_mode_cache_endpoint_id_alarm_.Cancel();
+ clear_local_high_vis_mode_cache_endpoint_id_alarm_ = CancelableAlarm();
+ }
+}
+
+std::string ClientProxy::ToString(PayloadProgressInfo::Status status) const {
+ switch (status) {
+ case PayloadProgressInfo::Status::kSuccess:
+ return std::string("Success");
+ case PayloadProgressInfo::Status::kFailure:
+ return std::string("Failure");
+ case PayloadProgressInfo::Status::kInProgress:
+ return std::string("In Progress");
+ case PayloadProgressInfo::Status::kCanceled:
+ return std::string("Cancelled");
+ }
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/client_proxy.h b/chromium/third_party/nearby/src/connections/implementation/client_proxy.h
new file mode 100644
index 00000000000..763105a2adb
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/client_proxy.h
@@ -0,0 +1,326 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_CLIENT_PROXY_H_
+#define CORE_INTERNAL_CLIENT_PROXY_H_
+
+#include <cstdint>
+#include <functional>
+#include <string>
+#include <vector>
+
+#include "connections/advertising_options.h"
+#include "connections/discovery_options.h"
+#include "connections/listeners.h"
+#include "connections/status.h"
+#include "connections/strategy.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/cancellation_flag.h"
+#include "internal/platform/error_code_recorder.h"
+#include "internal/platform/prng.h"
+#include "internal/platform/cancelable_alarm.h"
+#include "internal/platform/mutex.h"
+#include "internal/analytics/analytics_recorder.h"
+// Prefer using absl:: versions of a set and a map; they tend to be more
+// efficient: implementation is using open-addressing hash tables.
+#include "absl/container/flat_hash_map.h"
+#include "absl/container/flat_hash_set.h"
+#include "absl/types/span.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// ClientProxy is tracking state of client's connection, and serves as
+// a proxy for notifications sent to this client.
+class ClientProxy final {
+ public:
+ static constexpr int kEndpointIdLength = 4;
+ static constexpr absl::Duration
+ kHighPowerAdvertisementEndpointIdCacheTimeout = absl::Seconds(30);
+
+ explicit ClientProxy(analytics::EventLogger* event_logger = nullptr);
+ ~ClientProxy();
+ ClientProxy(ClientProxy&&) = default;
+ ClientProxy& operator=(ClientProxy&&) = default;
+
+ std::int64_t GetClientId() const;
+
+ std::string GetLocalEndpointId();
+
+ analytics::AnalyticsRecorder& GetAnalyticsRecorder() const {
+ return *analytics_recorder_;
+ }
+
+ std::string GetConnectionToken(const std::string& endpoint_id);
+
+ // Clears all the runtime state of this client.
+ void Reset();
+
+ // Marks this client as advertising with the given callbacks.
+ void StartedAdvertising(
+ const std::string& service_id, Strategy strategy,
+ const ConnectionListener& connection_lifecycle_listener,
+ absl::Span<proto::connections::Medium> mediums,
+ const AdvertisingOptions& advertising_options = AdvertisingOptions{});
+ // Marks this client as not advertising.
+ void StoppedAdvertising();
+ bool IsAdvertising() const;
+ std::string GetAdvertisingServiceId() const;
+
+ // Get service ID of a surrently active link (either advertising, or
+ // discovering).
+ std::string GetServiceId() const;
+
+ // Marks this client as discovering with the given callback.
+ void StartedDiscovery(
+ const std::string& service_id, Strategy strategy,
+ const DiscoveryListener& discovery_listener,
+ absl::Span<proto::connections::Medium> mediums,
+ const DiscoveryOptions& discovery_options = DiscoveryOptions{});
+ // Marks this client as not discovering at all.
+ void StoppedDiscovery();
+ bool IsDiscoveringServiceId(const std::string& service_id) const;
+ bool IsDiscovering() const;
+ std::string GetDiscoveryServiceId() const;
+
+ // Proxies to the client's DiscoveryListener::OnEndpointFound() callback.
+ void OnEndpointFound(const std::string& service_id,
+ const std::string& endpoint_id,
+ const ByteArray& endpoint_info,
+ proto::connections::Medium medium);
+ // Proxies to the client's DiscoveryListener::OnEndpointLost() callback.
+ void OnEndpointLost(const std::string& service_id,
+ const std::string& endpoint_id);
+
+ // Proxies to the client's ConnectionListener::OnInitiated() callback.
+ void OnConnectionInitiated(const std::string& endpoint_id,
+ const ConnectionResponseInfo& info,
+ const ConnectionOptions& connection_options,
+ const ConnectionListener& listener,
+ const std::string& connection_token);
+
+ // Proxies to the client's ConnectionListener::OnAccepted() callback.
+ void OnConnectionAccepted(const std::string& endpoint_id);
+ // Proxies to the client's ConnectionListener::OnRejected() callback.
+ void OnConnectionRejected(const std::string& endpoint_id,
+ const Status& status);
+
+ void OnBandwidthChanged(const std::string& endpoint_id, Medium new_medium);
+
+ // Removes the endpoint from this client's list of connected endpoints. If
+ // notify is true, also calls the client's
+ // ConnectionListener.disconnected_cb() callback.
+ void OnDisconnected(const std::string& endpoint_id, bool notify);
+
+ // Returns all mediums eligible for upgrade.
+ BooleanMediumSelector GetUpgradeMediums(const std::string& endpoint_id) const;
+ // Returns true if it's safe to send payloads to this endpoint.
+ bool IsConnectedToEndpoint(const std::string& endpoint_id) const;
+ // Returns all endpoints that can safely be sent payloads.
+ std::vector<std::string> GetConnectedEndpoints() const;
+ // Returns all endpoints that are still awaiting acceptance.
+ std::vector<std::string> GetPendingConnectedEndpoints() const;
+ // Returns the number of endpoints that are connected and outgoing.
+ std::int32_t GetNumOutgoingConnections() const;
+ // Returns the number of endpoints that are connected and incoming.
+ std::int32_t GetNumIncomingConnections() const;
+ // If true, then we're in the process of approving (or rejecting) a
+ // connection. No payloads should be sent until isConnectedToEndpoint()
+ // returns true.
+ bool HasPendingConnectionToEndpoint(const std::string& endpoint_id) const;
+ // Returns true if the local endpoint has already marked itself as
+ // accepted/rejected.
+ bool HasLocalEndpointResponded(const std::string& endpoint_id) const;
+ // Returns true if the remote endpoint has already marked themselves as
+ // accepted/rejected.
+ bool HasRemoteEndpointResponded(const std::string& endpoint_id) const;
+ // Marks the local endpoint as having accepted the connection.
+ void LocalEndpointAcceptedConnection(const std::string& endpoint_id,
+ const PayloadListener& listener);
+ // Marks the local endpoint as having rejected the connection.
+ void LocalEndpointRejectedConnection(const std::string& endpoint_id);
+ // Marks the remote endpoint as having accepted the connection.
+ void RemoteEndpointAcceptedConnection(const std::string& endpoint_id);
+ // Marks the remote endpoint as having rejected the connection.
+ void RemoteEndpointRejectedConnection(const std::string& endpoint_id);
+ // Returns true if both the local endpoint and the remote endpoint have
+ // accepted the connection.
+ bool IsConnectionAccepted(const std::string& endpoint_id) const;
+ // Returns true if either the local endpoint or the remote endpoint has
+ // rejected the connection.
+ bool IsConnectionRejected(const std::string& endpoint_id) const;
+
+ // Proxies to the client's PayloadListener::OnPayload() callback.
+ void OnPayload(const std::string& endpoint_id, Payload payload);
+ // Proxies to the client's PayloadListener::OnPayloadProgress() callback.
+ void OnPayloadProgress(const std::string& endpoint_id,
+ const PayloadProgressInfo& info);
+ bool LocalConnectionIsAccepted(std::string endpoint_id) const;
+ bool RemoteConnectionIsAccepted(std::string endpoint_id) const;
+
+ // Adds a CancellationFlag for endpoint id.
+ void AddCancellationFlag(const std::string& endpoint_id);
+ // Returns the CancellationFlag for endpoint id,
+ CancellationFlag* GetCancellationFlag(const std::string& endpoint_id);
+ // Sets the CancellationFlag to true for endpoint id.
+ void CancelEndpoint(const std::string& endpoint_id);
+ // Cancels all CancellationFlags.
+ void CancelAllEndpoints();
+ AdvertisingOptions GetAdvertisingOptions() const;
+ DiscoveryOptions GetDiscoveryOptions() const;
+
+ // The endpoint id will be stable for 30 seconds after high visibility mode
+ // (high power and Bluetooth Classic) advertisement stops.
+ // If client re-enters high visibility mode within 30 seconds, he is going to
+ // have the same endpoint id.
+ void EnterHighVisibilityMode();
+ // Cleans up any modifications in high visibility mode. The endpoint id always
+ // rotates.
+ void ExitHighVisibilityMode();
+
+ private:
+ struct Connection {
+ // Status: may be either:
+ // Connection::PENDING, or combination of
+ // Connection::LOCAL_ENDPOINT_ACCEPTED:
+ // Connection::LOCAL_ENDPOINT_REJECTED and
+ // Connection::REMOTE_ENDPOINT_ACCEPTED:
+ // Connection::REMOTE_ENDPOINT_REJECTED, or
+ // Connection::CONNECTED.
+ // Only when this is set to CONNECTED should you allow payload transfers.
+ //
+ // We want this enum to be implicitly convertible to int, because
+ // we perform bit operations on it.
+ enum Status : uint8_t {
+ kPending = 0,
+ kLocalEndpointAccepted = 1 << 0,
+ kLocalEndpointRejected = 1 << 1,
+ kRemoteEndpointAccepted = 1 << 2,
+ kRemoteEndpointRejected = 1 << 3,
+ kConnected = 1 << 4,
+ };
+ bool is_incoming{false};
+ Status status{kPending};
+ ConnectionListener connection_listener;
+ PayloadListener payload_listener;
+ ConnectionOptions connection_options;
+ DiscoveryOptions discovery_options;
+ AdvertisingOptions advertising_options;
+ std::string connection_token;
+ };
+
+ struct AdvertisingInfo {
+ std::string service_id;
+ ConnectionListener listener;
+ void Clear() { service_id.clear(); }
+ bool IsEmpty() const { return service_id.empty(); }
+ };
+
+ struct DiscoveryInfo {
+ std::string service_id;
+ DiscoveryListener listener;
+ void Clear() { service_id.clear(); }
+ bool IsEmpty() const { return service_id.empty(); }
+ };
+
+ void RemoveAllEndpoints();
+ void ResetLocalEndpointIdIfNeeded();
+ bool ConnectionStatusesContains(const std::string& endpoint_id,
+ Connection::Status status_to_match) const;
+ void AppendConnectionStatus(const std::string& endpoint_id,
+ Connection::Status status_to_append);
+
+ const Connection* LookupConnection(const std::string& endpoint_id) const;
+ Connection* LookupConnection(const std::string& endpoint_id);
+ bool ConnectionStatusMatches(const std::string& endpoint_id,
+ Connection::Status status) const;
+ std::vector<std::string> GetMatchingEndpoints(
+ std::function<bool(const Connection&)> pred) const;
+ std::string GenerateLocalEndpointId();
+
+ void ScheduleClearLocalHighVisModeCacheEndpointIdAlarm();
+ void CancelClearLocalHighVisModeCacheEndpointIdAlarm();
+
+ std::string ToString(PayloadProgressInfo::Status status) const;
+
+ mutable RecursiveMutex mutex_;
+ Prng prng_;
+ std::int64_t client_id_;
+ std::string local_endpoint_id_;
+ // If currently is advertising in high visibility mode is true: high power and
+ // Bluetooth Classic enabled. When high_visibility_mode_ is true, the endpoint
+ // id is stable for 30s. When high_visibility_mode_ is false, the endpoint id
+ // always rotates.
+ bool high_vis_mode_{false};
+ // Caches the endpoint id when it is in high visibility mode advertisement for
+ // 30s. Currently, Nearby Connections keeps rotating endpoint id. The client
+ // (Nearby Share) treats different endpoints as different receivers, duplicate
+ // share targets for same devices occur on share sheet in this case.
+ // Therefore, we remember the high visibility mode advertisement endpoint id
+ // here. empty if 1) There is no high power advertisement before 2) The
+ // endpoint id cached here in previous high visibility mode advertisement
+ // expires.
+ std::string local_high_vis_mode_cache_endpoint_id_;
+ ScheduledExecutor single_thread_executor_;
+ CancelableAlarm clear_local_high_vis_mode_cache_endpoint_id_alarm_;
+
+ // If not empty, we are currently advertising and accepting connection
+ // requests for the given service_id.
+ AdvertisingInfo advertising_info_;
+
+ // If not empty, we are currently discovering for the given service_id.
+ DiscoveryInfo discovery_info_;
+
+ // The active ClientProxy's advertising constraints. Empty()
+ // returns true if the client hasn't started advertising false otherwise.
+ // Note: this is not cleared when the client stops advertising because it
+ // might still be useful downstream of advertising (eg: establishing
+ // connections, performing bandwidth upgrades, etc.)
+ AdvertisingOptions advertising_options_;
+
+ // The active ClientProxy's discovery constraints. Null if the client
+ // hasn't started discovering. Note: this is not cleared when the client
+ // stops discovering because it might still be useful downstream of
+ // discovery (eg: connection speed, etc.)
+ DiscoveryOptions discovery_options_;
+
+ // Maps endpoint_id to endpoint connection state.
+ absl::flat_hash_map<std::string, Connection> connections_;
+
+ // A cache of endpoint ids that we've already notified the discoverer of. We
+ // check this cache before calling onEndpointFound() so that we don't notify
+ // the client multiple times for the same endpoint. This would otherwise
+ // happen because some mediums (like Bluetooth) repeatedly give us the same
+ // endpoints after each scan.
+ absl::flat_hash_set<std::string> discovered_endpoint_ids_;
+
+ // Maps endpoint_id to CancellationFlag.
+ absl::flat_hash_map<std::string, std::unique_ptr<CancellationFlag>>
+ cancellation_flags_;
+ // A default cancellation flag with isCancelled set be true.
+ std::unique_ptr<CancellationFlag> default_cancellation_flag_ =
+ std::make_unique<CancellationFlag>(true);
+
+ // An analytics logger with |EventLogger| provided by client, which is default
+ // nullptr as no-op.
+ std::unique_ptr<analytics::AnalyticsRecorder> analytics_recorder_;
+ std::unique_ptr<ErrorCodeRecorder> error_code_recorder_;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_CLIENT_PROXY_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/client_proxy_test.cc b/chromium/third_party/nearby/src/connections/implementation/client_proxy_test.cc
new file mode 100644
index 00000000000..35112b7dd4f
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/client_proxy_test.cc
@@ -0,0 +1,673 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/client_proxy.h"
+
+#include <string>
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "absl/container/flat_hash_set.h"
+#include "absl/time/clock.h"
+#include "absl/time/time.h"
+#include "absl/types/span.h"
+#include "connections/listeners.h"
+#include "connections/strategy.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/feature_flags.h"
+#include "internal/platform/medium_environment.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+
+using ::testing::MockFunction;
+using ::testing::StrictMock;
+
+constexpr FeatureFlags::Flags kTestCases[] = {
+ FeatureFlags::Flags{
+ .enable_cancellation_flag = true,
+ },
+ FeatureFlags::Flags{
+ .enable_cancellation_flag = false,
+ },
+};
+
+class ClientProxyTest : public ::testing::TestWithParam<FeatureFlags::Flags> {
+ protected:
+ struct MockDiscoveryListener {
+ StrictMock<MockFunction<void(const std::string& endpoint_id,
+ const ByteArray& endpoint_info,
+ const std::string& service_id)>>
+ endpoint_found_cb;
+ StrictMock<MockFunction<void(const std::string& endpoint_id)>>
+ endpoint_lost_cb;
+ };
+ struct MockConnectionListener {
+ StrictMock<MockFunction<void(const std::string& endpoint_id,
+ const ConnectionResponseInfo& info)>>
+ initiated_cb;
+ StrictMock<MockFunction<void(const std::string& endpoint_id)>> accepted_cb;
+ StrictMock<MockFunction<void(const std::string& endpoint_id,
+ const Status& status)>>
+ rejected_cb;
+ StrictMock<MockFunction<void(const std::string& endpoint_id)>>
+ disconnected_cb;
+ StrictMock<MockFunction<void(const std::string& endpoint_id,
+ std::int32_t quality)>>
+ bandwidth_changed_cb;
+ };
+ struct MockPayloadListener {
+ StrictMock<
+ MockFunction<void(const std::string& endpoint_id, Payload payload)>>
+ payload_cb;
+ StrictMock<MockFunction<void(const std::string& endpoint_id,
+ const PayloadProgressInfo& info)>>
+ payload_progress_cb;
+ };
+
+ struct Endpoint {
+ ByteArray info;
+ std::string id;
+ };
+
+ bool ShouldEnterHighVisibilityMode(
+ const AdvertisingOptions& advertising_options) {
+ return !advertising_options.low_power &&
+ advertising_options.allowed.bluetooth;
+ }
+
+ Endpoint StartAdvertising(
+ ClientProxy* client, ConnectionListener listener,
+ AdvertisingOptions advertising_options = AdvertisingOptions{}) {
+ if (ShouldEnterHighVisibilityMode(advertising_options)) {
+ client->EnterHighVisibilityMode();
+ }
+ Endpoint endpoint{
+ .info = ByteArray{"advertising endpoint name"},
+ .id = client->GetLocalEndpointId(),
+ };
+ client->StartedAdvertising(service_id_, strategy_, listener,
+ absl::MakeSpan(mediums_), advertising_options);
+ return endpoint;
+ }
+
+ void StopAdvertising(ClientProxy* client) { client->StoppedAdvertising(); }
+
+ Endpoint StartDiscovery(ClientProxy* client, DiscoveryListener listener) {
+ Endpoint endpoint{
+ .info = ByteArray{"discovery endpoint name"},
+ .id = client->GetLocalEndpointId(),
+ };
+ client->StartedDiscovery(service_id_, strategy_, listener,
+ absl::MakeSpan(mediums_));
+ return endpoint;
+ }
+
+ void OnDiscoveryEndpointFound(ClientProxy* client, const Endpoint& endpoint) {
+ EXPECT_CALL(mock_discovery_.endpoint_found_cb, Call).Times(1);
+ client->OnEndpointFound(service_id_, endpoint.id, endpoint.info, medium_);
+ }
+
+ void OnDiscoveryEndpointLost(ClientProxy* client, const Endpoint& endpoint) {
+ EXPECT_CALL(mock_discovery_.endpoint_lost_cb, Call).Times(1);
+ client->OnEndpointLost(service_id_, endpoint.id);
+ }
+
+ void OnDiscoveryConnectionInitiated(ClientProxy* client,
+ const Endpoint& endpoint) {
+ EXPECT_CALL(mock_discovery_connection_.initiated_cb, Call).Times(1);
+ const std::string auth_token{"auth_token"};
+ const ByteArray raw_auth_token{auth_token};
+ const std::string connection_token{"conntokn"};
+ advertising_connection_info_.remote_endpoint_info = endpoint.info;
+ client->OnConnectionInitiated(
+ endpoint.id, advertising_connection_info_, connection_options_,
+ discovery_connection_listener_, connection_token);
+ EXPECT_TRUE(client->HasPendingConnectionToEndpoint(endpoint.id));
+ }
+
+ void OnDiscoveryConnectionLocalAccepted(ClientProxy* client,
+ const Endpoint& endpoint) {
+ EXPECT_TRUE(client->HasPendingConnectionToEndpoint(endpoint.id));
+ EXPECT_FALSE(client->HasLocalEndpointResponded(endpoint.id));
+ client->LocalEndpointAcceptedConnection(endpoint.id, payload_listener_);
+ EXPECT_TRUE(client->HasLocalEndpointResponded(endpoint.id));
+ EXPECT_TRUE(client->LocalConnectionIsAccepted(endpoint.id));
+ }
+
+ void OnDiscoveryConnectionRemoteAccepted(ClientProxy* client,
+ const Endpoint& endpoint) {
+ EXPECT_TRUE(client->HasPendingConnectionToEndpoint(endpoint.id));
+ EXPECT_FALSE(client->HasRemoteEndpointResponded(endpoint.id));
+ client->RemoteEndpointAcceptedConnection(endpoint.id);
+ EXPECT_TRUE(client->HasRemoteEndpointResponded(endpoint.id));
+ EXPECT_TRUE(client->RemoteConnectionIsAccepted(endpoint.id));
+ }
+
+ void OnDiscoveryConnectionLocalRejected(ClientProxy* client,
+ const Endpoint& endpoint) {
+ EXPECT_TRUE(client->HasPendingConnectionToEndpoint(endpoint.id));
+ EXPECT_FALSE(client->HasLocalEndpointResponded(endpoint.id));
+ client->LocalEndpointRejectedConnection(endpoint.id);
+ EXPECT_TRUE(client->HasLocalEndpointResponded(endpoint.id));
+ EXPECT_FALSE(client->LocalConnectionIsAccepted(endpoint.id));
+ }
+
+ void OnDiscoveryConnectionRemoteRejected(ClientProxy* client,
+ const Endpoint& endpoint) {
+ EXPECT_TRUE(client->HasPendingConnectionToEndpoint(endpoint.id));
+ EXPECT_FALSE(client->HasRemoteEndpointResponded(endpoint.id));
+ client->RemoteEndpointRejectedConnection(endpoint.id);
+ EXPECT_TRUE(client->HasRemoteEndpointResponded(endpoint.id));
+ EXPECT_FALSE(client->RemoteConnectionIsAccepted(endpoint.id));
+ }
+
+ void OnDiscoveryConnectionAccepted(ClientProxy* client,
+ const Endpoint& endpoint) {
+ EXPECT_CALL(mock_discovery_connection_.accepted_cb, Call).Times(1);
+ EXPECT_TRUE(client->IsConnectionAccepted(endpoint.id));
+ client->OnConnectionAccepted(endpoint.id);
+ }
+
+ void OnDiscoveryConnectionRejected(ClientProxy* client,
+ const Endpoint& endpoint) {
+ EXPECT_CALL(mock_discovery_connection_.rejected_cb, Call).Times(1);
+ EXPECT_TRUE(client->IsConnectionRejected(endpoint.id));
+ client->OnConnectionRejected(endpoint.id, {Status::kConnectionRejected});
+ }
+
+ void OnDiscoveryBandwidthChanged(ClientProxy* client,
+ const Endpoint& endpoint) {
+ EXPECT_CALL(mock_discovery_connection_.bandwidth_changed_cb, Call).Times(1);
+ client->OnBandwidthChanged(endpoint.id, Medium::WIFI_LAN);
+ }
+
+ void OnDiscoveryConnectionDisconnected(ClientProxy* client,
+ const Endpoint& endpoint) {
+ EXPECT_CALL(mock_discovery_connection_.disconnected_cb, Call).Times(1);
+ client->OnDisconnected(endpoint.id, true);
+ }
+
+ void OnPayload(ClientProxy* client, const Endpoint& endpoint) {
+ EXPECT_CALL(mock_discovery_payload_.payload_cb, Call).Times(1);
+ client->OnPayload(endpoint.id, Payload(payload_bytes_));
+ }
+
+ void OnPayloadProgress(ClientProxy* client, const Endpoint& endpoint) {
+ EXPECT_CALL(mock_discovery_payload_.payload_progress_cb, Call).Times(1);
+ client->OnPayloadProgress(endpoint.id, {});
+ }
+
+ MockDiscoveryListener mock_discovery_;
+ MockConnectionListener mock_discovery_connection_;
+ MockPayloadListener mock_discovery_payload_;
+
+ proto::connections::Medium medium_{proto::connections::Medium::BLUETOOTH};
+ std::vector<proto::connections::Medium> mediums_{
+ proto::connections::Medium::BLUETOOTH,
+ };
+ Strategy strategy_{Strategy::kP2pPointToPoint};
+ const std::string service_id_{"service"};
+ ClientProxy client1_;
+ ClientProxy client2_;
+ std::string auth_token_ = "auth_token";
+ ByteArray raw_auth_token_ = ByteArray(auth_token_);
+ ByteArray payload_bytes_{"bytes"};
+ ConnectionResponseInfo advertising_connection_info_{
+ .authentication_token = auth_token_,
+ .raw_authentication_token = raw_auth_token_,
+ .is_incoming_connection = true,
+ };
+ ConnectionListener advertising_connection_listener_;
+ ConnectionListener discovery_connection_listener_{
+ .initiated_cb = mock_discovery_connection_.initiated_cb.AsStdFunction(),
+ .accepted_cb = mock_discovery_connection_.accepted_cb.AsStdFunction(),
+ .rejected_cb = mock_discovery_connection_.rejected_cb.AsStdFunction(),
+ .disconnected_cb =
+ mock_discovery_connection_.disconnected_cb.AsStdFunction(),
+ .bandwidth_changed_cb =
+ mock_discovery_connection_.bandwidth_changed_cb.AsStdFunction(),
+ };
+ DiscoveryListener discovery_listener_{
+ .endpoint_found_cb = mock_discovery_.endpoint_found_cb.AsStdFunction(),
+ .endpoint_lost_cb = mock_discovery_.endpoint_lost_cb.AsStdFunction(),
+ };
+ PayloadListener payload_listener_{
+ .payload_cb = mock_discovery_payload_.payload_cb.AsStdFunction(),
+ .payload_progress_cb =
+ mock_discovery_payload_.payload_progress_cb.AsStdFunction(),
+ };
+ ConnectionOptions connection_options_;
+ AdvertisingOptions advertising_options_;
+ DiscoveryOptions discovery_options_;
+};
+
+TEST_P(ClientProxyTest, CanCancelEndpoint) {
+ FeatureFlags::Flags feature_flags = GetParam();
+ MediumEnvironment::Instance().SetFeatureFlags(feature_flags);
+
+ Endpoint advertising_endpoint =
+ StartAdvertising(&client1_, advertising_connection_listener_);
+ StartDiscovery(&client2_, discovery_listener_);
+ OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
+ OnDiscoveryConnectionInitiated(&client2_, advertising_endpoint);
+
+ EXPECT_FALSE(
+ client2_.GetCancellationFlag(advertising_endpoint.id)->Cancelled());
+
+ client2_.CancelEndpoint(advertising_endpoint.id);
+
+ // If FeatureFlag is disabled, Cancelled is false as no-op.
+ if (!feature_flags.enable_cancellation_flag) {
+ EXPECT_FALSE(
+ client2_.GetCancellationFlag(advertising_endpoint.id)->Cancelled());
+ } else {
+ // The Cancelled is always true as the default flag being returned.
+ EXPECT_TRUE(
+ client2_.GetCancellationFlag(advertising_endpoint.id)->Cancelled());
+ }
+}
+
+TEST_P(ClientProxyTest, CanCancelAllEndpoints) {
+ FeatureFlags::Flags feature_flags = GetParam();
+ MediumEnvironment::Instance().SetFeatureFlags(feature_flags);
+
+ Endpoint advertising_endpoint =
+ StartAdvertising(&client1_, advertising_connection_listener_);
+ StartDiscovery(&client2_, discovery_listener_);
+ OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
+ OnDiscoveryConnectionInitiated(&client2_, advertising_endpoint);
+
+ EXPECT_FALSE(
+ client2_.GetCancellationFlag(advertising_endpoint.id)->Cancelled());
+
+ client2_.CancelAllEndpoints();
+
+ // If FeatureFlag is disabled, Cancelled is false as no-op.
+ if (!feature_flags.enable_cancellation_flag) {
+ EXPECT_FALSE(
+ client2_.GetCancellationFlag(advertising_endpoint.id)->Cancelled());
+ } else {
+ // The Cancelled is always true as the default flag being returned.
+ EXPECT_TRUE(
+ client2_.GetCancellationFlag(advertising_endpoint.id)->Cancelled());
+ }
+}
+
+TEST_P(ClientProxyTest, CanCancelAllEndpointsWithDifferentEndpoint) {
+ FeatureFlags::Flags feature_flags = GetParam();
+ MediumEnvironment::Instance().SetFeatureFlags(feature_flags);
+
+ ConnectionListener advertising_connection_listener_2;
+ ConnectionListener advertising_connection_listener_3;
+ ClientProxy client3;
+
+ StartDiscovery(&client1_, discovery_listener_);
+ Endpoint advertising_endpoint_2 =
+ StartAdvertising(&client2_, advertising_connection_listener_2);
+ Endpoint advertising_endpoint_3 =
+ StartAdvertising(&client3, advertising_connection_listener_3);
+ OnDiscoveryEndpointFound(&client1_, advertising_endpoint_2);
+ OnDiscoveryConnectionInitiated(&client1_, advertising_endpoint_2);
+ OnDiscoveryEndpointFound(&client1_, advertising_endpoint_3);
+ OnDiscoveryConnectionInitiated(&client1_, advertising_endpoint_3);
+
+ // The CancellationFlag of endpoint_2 and endpoint_3 have been added. Default
+ // Cancelled is false.
+ EXPECT_FALSE(
+ client1_.GetCancellationFlag(advertising_endpoint_2.id)->Cancelled());
+ EXPECT_FALSE(
+ client1_.GetCancellationFlag(advertising_endpoint_3.id)->Cancelled());
+
+ client1_.CancelAllEndpoints();
+
+ if (!feature_flags.enable_cancellation_flag) {
+ // The CancellationFlag of endpoint_2 and endpoint_3 will not be removed
+ // since it is not added. The default flag returned as Cancelled being true,
+ // but Cancelled requested is false since the FeatureFlag is off.
+ EXPECT_FALSE(
+ client1_.GetCancellationFlag(advertising_endpoint_2.id)->Cancelled());
+ EXPECT_FALSE(
+ client1_.GetCancellationFlag(advertising_endpoint_3.id)->Cancelled());
+ } else {
+ // Expect the CancellationFlag of endpoint_2 and endpoint_3 has been
+ // removed. The Cancelled is always true as the default flag being returned.
+ EXPECT_TRUE(
+ client1_.GetCancellationFlag(advertising_endpoint_2.id)->Cancelled());
+ EXPECT_TRUE(
+ client1_.GetCancellationFlag(advertising_endpoint_3.id)->Cancelled());
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(ParametrisedClientProxyTest, ClientProxyTest,
+ ::testing::ValuesIn(kTestCases));
+
+TEST_F(ClientProxyTest, ConstructorDestructorWorks) { SUCCEED(); }
+
+TEST_F(ClientProxyTest, ClientIdIsUnique) {
+ EXPECT_NE(client1_.GetClientId(), client2_.GetClientId());
+}
+
+TEST_F(ClientProxyTest, GeneratedEndpointIdIsUnique) {
+ EXPECT_NE(client1_.GetLocalEndpointId(), client2_.GetLocalEndpointId());
+}
+
+TEST_F(ClientProxyTest, ResetClearsState) {
+ client1_.Reset();
+ EXPECT_FALSE(client1_.IsAdvertising());
+ EXPECT_FALSE(client1_.IsDiscovering());
+ EXPECT_TRUE(client1_.GetAdvertisingServiceId().empty());
+ EXPECT_TRUE(client1_.GetDiscoveryServiceId().empty());
+}
+
+TEST_F(ClientProxyTest, StartedAdvertisingChangesStateFromIdle) {
+ client1_.StartedAdvertising(service_id_, strategy_, {}, {});
+
+ EXPECT_TRUE(client1_.IsAdvertising());
+ EXPECT_FALSE(client1_.IsDiscovering());
+ EXPECT_EQ(client1_.GetAdvertisingServiceId(), service_id_);
+ EXPECT_TRUE(client1_.GetDiscoveryServiceId().empty());
+}
+
+TEST_F(ClientProxyTest, StartedDiscoveryChangesStateFromIdle) {
+ client1_.StartedDiscovery(service_id_, strategy_, {}, {});
+
+ EXPECT_FALSE(client1_.IsAdvertising());
+ EXPECT_TRUE(client1_.IsDiscovering());
+ EXPECT_TRUE(client1_.GetAdvertisingServiceId().empty());
+ EXPECT_EQ(client1_.GetDiscoveryServiceId(), service_id_);
+}
+
+TEST_F(ClientProxyTest, OnEndpointFoundFiresNotificationInDiscovery) {
+ Endpoint advertising_endpoint =
+ StartAdvertising(&client1_, advertising_connection_listener_);
+ StartDiscovery(&client2_, discovery_listener_);
+ OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
+}
+
+TEST_F(ClientProxyTest, OnEndpointLostFiresNotificationInDiscovery) {
+ Endpoint advertising_endpoint =
+ StartAdvertising(&client1_, advertising_connection_listener_);
+ StartDiscovery(&client2_, discovery_listener_);
+ OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
+ OnDiscoveryEndpointLost(&client2_, advertising_endpoint);
+}
+
+TEST_F(ClientProxyTest, OnConnectionInitiatedFiresNotificationInDiscovery) {
+ Endpoint advertising_endpoint =
+ StartAdvertising(&client1_, advertising_connection_listener_);
+ StartDiscovery(&client2_, discovery_listener_);
+ OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
+ OnDiscoveryConnectionInitiated(&client2_, advertising_endpoint);
+}
+
+TEST_F(ClientProxyTest, OnBandwidthChangedFiresNotificationInDiscovery) {
+ Endpoint advertising_endpoint =
+ StartAdvertising(&client1_, advertising_connection_listener_);
+ StartDiscovery(&client2_, discovery_listener_);
+ OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
+ OnDiscoveryConnectionInitiated(&client2_, advertising_endpoint);
+ OnDiscoveryConnectionLocalAccepted(&client2_, advertising_endpoint);
+ OnDiscoveryConnectionRemoteAccepted(&client2_, advertising_endpoint);
+ OnDiscoveryConnectionAccepted(&client2_, advertising_endpoint);
+ OnDiscoveryBandwidthChanged(&client2_, advertising_endpoint);
+}
+
+TEST_F(ClientProxyTest, OnDisconnectedFiresNotificationInDiscovery) {
+ Endpoint advertising_endpoint =
+ StartAdvertising(&client1_, advertising_connection_listener_);
+ StartDiscovery(&client2_, discovery_listener_);
+ OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
+ OnDiscoveryConnectionInitiated(&client2_, advertising_endpoint);
+ OnDiscoveryConnectionDisconnected(&client2_, advertising_endpoint);
+}
+
+TEST_F(ClientProxyTest, LocalEndpointAcceptedConnectionChangesState) {
+ Endpoint advertising_endpoint =
+ StartAdvertising(&client1_, advertising_connection_listener_);
+ StartDiscovery(&client2_, discovery_listener_);
+ OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
+ OnDiscoveryConnectionInitiated(&client2_, advertising_endpoint);
+ OnDiscoveryConnectionLocalAccepted(&client2_, advertising_endpoint);
+}
+
+TEST_F(ClientProxyTest, LocalEndpointRejectedConnectionChangesState) {
+ Endpoint advertising_endpoint =
+ StartAdvertising(&client1_, advertising_connection_listener_);
+ StartDiscovery(&client2_, discovery_listener_);
+ OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
+ OnDiscoveryConnectionInitiated(&client2_, advertising_endpoint);
+ OnDiscoveryConnectionLocalRejected(&client2_, advertising_endpoint);
+}
+
+TEST_F(ClientProxyTest, RemoteEndpointAcceptedConnectionChangesState) {
+ Endpoint advertising_endpoint =
+ StartAdvertising(&client1_, advertising_connection_listener_);
+ StartDiscovery(&client2_, discovery_listener_);
+ OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
+ OnDiscoveryConnectionInitiated(&client2_, advertising_endpoint);
+ OnDiscoveryConnectionRemoteAccepted(&client2_, advertising_endpoint);
+}
+
+TEST_F(ClientProxyTest, RemoteEndpointRejectedConnectionChangesState) {
+ Endpoint advertising_endpoint =
+ StartAdvertising(&client1_, advertising_connection_listener_);
+ StartDiscovery(&client2_, discovery_listener_);
+ OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
+ OnDiscoveryConnectionInitiated(&client2_, advertising_endpoint);
+ OnDiscoveryConnectionRemoteRejected(&client2_, advertising_endpoint);
+}
+
+TEST_F(ClientProxyTest, OnPayloadChangesState) {
+ Endpoint advertising_endpoint =
+ StartAdvertising(&client1_, advertising_connection_listener_);
+ StartDiscovery(&client2_, discovery_listener_);
+ OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
+ OnDiscoveryConnectionInitiated(&client2_, advertising_endpoint);
+ OnDiscoveryConnectionLocalAccepted(&client2_, advertising_endpoint);
+ OnDiscoveryConnectionRemoteAccepted(&client2_, advertising_endpoint);
+ OnDiscoveryConnectionAccepted(&client2_, advertising_endpoint);
+ OnPayload(&client2_, advertising_endpoint);
+}
+
+TEST_F(ClientProxyTest, OnPayloadProgressChangesState) {
+ Endpoint advertising_endpoint =
+ StartAdvertising(&client1_, advertising_connection_listener_);
+ StartDiscovery(&client2_, discovery_listener_);
+ OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
+ OnDiscoveryConnectionInitiated(&client2_, advertising_endpoint);
+ OnDiscoveryConnectionLocalAccepted(&client2_, advertising_endpoint);
+ OnDiscoveryConnectionRemoteAccepted(&client2_, advertising_endpoint);
+ OnDiscoveryConnectionAccepted(&client2_, advertising_endpoint);
+ OnPayloadProgress(&client2_, advertising_endpoint);
+}
+
+TEST_F(ClientProxyTest,
+ EndpointIdCacheWhenHighVizAdvertisementAgainImmediately) {
+ BooleanMediumSelector booleanMediumSelector;
+ booleanMediumSelector.bluetooth = true;
+
+ AdvertisingOptions advertising_options{
+ {
+ strategy_,
+ booleanMediumSelector,
+ },
+ false, // auto_upgrade_bandwidth
+ false, // enforce_topology_constraints
+ false, // low_power
+ };
+
+ Endpoint advertising_endpoint_1 = StartAdvertising(
+ &client1_, advertising_connection_listener_, advertising_options);
+
+ StopAdvertising(&client1_);
+
+ // Advertise immediately.
+ Endpoint advertising_endpoint_2 = StartAdvertising(
+ &client1_, advertising_connection_listener_, advertising_options);
+
+ EXPECT_EQ(advertising_endpoint_1.id, advertising_endpoint_2.id);
+}
+
+TEST_F(ClientProxyTest,
+ EndpointIdRotateWhenHighVizAdvertisementAgainForAWhile) {
+ BooleanMediumSelector booleanMediumSelector;
+ booleanMediumSelector.bluetooth = true;
+
+ AdvertisingOptions advertising_options{
+ {
+ strategy_,
+ booleanMediumSelector,
+ },
+ false, // auto_upgrade_bandwidth
+ false, // enforce_topology_constraints
+ false, // low_power
+ };
+
+ Endpoint advertising_endpoint_1 = StartAdvertising(
+ &client1_, advertising_connection_listener_, advertising_options);
+
+ StopAdvertising(&client1_);
+
+ // Wait to expire and then advertise.
+ absl::SleepFor(ClientProxy::kHighPowerAdvertisementEndpointIdCacheTimeout +
+ absl::Milliseconds(100));
+ Endpoint advertising_endpoint_2 = StartAdvertising(
+ &client1_, advertising_connection_listener_, advertising_options);
+
+ EXPECT_NE(advertising_endpoint_1.id, advertising_endpoint_2.id);
+}
+
+TEST_F(ClientProxyTest,
+ EndpointIdRotateWhenLowVizAdvertisementAfterHighVizAdvertisement) {
+ BooleanMediumSelector booleanMediumSelector;
+ booleanMediumSelector.bluetooth = true;
+
+ AdvertisingOptions high_viz_advertising_options{
+ {
+ strategy_,
+ booleanMediumSelector,
+ },
+ false, // auto_upgrade_bandwidth
+ false, // enforce_topology_constraints
+ false, // low_power
+ };
+ Endpoint advertising_endpoint_1 =
+ StartAdvertising(&client1_, advertising_connection_listener_,
+ high_viz_advertising_options);
+
+ StopAdvertising(&client1_);
+
+ AdvertisingOptions low_viz_advertising_options{
+ {
+ strategy_,
+ booleanMediumSelector,
+ },
+ false, // auto_upgrade_bandwidth
+ false, // enforce_topology_constraints
+ true, // low_power
+ };
+
+ Endpoint advertising_endpoint_2 = StartAdvertising(
+ &client1_, advertising_connection_listener_, low_viz_advertising_options);
+
+ EXPECT_NE(advertising_endpoint_1.id, advertising_endpoint_2.id);
+}
+
+// Tests endpoint_id rotates when discover.
+TEST_F(ClientProxyTest, EndpointIdRotateWhenStartDiscovery) {
+ BooleanMediumSelector booleanMediumSelector;
+ booleanMediumSelector.bluetooth = true;
+
+ AdvertisingOptions advertising_options{
+ {
+ strategy_,
+ booleanMediumSelector,
+ },
+ false, // auto_upgrade_bandwidth
+ false, // enforce_topology_constraints
+ false, // low_power
+ };
+
+ Endpoint advertising_endpoint_1 = StartAdvertising(
+ &client1_, advertising_connection_listener_, advertising_options);
+
+ StopAdvertising(&client1_);
+ StartDiscovery(&client1_, discovery_listener_);
+
+ Endpoint advertising_endpoint_2 = StartAdvertising(
+ &client1_, advertising_connection_listener_, advertising_options);
+
+ EXPECT_NE(advertising_endpoint_1.id, advertising_endpoint_2.id);
+}
+
+// Tests the low visibility mode with bluetooth disabled advertisment.
+TEST_F(ClientProxyTest,
+ EndpointIdRotateWhenLowVizAdvertisementWithBluetoothDisabled) {
+ BooleanMediumSelector booleanMediumSelector;
+ booleanMediumSelector.bluetooth = false;
+
+ AdvertisingOptions advertising_options{
+ {
+ strategy_,
+ booleanMediumSelector,
+ },
+ false, // auto_upgrade_bandwidth
+ false, // enforce_topology_constraints
+ false, // low_power
+ };
+
+ Endpoint advertising_endpoint_1 = StartAdvertising(
+ &client1_, advertising_connection_listener_, advertising_options);
+
+ StopAdvertising(&client1_);
+
+ Endpoint advertising_endpoint_2 = StartAdvertising(
+ &client1_, advertising_connection_listener_, advertising_options);
+
+ EXPECT_NE(advertising_endpoint_1.id, advertising_endpoint_2.id);
+}
+
+// Tests the low visibility mode with low power advertisment.
+TEST_F(ClientProxyTest, EndpointIdRotateWhenLowVizAdvertisementWithLowPower) {
+ BooleanMediumSelector booleanMediumSelector;
+ booleanMediumSelector.bluetooth = false;
+
+ AdvertisingOptions advertising_options{
+ {
+ strategy_,
+ booleanMediumSelector,
+ },
+ false, // auto_upgrade_bandwidth
+ false, // enforce_topology_constraints
+ true, // low_power
+ };
+ Endpoint advertising_endpoint_1 = StartAdvertising(
+ &client1_, advertising_connection_listener_, advertising_options);
+
+ StopAdvertising(&client1_);
+
+ Endpoint advertising_endpoint_2 = StartAdvertising(
+ &client1_, advertising_connection_listener_, advertising_options);
+
+ EXPECT_NE(advertising_endpoint_1.id, advertising_endpoint_2.id);
+}
+
+} // namespace
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/encryption_runner.cc b/chromium/third_party/nearby/src/connections/implementation/encryption_runner.cc
new file mode 100644
index 00000000000..68e306f79e1
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/encryption_runner.cc
@@ -0,0 +1,389 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/encryption_runner.h"
+
+#include <cinttypes>
+#include <cstdint>
+#include <memory>
+
+#include "securegcm/ukey2_handshake.h"
+#include "absl/strings/ascii.h"
+#include "absl/time/clock.h"
+#include "absl/time/time.h"
+#include "internal/platform/base64_utils.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/cancelable_alarm.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+
+constexpr absl::Duration kTimeout = absl::Seconds(15);
+constexpr std::int32_t kMaxUkey2VerificationStringLength = 32;
+constexpr std::int32_t kTokenLength = 5;
+constexpr securegcm::UKey2Handshake::HandshakeCipher kCipher =
+ securegcm::UKey2Handshake::HandshakeCipher::P256_SHA512;
+
+// Transforms a raw UKEY2 token (which is a random ByteArray that's
+// kMaxUkey2VerificationStringLength long) into a kTokenLength string that only
+// uses [A-Z], [0-9], '_', '-' for each character.
+std::string ToHumanReadableString(const ByteArray& token) {
+ std::string result = Base64Utils::Encode(token).substr(0, kTokenLength);
+ absl::AsciiStrToUpper(&result);
+ return result;
+}
+
+bool HandleEncryptionSuccess(const std::string& endpoint_id,
+ std::unique_ptr<securegcm::UKey2Handshake> ukey2,
+ const EncryptionRunner::ResultListener& listener) {
+ std::unique_ptr<std::string> verification_string =
+ ukey2->GetVerificationString(kMaxUkey2VerificationStringLength);
+ if (verification_string == nullptr) {
+ return false;
+ }
+
+ ByteArray raw_authentication_token(*verification_string);
+
+ listener.on_success_cb(endpoint_id, std::move(ukey2),
+ ToHumanReadableString(raw_authentication_token),
+ raw_authentication_token);
+
+ return true;
+}
+
+void CancelableAlarmRunnable(ClientProxy* client,
+ const std::string& endpoint_id,
+ EndpointChannel* endpoint_channel) {
+ NEARBY_LOGS(INFO) << "Timing out encryption for client "
+ << client->GetClientId()
+ << " to endpoint_id=" << endpoint_id << " after "
+ << absl::FormatDuration(kTimeout);
+ endpoint_channel->Close();
+}
+
+class ServerRunnable final {
+ public:
+ ServerRunnable(ClientProxy* client, ScheduledExecutor* alarm_executor,
+ const std::string& endpoint_id, EndpointChannel* channel,
+ EncryptionRunner::ResultListener&& listener)
+ : client_(client),
+ alarm_executor_(alarm_executor),
+ endpoint_id_(endpoint_id),
+ channel_(channel),
+ listener_(std::move(listener)) {}
+
+ void operator()() const {
+ CancelableAlarm timeout_alarm(
+ "EncryptionRunner.StartServer() timeout",
+ [this]() { CancelableAlarmRunnable(client_, endpoint_id_, channel_); },
+ kTimeout, alarm_executor_);
+
+ std::unique_ptr<securegcm::UKey2Handshake> server =
+ securegcm::UKey2Handshake::ForResponder(kCipher);
+ if (server == nullptr) {
+ LogException();
+ HandleHandshakeOrIoException(&timeout_alarm);
+ return;
+ }
+
+ // Message 1 (Client Init)
+ ExceptionOr<ByteArray> client_init = channel_->Read();
+ if (!client_init.ok()) {
+ LogException();
+ HandleHandshakeOrIoException(&timeout_alarm);
+ return;
+ }
+
+ securegcm::UKey2Handshake::ParseResult parse_result =
+ server->ParseHandshakeMessage(std::string(client_init.result()));
+
+ // Java code throws a HandshakeException / AlertException.
+ if (!parse_result.success) {
+ LogException();
+ if (parse_result.alert_to_send != nullptr) {
+ HandleAlertException(parse_result);
+ }
+ HandleHandshakeOrIoException(&timeout_alarm);
+ return;
+ }
+
+ NEARBY_LOGS(INFO)
+ << "In StartServer(), read UKEY2 Message 1 from endpoint(id="
+ << endpoint_id_ << ").";
+
+ // Message 2 (Server Init)
+ std::unique_ptr<std::string> server_init =
+ server->GetNextHandshakeMessage();
+
+ // Java code throws a HandshakeException.
+ if (server_init == nullptr) {
+ LogException();
+ HandleHandshakeOrIoException(&timeout_alarm);
+ return;
+ }
+
+ Exception write_exception =
+ channel_->Write(ByteArray(std::move(*server_init)));
+ if (!write_exception.Ok()) {
+ LogException();
+ HandleHandshakeOrIoException(&timeout_alarm);
+ return;
+ }
+
+ NEARBY_LOGS(INFO)
+ << "In StartServer(), wrote UKEY2 Message 2 to endpoint(id="
+ << endpoint_id_ << ").";
+
+ // Message 3 (Client Finish)
+ ExceptionOr<ByteArray> client_finish = channel_->Read();
+
+ if (!client_finish.ok()) {
+ LogException();
+ HandleHandshakeOrIoException(&timeout_alarm);
+ return;
+ }
+
+ parse_result =
+ server->ParseHandshakeMessage(std::string(client_finish.result()));
+
+ // Java code throws an AlertException or a HandshakeException.
+ if (!parse_result.success) {
+ LogException();
+ if (parse_result.alert_to_send != nullptr) {
+ HandleAlertException(parse_result);
+ }
+ HandleHandshakeOrIoException(&timeout_alarm);
+ return;
+ }
+
+ NEARBY_LOGS(INFO)
+ << "In StartServer(), read UKEY2 Message 3 from endpoint(id="
+ << endpoint_id_ << ").";
+
+ timeout_alarm.Cancel();
+
+ if (!HandleEncryptionSuccess(endpoint_id_, std::move(server), listener_)) {
+ LogException();
+ HandleHandshakeOrIoException(&timeout_alarm);
+ return;
+ }
+ }
+
+ private:
+ void LogException() const {
+ NEARBY_LOGS(ERROR) << "In StartServer(), UKEY2 failed with endpoint(id="
+ << endpoint_id_ << ").";
+ }
+
+ void HandleHandshakeOrIoException(CancelableAlarm* timeout_alarm) const {
+ timeout_alarm->Cancel();
+ listener_.on_failure_cb(endpoint_id_, channel_);
+ }
+
+ void HandleAlertException(
+ const securegcm::UKey2Handshake::ParseResult& parse_result) const {
+ Exception write_exception =
+ channel_->Write(ByteArray(*parse_result.alert_to_send));
+ if (!write_exception.Ok()) {
+ NEARBY_LOGS(WARNING)
+ << "In StartServer(), client " << client_->GetClientId()
+ << " failed to pass the alert error message to endpoint(id="
+ << endpoint_id_ << ").";
+ }
+ }
+
+ ClientProxy* client_;
+ ScheduledExecutor* alarm_executor_;
+ const std::string endpoint_id_;
+ EndpointChannel* channel_;
+ EncryptionRunner::ResultListener listener_;
+};
+
+class ClientRunnable final {
+ public:
+ ClientRunnable(ClientProxy* client, ScheduledExecutor* alarm_executor,
+ const std::string& endpoint_id, EndpointChannel* channel,
+ EncryptionRunner::ResultListener&& listener)
+ : client_(client),
+ alarm_executor_(alarm_executor),
+ endpoint_id_(endpoint_id),
+ channel_(channel),
+ listener_(std::move(listener)) {}
+
+ void operator()() const {
+ CancelableAlarm timeout_alarm(
+ "EncryptionRunner.StartClient() timeout",
+ [this]() { CancelableAlarmRunnable(client_, endpoint_id_, channel_); },
+ kTimeout, alarm_executor_);
+
+ std::unique_ptr<securegcm::UKey2Handshake> crypto =
+ securegcm::UKey2Handshake::ForInitiator(kCipher);
+
+ // Java code throws a HandshakeException.
+ if (crypto == nullptr) {
+ LogException();
+ HandleHandshakeOrIoException(&timeout_alarm);
+ return;
+ }
+
+ // Message 1 (Client Init)
+ std::unique_ptr<std::string> client_init =
+ crypto->GetNextHandshakeMessage();
+
+ // Java code throws a HandshakeException.
+ if (client_init == nullptr) {
+ LogException();
+ HandleHandshakeOrIoException(&timeout_alarm);
+ return;
+ }
+
+ Exception write_init_exception = channel_->Write(ByteArray(*client_init));
+ if (!write_init_exception.Ok()) {
+ LogException();
+ HandleHandshakeOrIoException(&timeout_alarm);
+ return;
+ }
+
+ NEARBY_LOGS(INFO)
+ << "In StartClient(), wrote UKEY2 Message 1 to endpoint(id="
+ << endpoint_id_ << ").";
+
+ // Message 2 (Server Init)
+ ExceptionOr<ByteArray> server_init = channel_->Read();
+
+ if (!server_init.ok()) {
+ LogException();
+ HandleHandshakeOrIoException(&timeout_alarm);
+ return;
+ }
+
+ securegcm::UKey2Handshake::ParseResult parse_result =
+ crypto->ParseHandshakeMessage(std::string(server_init.result()));
+
+ // Java code throws an AlertException or a HandshakeException.
+ if (!parse_result.success) {
+ LogException();
+ if (parse_result.alert_to_send != nullptr) {
+ HandleAlertException(parse_result);
+ }
+ HandleHandshakeOrIoException(&timeout_alarm);
+ return;
+ }
+
+ NEARBY_LOGS(INFO)
+ << "In StartClient(), read UKEY2 Message 2 from endpoint(id="
+ << endpoint_id_ << ").";
+
+ // Message 3 (Client Finish)
+ std::unique_ptr<std::string> client_finish =
+ crypto->GetNextHandshakeMessage();
+
+ // Java code throws a HandshakeException.
+ if (client_finish == nullptr) {
+ LogException();
+ HandleHandshakeOrIoException(&timeout_alarm);
+ return;
+ }
+
+ Exception write_finish_exception =
+ channel_->Write(ByteArray(*client_finish));
+ if (!write_finish_exception.Ok()) {
+ LogException();
+ HandleHandshakeOrIoException(&timeout_alarm);
+ return;
+ }
+
+ NEARBY_LOGS(INFO)
+ << "In StartClient(), wrote UKEY2 Message 3 to endpoint(id="
+ << endpoint_id_ << ").";
+
+ timeout_alarm.Cancel();
+
+ if (!HandleEncryptionSuccess(endpoint_id_, std::move(crypto), listener_)) {
+ LogException();
+ HandleHandshakeOrIoException(&timeout_alarm);
+ return;
+ }
+ }
+
+ private:
+ void LogException() const {
+ NEARBY_LOGS(ERROR) << "In StartClient(), UKEY2 failed with endpoint(id="
+ << endpoint_id_ << ").";
+ }
+
+ void HandleHandshakeOrIoException(CancelableAlarm* timeout_alarm) const {
+ timeout_alarm->Cancel();
+ listener_.on_failure_cb(endpoint_id_, channel_);
+ }
+
+ void HandleAlertException(
+ const securegcm::UKey2Handshake::ParseResult& parse_result) const {
+ Exception write_exception =
+ channel_->Write(ByteArray(*parse_result.alert_to_send));
+ if (!write_exception.Ok()) {
+ NEARBY_LOGS(WARNING)
+ << "In StartClient(), client " << client_->GetClientId()
+ << " failed to pass the alert error message to endpoint(id="
+ << endpoint_id_ << ").";
+ }
+ }
+
+ ClientProxy* client_;
+ ScheduledExecutor* alarm_executor_;
+ const std::string endpoint_id_;
+ EndpointChannel* channel_;
+ EncryptionRunner::ResultListener listener_;
+};
+
+} // namespace
+
+EncryptionRunner::~EncryptionRunner() {
+ // Stop all the ongoing Runnables (as gracefully as possible).
+ client_executor_.Shutdown();
+ server_executor_.Shutdown();
+ alarm_executor_.Shutdown();
+}
+
+void EncryptionRunner::StartServer(
+ ClientProxy* client, const std::string& endpoint_id,
+ EndpointChannel* endpoint_channel,
+ EncryptionRunner::ResultListener&& listener) {
+ server_executor_.Execute(
+ "encryption-server",
+ [runnable{ServerRunnable(client, &alarm_executor_, endpoint_id,
+ endpoint_channel, std::move(listener))}]() {
+ runnable();
+ });
+}
+
+void EncryptionRunner::StartClient(
+ ClientProxy* client, const std::string& endpoint_id,
+ EndpointChannel* endpoint_channel,
+ EncryptionRunner::ResultListener&& listener) {
+ client_executor_.Execute(
+ "encryption-client",
+ [runnable{ClientRunnable(client, &alarm_executor_, endpoint_id,
+ endpoint_channel, std::move(listener))}]() {
+ runnable();
+ });
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/encryption_runner.h b/chromium/third_party/nearby/src/connections/implementation/encryption_runner.h
new file mode 100644
index 00000000000..4262f7ff772
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/encryption_runner.h
@@ -0,0 +1,86 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_ENCRYPTION_RUNNER_H_
+#define CORE_INTERNAL_ENCRYPTION_RUNNER_H_
+
+#include <string>
+
+#include "securegcm/ukey2_handshake.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/endpoint_channel.h"
+#include "connections/listeners.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/scheduled_executor.h"
+#include "internal/platform/single_thread_executor.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Encrypts a connection over UKEY2.
+//
+// NOTE: Stalled EndpointChannels will be disconnected after kTimeout.
+// This is to prevent unverified endpoints from maintaining an
+// indefinite connection to us.
+class EncryptionRunner {
+ public:
+ EncryptionRunner() = default;
+ ~EncryptionRunner();
+
+ struct ResultListener {
+ // @EncryptionRunnerThread
+ std::function<void(const std::string& endpoint_id,
+ std::unique_ptr<securegcm::UKey2Handshake> ukey2,
+ const std::string& auth_token,
+ const ByteArray& raw_auth_token)>
+ on_success_cb =
+ DefaultCallback<const std::string&,
+ std::unique_ptr<securegcm::UKey2Handshake>,
+ const std::string&, const ByteArray&>();
+
+ // Encryption has failed. The remote_endpoint_id and channel are given so
+ // that any pending state can be cleaned up.
+ //
+ // We return the EndpointChannel because, at this stage, simultaneous
+ // connections are a possibility. Use this channel to verify that the state
+ // you're cleaning up is for this EndpointChannel, and not state for another
+ // channel to the same endpoint.
+ //
+ // @EncryptionRunnerThread
+ std::function<void(const std::string& endpoint_id,
+ EndpointChannel* channel)>
+ on_failure_cb = DefaultCallback<const std::string&, EndpointChannel*>();
+ };
+
+ // @AnyThread
+ void StartServer(ClientProxy* client, const std::string& endpoint_id,
+ EndpointChannel* endpoint_channel,
+ ResultListener&& result_listener);
+ // @AnyThread
+ void StartClient(ClientProxy* client, const std::string& endpoint_id,
+ EndpointChannel* endpoint_channel,
+ ResultListener&& result_listener);
+
+ private:
+ ScheduledExecutor alarm_executor_;
+ SingleThreadExecutor server_executor_;
+ SingleThreadExecutor client_executor_;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_ENCRYPTION_RUNNER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/encryption_runner_test.cc b/chromium/third_party/nearby/src/connections/implementation/encryption_runner_test.cc
new file mode 100644
index 00000000000..c2440f36621
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/encryption_runner_test.cc
@@ -0,0 +1,160 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/encryption_runner.h"
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "absl/time/clock.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/endpoint_channel.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/pipe.h"
+#include "internal/platform/system_clock.h"
+#include "proto/connections_enums.pb.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+
+using ::location::nearby::proto::connections::Medium;
+
+class FakeEndpointChannel : public EndpointChannel {
+ public:
+ FakeEndpointChannel(InputStream* in, OutputStream* out)
+ : in_(in), out_(out) {}
+ ExceptionOr<ByteArray> Read() override {
+ read_timestamp_ = SystemClock::ElapsedRealtime();
+ return in_ ? in_->Read(Pipe::kChunkSize)
+ : ExceptionOr<ByteArray>{Exception::kIo};
+ }
+ Exception Write(const ByteArray& data) override {
+ write_timestamp_ = SystemClock::ElapsedRealtime();
+ return out_ ? out_->Write(data) : Exception{Exception::kIo};
+ }
+ void Close() override {
+ if (in_) in_->Close();
+ if (out_) out_->Close();
+ }
+ void Close(proto::connections::DisconnectionReason reason) override {
+ Close();
+ }
+ proto::connections::ConnectionTechnology GetTechnology() const override {
+ return proto::connections::ConnectionTechnology::
+ CONNECTION_TECHNOLOGY_BLE_GATT;
+ }
+ proto::connections::ConnectionBand GetBand() const override {
+ return proto::connections::ConnectionBand::CONNECTION_BAND_CELLULAR_BAND_2G;
+ }
+ int GetFrequency() const override { return 0; }
+ int GetTryCount() const override { return 0; }
+ std::string GetType() const override { return "fake-channel-type"; }
+ std::string GetName() const override { return "fake-channel"; }
+ Medium GetMedium() const override { return Medium::BLE; }
+ int GetMaxTransmitPacketSize() const override { return 512; }
+ void EnableEncryption(std::shared_ptr<EncryptionContext> context) override {}
+ void DisableEncryption() override {}
+ bool IsPaused() const override { return false; }
+ void Pause() override {}
+ void Resume() override {}
+ absl::Time GetLastReadTimestamp() const override { return read_timestamp_; }
+ absl::Time GetLastWriteTimestamp() const override { return write_timestamp_; }
+ void SetAnalyticsRecorder(analytics::AnalyticsRecorder* analytics_recorder,
+ const std::string& endpoint_id) override {}
+
+ private:
+ InputStream* in_ = nullptr;
+ OutputStream* out_ = nullptr;
+ absl::Time read_timestamp_ = absl::InfinitePast();
+ absl::Time write_timestamp_ = absl::InfinitePast();
+};
+
+struct User {
+ User(Pipe* reader, Pipe* writer)
+ : channel(&reader->GetInputStream(), &writer->GetOutputStream()) {}
+
+ FakeEndpointChannel channel;
+ EncryptionRunner crypto;
+ ClientProxy client;
+};
+
+struct Response {
+ enum class Status {
+ kUnknown = 0,
+ kDone = 1,
+ kFailed = 2,
+ };
+
+ CountDownLatch latch{2};
+ Status server_status = Status::kUnknown;
+ Status client_status = Status::kUnknown;
+};
+
+TEST(EncryptionRunnerTest, ConstructorDestructorWorks) { EncryptionRunner enc; }
+
+TEST(EncryptionRunnerTest, ReadWrite) {
+ Pipe from_a_to_b;
+ Pipe from_b_to_a;
+ User user_a(/*reader=*/&from_b_to_a, /*writer=*/&from_a_to_b);
+ User user_b(/*reader=*/&from_a_to_b, /*writer=*/&from_b_to_a);
+ Response response;
+
+ user_a.crypto.StartServer(
+ &user_a.client, "endpoint_id", &user_a.channel,
+ {
+ .on_success_cb =
+ [&response](const std::string& endpoint_id,
+ std::unique_ptr<securegcm::UKey2Handshake> ukey2,
+ const std::string& auth_token,
+ const ByteArray& raw_auth_token) {
+ response.server_status = Response::Status::kDone;
+ response.latch.CountDown();
+ },
+ .on_failure_cb =
+ [&response](const std::string& endpoint_id,
+ EndpointChannel* channel) {
+ response.server_status = Response::Status::kFailed;
+ response.latch.CountDown();
+ },
+ });
+ user_b.crypto.StartClient(
+ &user_b.client, "endpoint_id", &user_b.channel,
+ {
+ .on_success_cb =
+ [&response](const std::string& endpoint_id,
+ std::unique_ptr<securegcm::UKey2Handshake> ukey2,
+ const std::string& auth_token,
+ const ByteArray& raw_auth_token) {
+ response.client_status = Response::Status::kDone;
+ response.latch.CountDown();
+ },
+ .on_failure_cb =
+ [&response](const std::string& endpoint_id,
+ EndpointChannel* channel) {
+ response.client_status = Response::Status::kFailed;
+ response.latch.CountDown();
+ },
+ });
+ EXPECT_TRUE(response.latch.Await(absl::Milliseconds(5000)).result());
+ EXPECT_EQ(response.server_status, Response::Status::kDone);
+ EXPECT_EQ(response.client_status, Response::Status::kDone);
+}
+
+} // namespace
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/endpoint_channel.h b/chromium/third_party/nearby/src/connections/implementation/endpoint_channel.h
new file mode 100644
index 00000000000..7d73e7b2c3a
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/endpoint_channel.h
@@ -0,0 +1,119 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_ENDPOINT_CHANNEL_H_
+#define CORE_INTERNAL_ENDPOINT_CHANNEL_H_
+
+#include <cstdint>
+#include <string>
+
+#include "securegcm/d2d_connection_context_v1.h"
+#include "absl/time/clock.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/mutex.h"
+#include "internal/analytics/analytics_recorder.h"
+#include "proto/connections_enums.pb.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+class EndpointChannel {
+ public:
+ virtual ~EndpointChannel() = default;
+
+ using EncryptionContext = ::securegcm::D2DConnectionContextV1;
+
+ virtual ExceptionOr<ByteArray>
+ Read() = 0; // throws Exception::IO, Exception::INTERRUPTED
+
+ virtual Exception Write(const ByteArray& data) = 0; // throws Exception::IO
+
+ // Closes this EndpointChannel, without tracking the closure in analytics.
+ virtual void Close() = 0;
+
+ // Closes this EndpointChannel and records the closure with the given reason.
+ virtual void Close(proto::connections::DisconnectionReason reason) = 0;
+
+ // Returns a one-word type descriptor for the concrete EndpointChannel
+ // implementation that can be used in log messages; eg: BLUETOOTH, BLE, WIFI.
+ virtual std::string GetType() const = 0;
+
+ // Returns the name of the EndpointChannel.
+ virtual std::string GetName() const = 0;
+
+ // Returns the analytics enum representing the medium of this EndpointChannel.
+ virtual proto::connections::Medium GetMedium() const = 0;
+
+ // Returns the used BLE or WiFi technology of this EndpointChannel.
+ virtual proto::connections::ConnectionTechnology GetTechnology() const = 0;
+
+ // Returns the used wifi band of this EndpointChannel.
+ virtual proto::connections::ConnectionBand GetBand() const = 0;
+
+ // Returns the used wifi frequency of this EndpointChannel.
+ virtual int GetFrequency() const = 0;
+
+ // Returns the try counts of this EndpointChannel.
+ virtual int GetTryCount() const = 0;
+
+ // Returns the maximum supported transmit packet size(MTU) for the underlying
+ // transport.
+ virtual int GetMaxTransmitPacketSize() const = 0;
+
+ // Enables encryption on the EndpointChannel.
+ virtual void EnableEncryption(std::shared_ptr<EncryptionContext> context) = 0;
+
+ // Disables encryption on the EndpointChannel.
+ virtual void DisableEncryption() = 0;
+
+ // True if the EndpointChannel is currently pausing all writes.
+ virtual bool IsPaused() const = 0;
+
+ // Pauses all writes on this EndpointChannel until resume() is called.
+ virtual void Pause() = 0;
+
+ // Resumes any writes on this EndpointChannel that were suspended when pause()
+ // was called.
+ virtual void Resume() = 0;
+
+ // Returns the timestamp of the last read from this endpoint, or -1 if no
+ // reads have occurred.
+ virtual absl::Time GetLastReadTimestamp() const = 0;
+
+ // Returns the timestamp of the last write to this endpoint, or -1 if no
+ // writes have occurred.
+ virtual absl::Time GetLastWriteTimestamp() const = 0;
+
+ // Sets the AnalyticsRecorder instance for analytics.
+ virtual void SetAnalyticsRecorder(
+ analytics::AnalyticsRecorder* analytics_recorder,
+ const std::string& endpoint_id) = 0;
+};
+
+inline bool operator==(const EndpointChannel& lhs, const EndpointChannel& rhs) {
+ return (lhs.GetType() == rhs.GetType()) && (lhs.GetName() == rhs.GetName()) &&
+ (lhs.GetMedium() == rhs.GetMedium());
+}
+
+inline bool operator!=(const EndpointChannel& lhs, const EndpointChannel& rhs) {
+ return !(lhs == rhs);
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_ENDPOINT_CHANNEL_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/endpoint_channel_manager.cc b/chromium/third_party/nearby/src/connections/implementation/endpoint_channel_manager.cc
new file mode 100644
index 00000000000..ece10ebc4e8
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/endpoint_channel_manager.cc
@@ -0,0 +1,187 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/endpoint_channel_manager.h"
+
+#include <memory>
+#include <string>
+#include <utility>
+
+#include "absl/time/time.h"
+#include "connections/implementation/proto/offline_wire_formats.pb.h"
+#include "connections/implementation/offline_frames.h"
+#include "internal/platform/feature_flags.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/mutex.h"
+#include "internal/platform/mutex_lock.h"
+#include "internal/platform/system_clock.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+namespace {
+const absl::Duration kDataTransferDelay = absl::Milliseconds(500);
+}
+
+EndpointChannelManager::~EndpointChannelManager() {
+ NEARBY_LOG(INFO, "Initiating shutdown of EndpointChannelManager.");
+ MutexLock lock(&mutex_);
+ channel_state_.DestroyAll();
+ NEARBY_LOG(INFO, "EndpointChannelManager has shut down.");
+}
+
+void EndpointChannelManager::RegisterChannelForEndpoint(
+ ClientProxy* client, const std::string& endpoint_id,
+ std::unique_ptr<EndpointChannel> channel) {
+ MutexLock lock(&mutex_);
+
+ NEARBY_LOGS(INFO) << "EndpointChannelManager registered channel of type "
+ << channel->GetType() << " to endpoint " << endpoint_id;
+ SetActiveEndpointChannel(client, endpoint_id, std::move(channel));
+
+ NEARBY_LOG(INFO, "Registered channel: id=%s", endpoint_id.c_str());
+}
+
+void EndpointChannelManager::ReplaceChannelForEndpoint(
+ ClientProxy* client, const std::string& endpoint_id,
+ std::unique_ptr<EndpointChannel> channel) {
+ MutexLock lock(&mutex_);
+
+ auto* endpoint = channel_state_.LookupEndpointData(endpoint_id);
+ if (endpoint != nullptr && endpoint->channel == nullptr) {
+ NEARBY_LOGS(INFO) << "EndpointChannelManager is missing channel while "
+ "trying to update: endpoint "
+ << endpoint_id;
+ }
+
+ SetActiveEndpointChannel(client, endpoint_id, std::move(channel));
+}
+
+bool EndpointChannelManager::EncryptChannelForEndpoint(
+ const std::string& endpoint_id,
+ std::unique_ptr<EncryptionContext> context) {
+ MutexLock lock(&mutex_);
+
+ channel_state_.UpdateEncryptionContextForEndpoint(endpoint_id,
+ std::move(context));
+ auto* endpoint = channel_state_.LookupEndpointData(endpoint_id);
+ return channel_state_.EncryptChannel(endpoint);
+}
+
+std::shared_ptr<EndpointChannel> EndpointChannelManager::GetChannelForEndpoint(
+ const std::string& endpoint_id) {
+ MutexLock lock(&mutex_);
+
+ auto* endpoint = channel_state_.LookupEndpointData(endpoint_id);
+ if (endpoint == nullptr) {
+ NEARBY_LOGS(INFO) << "No channel info for endpoint " << endpoint_id;
+ return {};
+ }
+
+ return endpoint->channel;
+}
+
+void EndpointChannelManager::SetActiveEndpointChannel(
+ ClientProxy* client, const std::string& endpoint_id,
+ std::unique_ptr<EndpointChannel> channel) {
+ // Update the channel first, then encrypt this new channel, if
+ // crypto context is present.
+ channel->SetAnalyticsRecorder(&client->GetAnalyticsRecorder(), endpoint_id);
+ channel_state_.UpdateChannelForEndpoint(endpoint_id, std::move(channel));
+
+ auto* endpoint = channel_state_.LookupEndpointData(endpoint_id);
+ if (endpoint->IsEncrypted()) channel_state_.EncryptChannel(endpoint);
+}
+
+int EndpointChannelManager::GetConnectedEndpointsCount() const {
+ MutexLock lock(&mutex_);
+ return channel_state_.GetConnectedEndpointsCount();
+}
+
+///////////////////////////////// ChannelState /////////////////////////////////
+
+// endpoint - channel endpoint to encrypt
+bool EndpointChannelManager::ChannelState::EncryptChannel(
+ EndpointChannelManager::ChannelState::EndpointData* endpoint) {
+ if (endpoint != nullptr && endpoint->channel != nullptr &&
+ endpoint->context != nullptr) {
+ endpoint->channel->EnableEncryption(endpoint->context);
+ return true;
+ }
+ return false;
+}
+
+EndpointChannelManager::ChannelState::EndpointData*
+EndpointChannelManager::ChannelState::LookupEndpointData(
+ const std::string& endpoint_id) {
+ auto item = endpoints_.find(endpoint_id);
+ return item != endpoints_.end() ? &item->second : nullptr;
+}
+
+void EndpointChannelManager::ChannelState::UpdateChannelForEndpoint(
+ const std::string& endpoint_id, std::unique_ptr<EndpointChannel> channel) {
+ // Create EndpointData instance, if necessary, and populate channel.
+ endpoints_[endpoint_id].channel = std::move(channel);
+}
+
+void EndpointChannelManager::ChannelState::UpdateEncryptionContextForEndpoint(
+ const std::string& endpoint_id,
+ std::unique_ptr<EncryptionContext> context) {
+ // Create EndpointData instance, if necessary, and populate crypto context.
+ endpoints_[endpoint_id].context = std::move(context);
+}
+
+bool EndpointChannelManager::ChannelState::RemoveEndpoint(
+ const std::string& endpoint_id,
+ proto::connections::DisconnectionReason reason) {
+ auto item = endpoints_.find(endpoint_id);
+ if (item == endpoints_.end()) return false;
+ item->second.disconnect_reason = reason;
+ auto channel = item->second.channel;
+ if (channel) {
+ // If the channel was paused (i.e. during a bandwidth upgrade negotiation)
+ // we resume to ensure the thread won't hang when trying to write to it.
+ channel->Resume();
+
+ channel->Write(parser::ForDisconnection());
+ NEARBY_LOGS(INFO)
+ << "EndpointChannelManager reported the disconnection to endpoint "
+ << endpoint_id;
+ SystemClock::Sleep(kDataTransferDelay);
+ }
+ endpoints_.erase(item);
+ return true;
+}
+
+bool EndpointChannelManager::UnregisterChannelForEndpoint(
+ const std::string& endpoint_id) {
+ MutexLock lock(&mutex_);
+
+ if (!channel_state_.RemoveEndpoint(
+ endpoint_id,
+ proto::connections::DisconnectionReason::LOCAL_DISCONNECTION)) {
+ return false;
+ }
+
+ NEARBY_LOGS(INFO)
+ << "EndpointChannelManager unregistered channel for endpoint "
+ << endpoint_id;
+
+ return true;
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/endpoint_channel_manager.h b/chromium/third_party/nearby/src/connections/implementation/endpoint_channel_manager.h
new file mode 100644
index 00000000000..fa431c188f9
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/endpoint_channel_manager.h
@@ -0,0 +1,172 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_ENDPOINT_CHANNEL_MANAGER_H_
+#define CORE_INTERNAL_ENDPOINT_CHANNEL_MANAGER_H_
+
+#include <memory>
+#include <string>
+
+#include "securegcm/d2d_connection_context_v1.h"
+#include "absl/container/flat_hash_map.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/endpoint_channel.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/mutex.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// NOTE(std::string):
+// All the strings in internal class public interfaces should be exchanged as
+// const std::string& if they are immutable, and as std::string if they are
+// mutable.
+// This is to keep all the internal classes compatible with each other,
+// and minimize resources spent on the type conversion.
+// Project-wide, strings are either passed around as reference (which has
+// zero maintenance costs, and sizeof(void*) memory usage => passed around in a
+// CPU register), and whenever lifetime etension is required, it must be copied
+// to std::string instance (which will again propagate as a const reference
+// within it's lifetime domain).
+
+// Manages the communication channels to all the remote endpoints with which we
+// are interacting.
+class EndpointChannelManager final {
+ public:
+ using EncryptionContext = EndpointChannel::EncryptionContext;
+
+ ~EndpointChannelManager();
+
+ // Registers the initial EndpointChannel to be associated with an endpoint;
+ // if there already exists a previously-associated EndpointChannel, that will
+ // be closed before continuing the registration.
+ void RegisterChannelForEndpoint(ClientProxy* client,
+ const std::string& endpoint_id,
+ std::unique_ptr<EndpointChannel> channel)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Replaces the EndpointChannel to be associated with an endpoint from here on
+ // in, transferring the encryption context from the previous EndpointChannel
+ // to the newly-provided EndpointChannel.
+ void ReplaceChannelForEndpoint(ClientProxy* client,
+ const std::string& endpoint_id,
+ std::unique_ptr<EndpointChannel> channel)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ bool EncryptChannelForEndpoint(const std::string& endpoint_id,
+ std::unique_ptr<EncryptionContext> context)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // NOTE(shared_ptr<> usage):
+ //
+ // EndpointChannelManager is holding an EndpointChannel instance;
+ // GetChannelForEndpoint() is passing ownership over to a worker thread.
+ // It is not a pointer passing but an ownership passing, to guarantee that
+ // channel instance will not disappear underneath the feet of a worker thread
+ // inside EndpointManager [ EndpointManager::EndpointChannelLoopRunnable() ].
+ // If it is just a pointer, Channel will get destroyed while in use by a
+ // worker thread. shared_ptr is a simple and reliable tool to avoid that.
+ //
+ // The reason why it can not be std::unique_ptr<> is: there are other code
+ // paths that expect to be able to read the pointer value multiple times, from
+ // multiple places (each of them needs "ownership" for the duration of their
+ // use). EndpointManager::SendTransferFrameBytes() is another such place.
+ // If EndpointChannelManager replaces the current channel, and any (or both)
+ // EndpointManager methods that use a channel are running, it is better to
+ // have a shared ownership.
+ std::shared_ptr<EndpointChannel> GetChannelForEndpoint(
+ const std::string& endpoint_id) ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns true if 'endpoint_id' actually had a registered EndpointChannel.
+ // IOW, a return of false signifies a no-op.
+ bool UnregisterChannelForEndpoint(const std::string& endpoint_id)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ int GetConnectedEndpointsCount() const ABSL_LOCKS_EXCLUDED(mutex_);
+
+ private:
+ // Tracks channel state for all endpoints. This includes what EndpointChannel
+ // the endpoint is currently using and whether or not the EndpointChannel has
+ // been encrypted yet.
+ class ChannelState {
+ public:
+ struct EndpointData {
+ EndpointData() = default;
+ EndpointData(EndpointData&&) = default;
+ EndpointData& operator=(EndpointData&&) = default;
+ ~EndpointData() {
+ if (channel != nullptr) {
+ channel->Close(disconnect_reason);
+ }
+ }
+
+ // True if we have a 'context' for the endpoint.
+ bool IsEncrypted() const { return context != nullptr; }
+
+ std::shared_ptr<EndpointChannel> channel;
+ std::shared_ptr<EncryptionContext> context;
+ proto::connections::DisconnectionReason disconnect_reason =
+ proto::connections::DisconnectionReason::UNKNOWN_DISCONNECTION_REASON;
+ };
+
+ ChannelState() = default;
+ ~ChannelState() { DestroyAll(); }
+ ChannelState(ChannelState&&) = default;
+ ChannelState& operator=(ChannelState&&) = default;
+
+ // Provides a way to destroy contents of a container, while holding a lock.
+ void DestroyAll() { endpoints_.clear(); }
+ // Return pointer to endpoint data, or nullptr, it not found.
+ EndpointData* LookupEndpointData(const std::string& endpoint_id);
+
+ // Stores a new EndpointChannel for the endpoint.
+ // Prevoius one is destroyed, if it existed.
+ void UpdateChannelForEndpoint(const std::string& endpoint_id,
+ std::unique_ptr<EndpointChannel> channel);
+
+ // Stores a new EncryptionContext for the endpoint.
+ // Prevoius one is destroyed, if it existed.
+ void UpdateEncryptionContextForEndpoint(
+ const std::string& endpoint_id,
+ std::unique_ptr<EncryptionContext> context);
+
+ // Removes all knowledge of this endpoint, cleaning up as necessary.
+ // Returns false if the endpoint was not found.
+ bool RemoveEndpoint(const std::string& endpoint_id,
+ proto::connections::DisconnectionReason reason);
+
+ bool EncryptChannel(EndpointData* endpoint);
+ int GetConnectedEndpointsCount() const { return endpoints_.size(); }
+
+ private:
+ // Endpoint ID -> EndpointData. Contains everything we know about the
+ // endpoint.
+ absl::flat_hash_map<std::string, EndpointData> endpoints_;
+ };
+
+ void SetActiveEndpointChannel(ClientProxy* client,
+ const std::string& endpoint_id,
+ std::unique_ptr<EndpointChannel> channel)
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ mutable Mutex mutex_;
+ ChannelState channel_state_ ABSL_GUARDED_BY(mutex_);
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_ENDPOINT_CHANNEL_MANAGER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/endpoint_channel_manager_test.cc b/chromium/third_party/nearby/src/connections/implementation/endpoint_channel_manager_test.cc
new file mode 100644
index 00000000000..c6dc522c44e
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/endpoint_channel_manager_test.cc
@@ -0,0 +1,32 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/endpoint_channel_manager.h"
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+TEST(EndpointChannelManagerTest, ConstructorDestructorWorks) {
+ EndpointChannelManager mgr;
+ SUCCEED();
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/endpoint_manager.cc b/chromium/third_party/nearby/src/connections/implementation/endpoint_manager.cc
new file mode 100644
index 00000000000..407a3fb09cb
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/endpoint_manager.cc
@@ -0,0 +1,674 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/endpoint_manager.h"
+
+#include <memory>
+#include <utility>
+
+#include "connections/implementation/proto/offline_wire_formats.pb.h"
+#include "connections/implementation/endpoint_channel.h"
+#include "connections/implementation/offline_frames.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/mutex_lock.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+using ::location::nearby::proto::connections::Medium;
+
+constexpr absl::Duration EndpointManager::kProcessEndpointDisconnectionTimeout;
+constexpr absl::Time EndpointManager::kInvalidTimestamp;
+
+class EndpointManager::LockedFrameProcessor {
+ public:
+ explicit LockedFrameProcessor(FrameProcessorWithMutex* fp)
+ : lock_{std::make_unique<MutexLock>(&fp->mutex_)},
+ frame_processor_with_mutex_{fp} {}
+
+ // Constructor of a no-op object.
+ LockedFrameProcessor() {}
+
+ explicit operator bool() const { return get() != nullptr; }
+
+ FrameProcessor* operator->() const { return get(); }
+
+ void set(FrameProcessor* frame_processor) {
+ if (frame_processor_with_mutex_)
+ frame_processor_with_mutex_->frame_processor_ = frame_processor;
+ }
+
+ FrameProcessor* get() const {
+ return frame_processor_with_mutex_
+ ? frame_processor_with_mutex_->frame_processor_
+ : nullptr;
+ }
+
+ void reset() {
+ if (frame_processor_with_mutex_)
+ frame_processor_with_mutex_->frame_processor_ = nullptr;
+ }
+
+ private:
+ std::unique_ptr<MutexLock> lock_;
+ FrameProcessorWithMutex* frame_processor_with_mutex_ = nullptr;
+};
+
+// A Runnable that continuously grabs the most recent EndpointChannel available
+// for an endpoint.
+//
+// handler - Called whenever an EndpointChannel is available for endpointId.
+// Implementations are expected to read/write freely to the
+// EndpointChannel until an Exception::IO is thrown. Once an
+// Exception::IO occurs, a check will be performed to see if another
+// EndpointChannel is available for the given endpoint and, if so,
+// handler(EndpointChannel) will be called again.
+void EndpointManager::EndpointChannelLoopRunnable(
+ const std::string& runnable_name, ClientProxy* client,
+ const std::string& endpoint_id,
+ std::function<ExceptionOr<bool>(EndpointChannel*)> handler) {
+ // EndpointChannelManager will not let multiple channels exist simultaneously
+ // for the same endpoint_id; it will be closing "old" channels as new ones
+ // come.
+ // Closed channel will return Exception::kIo for any Read, and loop (below)
+ // will retry and attempt to pick another channel.
+ // If channel is deleted (no mapping), or it is still the same channel
+ // (same Medium) on which we got the Exception::kIo, we terminate the loop.
+ NEARBY_LOG(INFO, "Started worker loop name=%s, endpoint=%s",
+ runnable_name.c_str(), endpoint_id.c_str());
+ Medium last_failed_medium = Medium::UNKNOWN_MEDIUM;
+ while (true) {
+ // It's important to keep re-fetching the EndpointChannel for an endpoint
+ // because it can be changed out from under us (for example, when we
+ // upgrade from Bluetooth to Wifi).
+ std::shared_ptr<EndpointChannel> channel =
+ channel_manager_->GetChannelForEndpoint(endpoint_id);
+ if (channel == nullptr) {
+ NEARBY_LOG(INFO, "Endpoint channel is nullptr, bail out.");
+ break;
+ }
+
+ // If we're looping back around after a failure, and there's not a new
+ // EndpointChannel for this endpoint, there's nothing more to do here.
+ if ((last_failed_medium != Medium::UNKNOWN_MEDIUM) &&
+ (channel->GetMedium() == last_failed_medium)) {
+ NEARBY_LOG(
+ INFO, "No new endpoint channel is found after a failure, exit loop.");
+ break;
+ }
+
+ ExceptionOr<bool> keep_using_channel = handler(channel.get());
+
+ if (!keep_using_channel.ok()) {
+ Exception exception = keep_using_channel.GetException();
+ // An "invalid proto" may be a final payload on a channel we're about to
+ // close, so we'll loop back around once. We set |last_failed_medium| to
+ // ensure we don't loop indefinitely. See crbug.com/1182031 for more
+ // detail.
+ if (exception.Raised(Exception::kInvalidProtocolBuffer)) {
+ last_failed_medium = channel->GetMedium();
+ NEARBY_LOGS(INFO)
+ << "Received invalid protobuf message, re-fetching endpoint "
+ "channel; last_failed_medium="
+ << proto::connections::Medium_Name(last_failed_medium);
+ continue;
+ }
+ if (exception.Raised(Exception::kIo)) {
+ last_failed_medium = channel->GetMedium();
+ NEARBY_LOGS(INFO)
+ << "Endpoint channel IO exception; last_failed_medium="
+ << proto::connections::Medium_Name(last_failed_medium);
+ continue;
+ }
+ if (exception.Raised(Exception::kInterrupted)) {
+ break;
+ }
+ }
+
+ if (!keep_using_channel.result()) {
+ NEARBY_LOGS(INFO) << "Dropping current channel: last medium="
+ << proto::connections::Medium_Name(last_failed_medium);
+ break;
+ }
+ }
+ // Indicate we're out of the loop and it is ok to schedule another instance
+ // if needed.
+ NEARBY_LOGS(INFO) << "Worker going down; worker name=" << runnable_name
+ << "; endpoint_id=" << endpoint_id;
+ // Always clear out all state related to this endpoint before terminating
+ // this thread.
+ DiscardEndpoint(client, endpoint_id);
+ NEARBY_LOGS(INFO) << "Worker done; worker name=" << runnable_name
+ << "; endpoint_id=" << endpoint_id;
+}
+
+ExceptionOr<bool> EndpointManager::HandleData(
+ const std::string& endpoint_id, ClientProxy* client,
+ EndpointChannel* endpoint_channel) {
+ // Read as much as we can from the healthy EndpointChannel - when it is no
+ // longer in good shape (i.e. our read from it throws an Exception), our
+ // super class will loop back around and try our luck in case there's been
+ // a replacement for this endpoint since we last checked with the
+ // EndpointChannelManager.
+ while (true) {
+ ExceptionOr<ByteArray> bytes = endpoint_channel->Read();
+ if (!bytes.ok()) {
+ NEARBY_LOG(INFO, "Stop reading on read-time exception: %d",
+ bytes.exception());
+ return ExceptionOr<bool>(bytes.exception());
+ }
+ ExceptionOr<OfflineFrame> wrapped_frame = parser::FromBytes(bytes.result());
+ if (!wrapped_frame.ok()) {
+ if (wrapped_frame.GetException().Raised(
+ Exception::kInvalidProtocolBuffer)) {
+ NEARBY_LOG(INFO, "Failed to decode; endpoint=%s; channel=%s; skip",
+ endpoint_id.c_str(), endpoint_channel->GetType().c_str());
+ continue;
+ } else {
+ NEARBY_LOG(INFO, "Stop reading on parse-time exception: %d",
+ wrapped_frame.exception());
+ return ExceptionOr<bool>(wrapped_frame.exception());
+ }
+ }
+ OfflineFrame& frame = wrapped_frame.result();
+
+ // Route the incoming offlineFrame to its registered processor.
+ V1Frame::FrameType frame_type = parser::GetFrameType(frame);
+ LockedFrameProcessor frame_processor = GetFrameProcessor(frame_type);
+ if (!frame_processor) {
+ // report messages without handlers, except KEEP_ALIVE, which has
+ // no explicit handler.
+ if (frame_type == V1Frame::KEEP_ALIVE) {
+ NEARBY_LOG(INFO, "KeepAlive message for endpoint %s",
+ endpoint_id.c_str());
+ } else if (frame_type == V1Frame::DISCONNECTION) {
+ NEARBY_LOG(INFO, "Disconnect message for endpoint %s",
+ endpoint_id.c_str());
+ endpoint_channel->Close();
+ } else {
+ NEARBY_LOGS(ERROR) << "Unhandled message: endpoint_id=" << endpoint_id
+ << ", frame type="
+ << V1Frame::FrameType_Name(frame_type);
+ }
+ continue;
+ }
+
+ frame_processor->OnIncomingFrame(frame, endpoint_id, client,
+ endpoint_channel->GetMedium());
+ }
+}
+
+ExceptionOr<bool> EndpointManager::HandleKeepAlive(
+ EndpointChannel* endpoint_channel, absl::Duration keep_alive_interval,
+ absl::Duration keep_alive_timeout, Mutex* keep_alive_waiter_mutex,
+ ConditionVariable* keep_alive_waiter) {
+ // Check if it has been too long since we received a frame from our endpoint.
+ absl::Time last_read_time = endpoint_channel->GetLastReadTimestamp();
+ absl::Duration duration_until_timeout =
+ last_read_time == kInvalidTimestamp
+ ? keep_alive_timeout
+ : last_read_time + keep_alive_timeout -
+ SystemClock::ElapsedRealtime();
+ if (duration_until_timeout <= absl::ZeroDuration()) {
+ return ExceptionOr<bool>(false);
+ }
+
+ // If we haven't written anything to the endpoint for a while, attempt to send
+ // the KeepAlive frame over the endpoint channel. If the write fails, our
+ // super class will loop back around and try our luck again in case there's
+ // been a replacement for this endpoint.
+ absl::Time last_write_time = endpoint_channel->GetLastWriteTimestamp();
+ absl::Duration duration_until_write_keep_alive =
+ last_write_time == kInvalidTimestamp
+ ? keep_alive_interval
+ : last_write_time + keep_alive_interval -
+ SystemClock::ElapsedRealtime();
+ if (duration_until_write_keep_alive <= absl::ZeroDuration()) {
+ Exception write_exception = endpoint_channel->Write(parser::ForKeepAlive());
+ if (!write_exception.Ok()) {
+ return ExceptionOr<bool>(write_exception);
+ }
+ duration_until_write_keep_alive = keep_alive_interval;
+ }
+
+ absl::Duration wait_for =
+ std::min(duration_until_timeout, duration_until_write_keep_alive);
+ {
+ MutexLock lock(keep_alive_waiter_mutex);
+ Exception wait_exception = keep_alive_waiter->Wait(wait_for);
+ if (!wait_exception.Ok()) {
+ return ExceptionOr<bool>(wait_exception);
+ }
+ }
+
+ return ExceptionOr<bool>(true);
+}
+
+bool operator==(const EndpointManager::FrameProcessor& lhs,
+ const EndpointManager::FrameProcessor& rhs) {
+ // We're comparing addresses because these objects are callbacks which need to
+ // be matched by exact instances.
+ return &lhs == &rhs;
+}
+
+bool operator<(const EndpointManager::FrameProcessor& lhs,
+ const EndpointManager::FrameProcessor& rhs) {
+ // We're comparing addresses because these objects are callbacks which need to
+ // be matched by exact instances.
+ return &lhs < &rhs;
+}
+
+EndpointManager::EndpointManager(EndpointChannelManager* manager)
+ : channel_manager_(manager) {}
+
+EndpointManager::~EndpointManager() {
+ NEARBY_LOG(INFO, "Initiating shutdown of EndpointManager.");
+ CountDownLatch latch(1);
+ RunOnEndpointManagerThread("bring-down-endpoints", [this, &latch]() {
+ NEARBY_LOG(INFO, "Bringing down endpoints");
+ endpoints_.clear();
+ latch.CountDown();
+ });
+ latch.Await();
+
+ NEARBY_LOG(INFO, "Bringing down control thread");
+ serial_executor_.Shutdown();
+ NEARBY_LOG(INFO, "EndpointManager is down");
+}
+
+void EndpointManager::RegisterFrameProcessor(
+ V1Frame::FrameType frame_type, EndpointManager::FrameProcessor* processor) {
+ if (auto frame_processor = GetFrameProcessor(frame_type)) {
+ NEARBY_LOGS(INFO) << "EndpointManager received request to update "
+ "registration of frame processor "
+ << processor << " for frame type "
+ << V1Frame::FrameType_Name(frame_type) << ", self"
+ << this;
+ frame_processor.set(processor);
+ } else {
+ MutexLock lock(&frame_processors_lock_);
+ NEARBY_LOGS(INFO) << "EndpointManager received request to add registration "
+ "of frame processor "
+ << processor << " for frame type "
+ << V1Frame::FrameType_Name(frame_type)
+ << ", self=" << this;
+ frame_processors_.emplace(frame_type, processor);
+ }
+}
+
+void EndpointManager::UnregisterFrameProcessor(
+ V1Frame::FrameType frame_type,
+ const EndpointManager::FrameProcessor* processor) {
+ NEARBY_LOGS(INFO) << "UnregisterFrameProcessor [enter]: processor ="
+ << processor;
+ if (processor == nullptr) return;
+ if (auto frame_processor = GetFrameProcessor(frame_type)) {
+ if (frame_processor.get() == processor) {
+ frame_processor.reset();
+ NEARBY_LOGS(INFO) << "EndpointManager unregister frame processor "
+ << processor << " for frame type "
+ << V1Frame::FrameType_Name(frame_type)
+ << ", self=" << this;
+ } else {
+ NEARBY_LOGS(INFO) << "EndpointManager cannot unregister frame processor "
+ << processor
+ << " because it is not registered for frame type "
+ << V1Frame::FrameType_Name(frame_type)
+ << ", expected=" << frame_processor.get();
+ }
+ } else {
+ NEARBY_LOGS(INFO) << "UnregisterFrameProcessor [not found]: processor="
+ << processor;
+ }
+}
+
+EndpointManager::LockedFrameProcessor EndpointManager::GetFrameProcessor(
+ V1Frame::FrameType frame_type) {
+ MutexLock lock(&frame_processors_lock_);
+ auto it = frame_processors_.find(frame_type);
+ if (it != frame_processors_.end()) {
+ return LockedFrameProcessor(&it->second);
+ }
+ return LockedFrameProcessor();
+}
+
+void EndpointManager::RemoveEndpointState(const std::string& endpoint_id) {
+ NEARBY_LOGS(VERBOSE) << "EnsureWorkersTerminated for endpoint "
+ << endpoint_id;
+ auto item = endpoints_.find(endpoint_id);
+ if (item != endpoints_.end()) {
+ NEARBY_LOGS(INFO) << "EndpointState found for endpoint " << endpoint_id;
+ // If another instance of data and keep-alive handlers is running, it will
+ // terminate soon. Removing EndpointState waits for workers to complete.
+ endpoints_.erase(item);
+ NEARBY_LOGS(VERBOSE) << "Workers terminated for endpoint " << endpoint_id;
+ } else {
+ NEARBY_LOGS(INFO) << "EndpointState not found for endpoint " << endpoint_id;
+ }
+}
+
+void EndpointManager::RegisterEndpoint(
+ ClientProxy* client, const std::string& endpoint_id,
+ const ConnectionResponseInfo& info,
+ const ConnectionOptions& connection_options,
+ std::unique_ptr<EndpointChannel> channel,
+ const ConnectionListener& listener, const std::string& connection_token) {
+ CountDownLatch latch(1);
+
+ // NOTE (unique_ptr<> capture):
+ // std::unique_ptr<> is not copyable, so we can not pass it to
+ // lambda capture, because lambda eventually is converted to std::function<>.
+ // Instead, we release() a pointer, and pass a raw pointer, which is copyalbe.
+ // We ignore the risk of job not scheduled (and an associated risk of memory
+ // leak), because this may only happen during service shutdown.
+ RunOnEndpointManagerThread("register-endpoint", [this, client,
+ channel = channel.release(),
+ &endpoint_id, &info,
+ &connection_options,
+ &listener, &connection_token,
+ &latch]() {
+ if (endpoints_.contains(endpoint_id)) {
+ NEARBY_LOGS(WARNING) << "Registering duplicate endpoint " << endpoint_id;
+ // We must remove old endpoint state before registering a new one for the
+ // same endpoint_id.
+ RemoveEndpointState(endpoint_id);
+ }
+
+ absl::Duration keep_alive_interval =
+ absl::Milliseconds(connection_options.keep_alive_interval_millis);
+ absl::Duration keep_alive_timeout =
+ absl::Milliseconds(connection_options.keep_alive_timeout_millis);
+ NEARBY_LOGS(INFO) << "Registering endpoint " << endpoint_id
+ << " for client " << client->GetClientId()
+ << " with keep-alive frame as interval="
+ << absl::FormatDuration(keep_alive_interval)
+ << ", timeout="
+ << absl::FormatDuration(keep_alive_timeout);
+
+ // Pass ownership of channel to EndpointChannelManager
+ NEARBY_LOGS(INFO) << "Registering endpoint with channel manager: endpoint "
+ << endpoint_id;
+ channel_manager_->RegisterChannelForEndpoint(
+ client, endpoint_id, std::unique_ptr<EndpointChannel>(channel));
+
+ EndpointState& endpoint_state =
+ endpoints_
+ .emplace(endpoint_id, EndpointState(endpoint_id, channel_manager_))
+ .first->second;
+
+ NEARBY_LOGS(INFO) << "Starting workers: endpoint " << endpoint_id;
+ // For every endpoint, there's normally only one Read handler instance
+ // running on a dedicated thread. This instance reads data from the
+ // endpoint and delegates incoming frames to various FrameProcessors.
+ // Once the frame has been properly handled, it starts reading again for
+ // the next frame. If the handler fails its read and no other
+ // EndpointChannels are available for this endpoint, a disconnection
+ // will be initiated.
+ endpoint_state.StartEndpointReader([this, client, endpoint_id]() {
+ EndpointChannelLoopRunnable(
+ "Read", client, endpoint_id,
+ [this, client, endpoint_id](EndpointChannel* channel) {
+ return HandleData(endpoint_id, client, channel);
+ });
+ });
+
+ // For every endpoint, there's only one KeepAliveManager instance running on
+ // a dedicated thread. This instance will periodically send out a ping* to
+ // the endpoint while listening for an incoming pong**. If it fails to send
+ // the ping, or if no pong is heard within keep_alive_timeout, it initiates
+ // a disconnection.
+ //
+ // (*) Bluetooth requires a constant outgoing stream of messages. If
+ // there's silence, Android will break the socket. This is why we ping.
+ // (**) Wifi Hotspots can fail to notice a connection has been lost, and
+ // they will happily keep writing to /dev/null. This is why we listen
+ // for the pong.
+ NEARBY_LOGS(VERBOSE) << "EndpointManager enabling KeepAlive for endpoint "
+ << endpoint_id;
+ endpoint_state.StartEndpointKeepAliveManager(
+ [this, client, endpoint_id, keep_alive_interval, keep_alive_timeout](
+ Mutex* keep_alive_waiter_mutex,
+ ConditionVariable* keep_alive_waiter) {
+ EndpointChannelLoopRunnable(
+ "KeepAliveManager", client, endpoint_id,
+ [this, keep_alive_interval, keep_alive_timeout,
+ keep_alive_waiter_mutex,
+ keep_alive_waiter](EndpointChannel* channel) {
+ return HandleKeepAlive(
+ channel, keep_alive_interval, keep_alive_timeout,
+ keep_alive_waiter_mutex, keep_alive_waiter);
+ });
+ });
+ NEARBY_LOGS(INFO) << "Registering endpoint " << endpoint_id
+ << ", workers started and notifying client.";
+
+ // It's now time to let the client know of this new connection so that
+ // they can accept or reject it.
+ client->OnConnectionInitiated(endpoint_id, info, connection_options,
+ listener, connection_token);
+ latch.CountDown();
+ });
+ latch.Await();
+}
+
+void EndpointManager::UnregisterEndpoint(ClientProxy* client,
+ const std::string& endpoint_id) {
+ NEARBY_LOGS(INFO) << "UnregisterEndpoint for endpoint " << endpoint_id;
+ CountDownLatch latch(1);
+ RunOnEndpointManagerThread(
+ "unregister-endpoint", [this, client, endpoint_id, &latch]() {
+ RemoveEndpoint(client, endpoint_id,
+ /*notify=*/client->IsConnectedToEndpoint(endpoint_id));
+ latch.CountDown();
+ });
+ latch.Await();
+}
+
+int EndpointManager::GetMaxTransmitPacketSize(const std::string& endpoint_id) {
+ std::shared_ptr<EndpointChannel> channel =
+ channel_manager_->GetChannelForEndpoint(endpoint_id);
+ if (channel == nullptr) {
+ return 0;
+ }
+
+ return channel->GetMaxTransmitPacketSize();
+}
+
+std::vector<std::string> EndpointManager::SendPayloadChunk(
+ const PayloadTransferFrame::PayloadHeader& payload_header,
+ const PayloadTransferFrame::PayloadChunk& payload_chunk,
+ const std::vector<std::string>& endpoint_ids) {
+ ByteArray bytes =
+ parser::ForDataPayloadTransfer(payload_header, payload_chunk);
+
+ return SendTransferFrameBytes(
+ endpoint_ids, bytes, payload_header.id(),
+ /*offset=*/payload_chunk.offset(),
+ /*packet_type=*/
+ PayloadTransferFrame::PacketType_Name(PayloadTransferFrame::DATA));
+}
+
+// Designed to run asynchronously. It is called from IO thread pools, and
+// jobs in these pools may be waited for from the EndpointManager thread. If we
+// allow synchronous behavior here it will cause a live lock.
+void EndpointManager::DiscardEndpoint(ClientProxy* client,
+ const std::string& endpoint_id) {
+ NEARBY_LOGS(VERBOSE) << "DiscardEndpoint for endpoint " << endpoint_id;
+ RunOnEndpointManagerThread("discard-endpoint", [this, client, endpoint_id]() {
+ RemoveEndpoint(client, endpoint_id,
+ /*notify=*/client->IsConnectedToEndpoint(endpoint_id));
+ });
+}
+
+std::vector<std::string> EndpointManager::SendControlMessage(
+ const PayloadTransferFrame::PayloadHeader& header,
+ const PayloadTransferFrame::ControlMessage& control,
+ const std::vector<std::string>& endpoint_ids) {
+ ByteArray bytes = parser::ForControlPayloadTransfer(header, control);
+
+ return SendTransferFrameBytes(
+ endpoint_ids, bytes, header.id(),
+ /*offset=*/control.offset(),
+ /*packet_type=*/
+ PayloadTransferFrame::PacketType_Name(PayloadTransferFrame::CONTROL));
+}
+
+// @EndpointManagerThread
+void EndpointManager::RemoveEndpoint(ClientProxy* client,
+ const std::string& endpoint_id,
+ bool notify) {
+ NEARBY_LOGS(INFO) << "RemoveEndpoint for endpoint " << endpoint_id;
+ // Unregistering from channel_manager_ will also serve to terminate
+ // the dedicated handler and KeepAlive threads we started when we registered
+ // this endpoint.
+ if (channel_manager_->UnregisterChannelForEndpoint(endpoint_id)) {
+ // Notify all frame processors of the disconnection immediately and wait
+ // for them to clean up state. Only once all processors are done cleaning
+ // up, we can remove the endpoint from ClientProxy after which there
+ // should be no further interactions with the endpoint.
+ // (See b/37352254 for history)
+ WaitForEndpointDisconnectionProcessing(client, endpoint_id);
+
+ client->OnDisconnected(endpoint_id, notify);
+ NEARBY_LOGS(INFO) << "Removed endpoint for endpoint " << endpoint_id;
+ }
+ RemoveEndpointState(endpoint_id);
+}
+
+// @EndpointManagerThread
+void EndpointManager::WaitForEndpointDisconnectionProcessing(
+ ClientProxy* client, const std::string& endpoint_id) {
+ NEARBY_LOGS(INFO) << "Wait: client=" << client
+ << "; endpoint_id=" << endpoint_id;
+ CountDownLatch barrier =
+ NotifyFrameProcessorsOnEndpointDisconnect(client, endpoint_id);
+
+ NEARBY_LOGS(INFO)
+ << "Waiting for frame processors to disconnect from endpoint "
+ << endpoint_id;
+ if (!barrier.Await(kProcessEndpointDisconnectionTimeout).result()) {
+ NEARBY_LOGS(INFO) << "Failed to disconnect frame processors from endpoint "
+ << endpoint_id;
+ } else {
+ NEARBY_LOGS(INFO)
+ << "Finished waiting for frame processors to disconnect from endpoint "
+ << endpoint_id;
+ }
+}
+
+CountDownLatch EndpointManager::NotifyFrameProcessorsOnEndpointDisconnect(
+ ClientProxy* client, const std::string& endpoint_id) {
+ NEARBY_LOGS(INFO) << "NotifyFrameProcessorsOnEndpointDisconnect: client="
+ << client << "; endpoint_id=" << endpoint_id;
+ MutexLock lock(&frame_processors_lock_);
+ auto total_size = frame_processors_.size();
+ NEARBY_LOGS(INFO) << "Total frame processors: " << total_size;
+ CountDownLatch barrier(total_size);
+
+ int valid = 0;
+ for (auto& item : frame_processors_) {
+ LockedFrameProcessor processor(&item.second);
+ NEARBY_LOGS(INFO) << "processor=" << processor.get()
+ << "; frame type=" << V1Frame::FrameType_Name(item.first);
+ if (processor) {
+ valid++;
+ processor->OnEndpointDisconnect(client, endpoint_id, barrier);
+ } else {
+ barrier.CountDown();
+ }
+ }
+
+ if (!valid) {
+ NEARBY_LOGS(INFO) << "No valid frame processors.";
+ } else {
+ NEARBY_LOGS(INFO) << "Valid frame processors: " << valid;
+ }
+ return barrier;
+}
+
+std::vector<std::string> EndpointManager::SendTransferFrameBytes(
+ const std::vector<std::string>& endpoint_ids, const ByteArray& bytes,
+ std::int64_t payload_id, std::int64_t offset,
+ const std::string& packet_type) {
+ std::vector<std::string> failed_endpoint_ids;
+ for (const std::string& endpoint_id : endpoint_ids) {
+ std::shared_ptr<EndpointChannel> channel =
+ channel_manager_->GetChannelForEndpoint(endpoint_id);
+
+ if (channel == nullptr) {
+ // We no longer know about this endpoint (it was either explicitly
+ // unregistered, or a read/write error made us unregister it internally).
+ NEARBY_LOGS(ERROR) << "EndpointManager failed to find EndpointChannel "
+ "over which to write "
+ << packet_type << " at offset " << offset
+ << " of Payload " << payload_id << " to endpoint "
+ << endpoint_id;
+
+ failed_endpoint_ids.push_back(endpoint_id);
+ continue;
+ }
+
+ Exception write_exception = channel->Write(bytes);
+ if (!write_exception.Ok()) {
+ failed_endpoint_ids.push_back(endpoint_id);
+ NEARBY_LOGS(INFO) << "Failed to send packet; endpoint_id=" << endpoint_id;
+ continue;
+ }
+ }
+
+ return failed_endpoint_ids;
+}
+
+EndpointManager::EndpointState::~EndpointState() {
+ // We must unregister the endpoint first to signal the runnables that they
+ // should exit their loops. SingleThreadExecutor destructors will wait for the
+ // workers to finish. |channel_manager_| is null after moved from this object
+ // (in move constructor) which prevents unregistering the channel prematurely.
+ if (channel_manager_) {
+ NEARBY_LOG(VERBOSE, "EndpointState destructor %s", endpoint_id_.c_str());
+ channel_manager_->UnregisterChannelForEndpoint(endpoint_id_);
+ }
+
+ // Make sure the KeepAlive thread isn't blocking shutdown.
+ if (keep_alive_waiter_mutex_ && keep_alive_waiter_) {
+ MutexLock lock(keep_alive_waiter_mutex_.get());
+ keep_alive_waiter_->Notify();
+ }
+}
+
+void EndpointManager::EndpointState::StartEndpointReader(Runnable&& runnable) {
+ reader_thread_.Execute("reader", std::move(runnable));
+}
+
+void EndpointManager::EndpointState::StartEndpointKeepAliveManager(
+ std::function<void(Mutex*, ConditionVariable*)> runnable) {
+ keep_alive_thread_.Execute(
+ "keep-alive",
+ [runnable, keep_alive_waiter_mutex = keep_alive_waiter_mutex_.get(),
+ keep_alive_waiter = keep_alive_waiter_.get()]() {
+ runnable(keep_alive_waiter_mutex, keep_alive_waiter);
+ });
+}
+
+void EndpointManager::RunOnEndpointManagerThread(const std::string& name,
+ Runnable runnable) {
+ serial_executor_.Execute(name, std::move(runnable));
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/endpoint_manager.h b/chromium/third_party/nearby/src/connections/implementation/endpoint_manager.h
new file mode 100644
index 00000000000..416e0699162
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/endpoint_manager.h
@@ -0,0 +1,284 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_ENDPOINT_MANAGER_H_
+#define CORE_INTERNAL_ENDPOINT_MANAGER_H_
+
+#include <cstdint>
+#include <memory>
+
+#include "absl/base/thread_annotations.h"
+#include "absl/container/flat_hash_map.h"
+#include "absl/container/flat_hash_set.h"
+#include "absl/time/time.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/endpoint_channel.h"
+#include "connections/implementation/endpoint_channel_manager.h"
+#include "connections/listeners.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/runnable.h"
+#include "internal/platform/condition_variable.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/multi_thread_executor.h"
+#include "internal/platform/single_thread_executor.h"
+#include "internal/platform/system_clock.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Manages all operations related to the remote endpoints with which we are
+// interacting.
+//
+// All processing of incoming and outgoing payloads is spread across this and
+// the PayloadManager as described below.
+//
+// The sending of outgoing payloads originates in
+// PayloadManager::SendPayload() before control is transferred over to
+// EndpointManager::SendPayloadChunk(). This work happens on one of three
+// dedicated writer threads belonging to the PayloadManager. The writer thread
+// that is used depends on the Payload::Type.
+//
+// The EndpointManager has one dedicated reader thread for each registered
+// endpoint, and the receiving of every incoming payload (and its subsequent
+// chunks) originates on one of those threads before control is transferred over
+// to PayloadManager::ProcessFrame() (still running on that
+// same dedicated reader thread).
+
+class EndpointManager {
+ public:
+ class FrameProcessor {
+ public:
+ virtual ~FrameProcessor() = default;
+
+ // @EndpointManagerReaderThread
+ // Called for every incoming frame of registered type.
+ // NOTE(OfflineFrame& frame):
+ // For large payload in data phase, resources may be saved if data is moved,
+ // rather than copied (if passing data by reference is not an option).
+ // To achieve that, OfflineFrame needs to be either mutabe lvalue reference,
+ // or rvalue reference. Rvalue references are discouraged by go/cstyle,
+ // and that leaves us with mutable lvalue reference.
+ virtual void OnIncomingFrame(OfflineFrame& offline_frame,
+ const std::string& from_endpoint_id,
+ ClientProxy* to_client,
+ proto::connections::Medium current_medium) = 0;
+
+ // Implementations must call barrier.CountDown() once
+ // they're done. This parallelizes the disconnection event across all frame
+ // processors.
+ //
+ // @EndpointManagerThread
+ virtual void OnEndpointDisconnect(ClientProxy* client,
+ const std::string& endpoint_id,
+ CountDownLatch barrier) = 0;
+ };
+
+ explicit EndpointManager(EndpointChannelManager* manager);
+ ~EndpointManager();
+
+ // Invoked from the constructors of the various *Manager components that make
+ // up the OfflineServiceController implementation.
+ // FrameProcessor* instances are of dynamic duration and survive all sessions.
+ // Blocks until registration is complete.
+ void RegisterFrameProcessor(V1Frame::FrameType frame_type,
+ FrameProcessor* processor);
+ void UnregisterFrameProcessor(V1Frame::FrameType frame_type,
+ const FrameProcessor* processor);
+
+ // Invoked from the different PcpHandler implementations (of which there can
+ // be only one at a time).
+ // Blocks until registration is complete.
+ void RegisterEndpoint(ClientProxy* client, const std::string& endpoint_id,
+ const ConnectionResponseInfo& info,
+ const ConnectionOptions& connection_options,
+ std::unique_ptr<EndpointChannel> channel,
+ const ConnectionListener& listener,
+ const std::string& connection_token);
+ // Called when a client explicitly asks to disconnect from this endpoint. In
+ // this case, we do not notify the client of onDisconnected().
+ void UnregisterEndpoint(ClientProxy* client, const std::string& endpoint_id);
+
+ // Returns the maximum supported transmit packet size(MTU) for the underlying
+ // transport.
+ int GetMaxTransmitPacketSize(const std::string& endpoint_id);
+
+ // Returns the list of endpoints to which sending this chunk failed.
+ //
+ // Invoked from the PayloadManager's sendPayload() method.
+ std::vector<std::string> SendPayloadChunk(
+ const PayloadTransferFrame::PayloadHeader& payload_header,
+ const PayloadTransferFrame::PayloadChunk& payload_chunk,
+ const std::vector<std::string>& endpoint_ids);
+ std::vector<std::string> SendControlMessage(
+ const PayloadTransferFrame::PayloadHeader& payload_header,
+ const PayloadTransferFrame::ControlMessage& control_message,
+ const std::vector<std::string>& endpoint_ids);
+
+ // Called when we internally want to get rid of the endpoint, without the
+ // client directly telling us to. For example...
+ // a) We failed to read from the endpoint in its dedicated reader thread.
+ // b) We failed to write to the endpoint in PayloadManager.
+ // c) The connection was rejected in PCPHandler.
+ // d) The dedicated KeepAlive thread exceeded its period of inactivity.
+ // Or in the numerous other cases where a failure occurred and we no longer
+ // believe the endpoint is in a healthy state.
+ //
+ // Note: This must not block. Otherwise we can get into a deadlock where we
+ // ask everyone who's registered an FrameProcessor to
+ // processEndpointDisconnection() while the caller of DiscardEndpoint() is
+ // blocked here.
+ void DiscardEndpoint(ClientProxy* client, const std::string& endpoint_id);
+
+ private:
+ class EndpointState {
+ public:
+ EndpointState(const std::string& endpoint_id,
+ EndpointChannelManager* channel_manager)
+ : endpoint_id_{endpoint_id},
+ channel_manager_{channel_manager},
+ keep_alive_waiter_mutex_{std::make_unique<Mutex>()},
+ keep_alive_waiter_{std::make_unique<ConditionVariable>(
+ keep_alive_waiter_mutex_.get())} {}
+
+ EndpointState(const EndpointState&) = delete;
+ // The default move constructor would not reset |channel_manager_|, for
+ // example. This needs to be nullified so the destructor shutdown logic is
+ // bypassed when objects are moved.
+ EndpointState(EndpointState&& other)
+ : endpoint_id_{std::move(other.endpoint_id_)},
+ channel_manager_{std::exchange(other.channel_manager_, nullptr)},
+ reader_thread_{std::move(other.reader_thread_)},
+ keep_alive_waiter_mutex_{
+ std::exchange(other.keep_alive_waiter_mutex_, nullptr)},
+ keep_alive_waiter_{std::exchange(other.keep_alive_waiter_, nullptr)},
+ keep_alive_thread_{std::move(other.keep_alive_thread_)} {}
+ EndpointState& operator=(const EndpointState&) = delete;
+ EndpointState&& operator=(EndpointState&&) = delete;
+ ~EndpointState();
+
+ void StartEndpointReader(Runnable&& runnable);
+ void StartEndpointKeepAliveManager(
+ std::function<void(Mutex*, ConditionVariable*)> runnable);
+
+ private:
+ const std::string endpoint_id_;
+ EndpointChannelManager* channel_manager_;
+ SingleThreadExecutor reader_thread_;
+
+ // Use a condition variable so we can wait on the thread but still be able
+ // to wake it up before shutting down. We don't want to just sleep and risk
+ // blocking shutdown. Note: Create the mutex/condition variable on the heap
+ // so raw pointers sent to HandleKeepAlive() aren't invalidated during
+ // std::move operations.
+ mutable std::unique_ptr<Mutex> keep_alive_waiter_mutex_;
+ std::unique_ptr<ConditionVariable> keep_alive_waiter_;
+ SingleThreadExecutor keep_alive_thread_;
+ };
+
+ // RAII accessor for FrameProcessor
+ class LockedFrameProcessor;
+
+ // Provides a mutex per FrameProcessor to prevent unregistering (and
+ // destroying) a FrameProcessor when it's in use.
+ class FrameProcessorWithMutex {
+ public:
+ explicit FrameProcessorWithMutex(FrameProcessor* frame_processor = nullptr)
+ : frame_processor_{frame_processor} {}
+
+ private:
+ FrameProcessor* frame_processor_;
+ Mutex mutex_;
+ friend class LockedFrameProcessor;
+ };
+
+ LockedFrameProcessor GetFrameProcessor(V1Frame::FrameType frame_type);
+
+ ExceptionOr<bool> HandleData(const std::string& endpoint_id,
+ ClientProxy* client_proxy,
+ EndpointChannel* endpoint_channel);
+
+ ExceptionOr<bool> HandleKeepAlive(EndpointChannel* endpoint_channel,
+ absl::Duration keep_alive_interval,
+ absl::Duration keep_alive_timeout,
+ Mutex* keep_alive_waiter_mutex,
+ ConditionVariable* keep_alive_waiter);
+
+ // Waits for a given endpoint EndpointChannelLoopRunnable() workers to
+ // terminate.
+ // Is called from RegisterEndpoint to avoid races; also called from
+ // RemoveEndpoint as part of proper endpoint shutdown sequence.
+ // @EndpointManagerThread
+ void RemoveEndpointState(const std::string& endpoint_id);
+
+ void EndpointChannelLoopRunnable(
+ const std::string& runnable_name, ClientProxy* client_proxy,
+ const std::string& endpoint_id,
+ std::function<ExceptionOr<bool>(EndpointChannel*)> handler);
+
+ static void WaitForLatch(const std::string& method_name,
+ CountDownLatch* latch);
+ static void WaitForLatch(const std::string& method_name,
+ CountDownLatch* latch, std::int32_t timeout_millis);
+
+ static constexpr absl::Duration kProcessEndpointDisconnectionTimeout =
+ absl::Milliseconds(2000);
+ static constexpr absl::Time kInvalidTimestamp = absl::InfinitePast();
+
+ // It should be noted that this method may be called multiple times (because
+ // invoking this method closes the endpoint channel, which causes the
+ // dedicated reader and KeepAlive threads to terminate, which in turn leads to
+ // this method being called), but that's alright because the implementation of
+ // this method is idempotent.
+ // @EndpointManagerThread
+ void RemoveEndpoint(ClientProxy* client, const std::string& endpoint_id,
+ bool notify);
+
+ void WaitForEndpointDisconnectionProcessing(ClientProxy* client,
+ const std::string& endpoint_id);
+
+ CountDownLatch NotifyFrameProcessorsOnEndpointDisconnect(
+ ClientProxy* client, const std::string& endpoint_id);
+
+ std::vector<std::string> SendTransferFrameBytes(
+ const std::vector<std::string>& endpoint_ids,
+ const ByteArray& payload_transfer_frame_bytes, std::int64_t payload_id,
+ std::int64_t offset, const std::string& packet_type);
+
+ // Executes all jobs sequentially, on a serial_executor_.
+ void RunOnEndpointManagerThread(const std::string& name, Runnable runnable);
+
+ EndpointChannelManager* channel_manager_;
+
+ RecursiveMutex frame_processors_lock_;
+ absl::flat_hash_map<V1Frame::FrameType, FrameProcessorWithMutex>
+ frame_processors_ ABSL_GUARDED_BY(frame_processors_lock_);
+
+ // We keep track of all registered channel endpoints here.
+ absl::flat_hash_map<std::string, EndpointState> endpoints_;
+
+ SingleThreadExecutor serial_executor_;
+};
+
+// Operator overloads when comparing FrameProcessor*.
+bool operator==(const EndpointManager::FrameProcessor& lhs,
+ const EndpointManager::FrameProcessor& rhs);
+bool operator<(const EndpointManager::FrameProcessor& lhs,
+ const EndpointManager::FrameProcessor& rhs);
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_ENDPOINT_MANAGER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/endpoint_manager_test.cc b/chromium/third_party/nearby/src/connections/implementation/endpoint_manager_test.cc
new file mode 100644
index 00000000000..450e59c9956
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/endpoint_manager_test.cc
@@ -0,0 +1,289 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/endpoint_manager.h"
+
+#include <atomic>
+#include <memory>
+#include <string>
+#include <utility>
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "absl/synchronization/mutex.h"
+#include "absl/time/clock.h"
+#include "absl/time/time.h"
+#include "connections/connection_options.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/endpoint_channel_manager.h"
+#include "connections/implementation/offline_frames.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/pipe.h"
+#include "proto/connections_enums.pb.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+
+using ::location::nearby::proto::connections::DisconnectionReason;
+using ::location::nearby::proto::connections::Medium;
+using ::testing::_;
+using ::testing::MockFunction;
+using ::testing::Return;
+using ::testing::StrictMock;
+
+class MockEndpointChannel : public EndpointChannel {
+ public:
+ MOCK_METHOD(ExceptionOr<ByteArray>, Read, (), (override));
+ MOCK_METHOD(Exception, Write, (const ByteArray& data), (override));
+ MOCK_METHOD(void, Close, (), (override));
+ MOCK_METHOD(void, Close, (DisconnectionReason reason), (override));
+ MOCK_METHOD(proto::connections::ConnectionTechnology, GetTechnology, (),
+ (const override));
+ MOCK_METHOD(proto::connections::ConnectionBand, GetBand, (),
+ (const override));
+ MOCK_METHOD(int, GetFrequency, (), (const override));
+ MOCK_METHOD(int, GetTryCount, (), (const override));
+ MOCK_METHOD(std::string, GetType, (), (const override));
+ MOCK_METHOD(std::string, GetName, (), (const override));
+ MOCK_METHOD(Medium, GetMedium, (), (const override));
+ MOCK_METHOD(int, GetMaxTransmitPacketSize, (), (const override));
+ MOCK_METHOD(void, EnableEncryption,
+ (std::shared_ptr<EncryptionContext> context), (override));
+ MOCK_METHOD(void, DisableEncryption, (), (override));
+ MOCK_METHOD(bool, IsPaused, (), (const override));
+ MOCK_METHOD(void, Pause, (), (override));
+ MOCK_METHOD(void, Resume, (), (override));
+ MOCK_METHOD(absl::Time, GetLastReadTimestamp, (), (const override));
+ MOCK_METHOD(absl::Time, GetLastWriteTimestamp, (), (const override));
+ MOCK_METHOD(void, SetAnalyticsRecorder,
+ (analytics::AnalyticsRecorder*, const std::string&), (override));
+
+ bool IsClosed() const {
+ absl::MutexLock lock(&mutex_);
+ return closed_;
+ }
+ void DoClose() {
+ absl::MutexLock lock(&mutex_);
+ closed_ = true;
+ }
+
+ private:
+ mutable absl::Mutex mutex_;
+ bool closed_ = false;
+};
+
+class MockFrameProcessor : public EndpointManager::FrameProcessor {
+ public:
+ MOCK_METHOD(void, OnIncomingFrame,
+ (OfflineFrame & offline_frame,
+ const std::string& from_endpoint_id, ClientProxy* to_client,
+ Medium current_medium),
+ (override));
+
+ MOCK_METHOD(void, OnEndpointDisconnect,
+ (ClientProxy * client, const std::string& endpoint_id,
+ CountDownLatch barrier),
+ (override));
+};
+
+class EndpointManagerTest : public ::testing::Test {
+ protected:
+ void RegisterEndpoint(std::unique_ptr<MockEndpointChannel> channel,
+ bool should_close = true) {
+ CountDownLatch done(1);
+ if (should_close) {
+ ON_CALL(*channel, Close(_))
+ .WillByDefault(
+ [&done](DisconnectionReason reason) { done.CountDown(); });
+ }
+ EXPECT_CALL(*channel, GetMedium()).WillRepeatedly(Return(Medium::BLE));
+ EXPECT_CALL(*channel, GetLastReadTimestamp())
+ .WillRepeatedly(Return(start_time_));
+ EXPECT_CALL(*channel, GetLastWriteTimestamp())
+ .WillRepeatedly(Return(start_time_));
+ EXPECT_CALL(mock_listener_.initiated_cb, Call).Times(1);
+ em_.RegisterEndpoint(&client_, endpoint_id_, info_, connection_options_,
+ std::move(channel), listener_, connection_token);
+ if (should_close) {
+ EXPECT_TRUE(done.Await(absl::Milliseconds(1000)).result());
+ }
+ }
+
+ ClientProxy client_;
+ ConnectionOptions connection_options_{
+ .keep_alive_interval_millis = 5000,
+ .keep_alive_timeout_millis = 30000,
+ };
+ std::vector<std::unique_ptr<EndpointManager::FrameProcessor>> processors_;
+ EndpointChannelManager ecm_;
+ EndpointManager em_{&ecm_};
+ std::string endpoint_id_ = "endpoint_id";
+ ConnectionResponseInfo info_ = {
+ .remote_endpoint_info = ByteArray{"info"},
+ .authentication_token = "auth_token",
+ .raw_authentication_token = ByteArray{"auth_token"},
+ .is_incoming_connection = true,
+ };
+ struct MockConnectionListener {
+ StrictMock<MockFunction<void(const std::string& endpoint_id,
+ const ConnectionResponseInfo& info)>>
+ initiated_cb;
+ StrictMock<MockFunction<void(const std::string& endpoint_id)>> accepted_cb;
+ StrictMock<MockFunction<void(const std::string& endpoint_id,
+ const Status& status)>>
+ rejected_cb;
+ StrictMock<MockFunction<void(const std::string& endpoint_id)>>
+ disconnected_cb;
+ StrictMock<MockFunction<void(const std::string& endpoint_id,
+ std::int32_t quality)>>
+ bandwidth_changed_cb;
+ } mock_listener_;
+ ConnectionListener listener_{
+ .initiated_cb = mock_listener_.initiated_cb.AsStdFunction(),
+ .accepted_cb = mock_listener_.accepted_cb.AsStdFunction(),
+ .rejected_cb = mock_listener_.rejected_cb.AsStdFunction(),
+ .disconnected_cb = mock_listener_.disconnected_cb.AsStdFunction(),
+ .bandwidth_changed_cb =
+ mock_listener_.bandwidth_changed_cb.AsStdFunction(),
+ };
+ std::string connection_token = "conntokn";
+ absl::Time start_time_{absl::Now()};
+};
+
+TEST_F(EndpointManagerTest, ConstructorDestructorWorks) { SUCCEED(); }
+
+TEST_F(EndpointManagerTest, RegisterEndpointCallsOnConnectionInitiated) {
+ auto endpoint_channel = std::make_unique<MockEndpointChannel>();
+ EXPECT_CALL(*endpoint_channel, Read())
+ .WillRepeatedly(Return(ExceptionOr<ByteArray>(Exception::kIo)));
+ EXPECT_CALL(*endpoint_channel, Close(_)).Times(1);
+ RegisterEndpoint(std::move(endpoint_channel));
+}
+
+TEST_F(EndpointManagerTest, UnregisterEndpointCallsOnDisconnected) {
+ auto endpoint_channel = std::make_unique<MockEndpointChannel>();
+ EXPECT_CALL(*endpoint_channel, Read())
+ .WillRepeatedly(Return(ExceptionOr<ByteArray>(Exception::kIo)));
+ RegisterEndpoint(std::make_unique<MockEndpointChannel>());
+ // NOTE: disconnect_cb is not called, because we did not reach fully connected
+ // state. On top of that, UnregisterEndpoint is suppressing this notification.
+ // (IMO, it should be called as long as any connection callback was called
+ // before. (in this case initiated_cb is called)).
+ // Test captures current protocol behavior.
+ em_.UnregisterEndpoint(&client_, endpoint_id_);
+}
+
+TEST_F(EndpointManagerTest, RegisterFrameProcessorWorks) {
+ auto endpoint_channel = std::make_unique<MockEndpointChannel>();
+ auto connect_request = std::make_unique<MockFrameProcessor>();
+ ByteArray endpoint_info{"endpoint_name"};
+ auto read_data =
+ parser::ForConnectionRequest("endpoint_id", endpoint_info, 1234, false,
+ "", std::vector{Medium::BLE}, 0, 0);
+ EXPECT_CALL(*connect_request, OnIncomingFrame);
+ EXPECT_CALL(*connect_request, OnEndpointDisconnect);
+ EXPECT_CALL(*endpoint_channel, Read())
+ .WillOnce(Return(ExceptionOr<ByteArray>(read_data)))
+ .WillRepeatedly(Return(ExceptionOr<ByteArray>(Exception::kIo)));
+ EXPECT_CALL(*endpoint_channel, Write(_))
+ .WillRepeatedly(Return(Exception{Exception::kSuccess}));
+ // Register frame processor, then register endpoint.
+ // Endpoint will read one frame, then fail to read more and terminate.
+ // On disconnection, it will notify frame processor and we verify that.
+ em_.RegisterFrameProcessor(V1Frame::CONNECTION_REQUEST,
+ connect_request.get());
+ processors_.emplace_back(std::move(connect_request));
+ RegisterEndpoint(std::move(endpoint_channel));
+}
+
+TEST_F(EndpointManagerTest, UnregisterFrameProcessorWorks) {
+ auto endpoint_channel = std::make_unique<MockEndpointChannel>();
+ EXPECT_CALL(*endpoint_channel, Read())
+ .WillRepeatedly(Return(ExceptionOr<ByteArray>(Exception::kIo)));
+ EXPECT_CALL(*endpoint_channel, Write(_))
+ .WillRepeatedly(Return(Exception{Exception::kSuccess}));
+
+ // We should not receive any notifications to frame processor.
+ auto connect_request = std::make_unique<StrictMock<MockFrameProcessor>>();
+
+ // Register frame processor and immediately unregister it.
+ em_.RegisterFrameProcessor(V1Frame::CONNECTION_REQUEST,
+ connect_request.get());
+ em_.UnregisterFrameProcessor(V1Frame::CONNECTION_REQUEST,
+ connect_request.get());
+
+ processors_.emplace_back(std::move(connect_request));
+ // Endpoint will not send OnDisconnect notification to frame processor.
+ RegisterEndpoint(std::move(endpoint_channel), false);
+ em_.UnregisterEndpoint(&client_, endpoint_id_);
+}
+
+TEST_F(EndpointManagerTest, SendControlMessageWorks) {
+ auto endpoint_channel = std::make_unique<MockEndpointChannel>();
+ PayloadTransferFrame::PayloadHeader header;
+ PayloadTransferFrame::ControlMessage control;
+ header.set_id(12345);
+ header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
+ header.set_total_size(1024);
+ control.set_offset(150);
+ control.set_event(PayloadTransferFrame::ControlMessage::PAYLOAD_CANCELED);
+
+ ON_CALL(*endpoint_channel, Read())
+ .WillByDefault([channel = endpoint_channel.get()]() {
+ if (channel->IsClosed()) return ExceptionOr<ByteArray>(Exception::kIo);
+ NEARBY_LOG(INFO, "Simulate read delay: wait");
+ absl::SleepFor(absl::Milliseconds(100));
+ NEARBY_LOG(INFO, "Simulate read delay: done");
+ if (channel->IsClosed()) return ExceptionOr<ByteArray>(Exception::kIo);
+ return ExceptionOr<ByteArray>(ByteArray{});
+ });
+ ON_CALL(*endpoint_channel, Close(_))
+ .WillByDefault(
+ [channel = endpoint_channel.get()](DisconnectionReason reason) {
+ channel->DoClose();
+ NEARBY_LOG(INFO, "Channel closed");
+ });
+ EXPECT_CALL(*endpoint_channel, Write(_))
+ .WillRepeatedly(Return(Exception{Exception::kSuccess}));
+
+ RegisterEndpoint(std::move(endpoint_channel), false);
+ auto failed_ids =
+ em_.SendControlMessage(header, control, std::vector{endpoint_id_});
+ EXPECT_EQ(failed_ids, std::vector<std::string>{});
+ NEARBY_LOG(INFO, "Will unregister endpoint now");
+ em_.UnregisterEndpoint(&client_, endpoint_id_);
+ NEARBY_LOG(INFO, "Will call destructors now");
+}
+
+TEST_F(EndpointManagerTest, SingleReadOnInvalidPayload) {
+ auto endpoint_channel = std::make_unique<MockEndpointChannel>();
+ EXPECT_CALL(*endpoint_channel, Read())
+ .WillOnce(
+ Return(ExceptionOr<ByteArray>(Exception::kInvalidProtocolBuffer)));
+ EXPECT_CALL(*endpoint_channel, Write(_))
+ .WillRepeatedly(Return(Exception{Exception::kSuccess}));
+ EXPECT_CALL(*endpoint_channel, Close(_)).Times(1);
+ RegisterEndpoint(std::move(endpoint_channel));
+}
+
+} // namespace
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/injected_bluetooth_device_store.cc b/chromium/third_party/nearby/src/connections/implementation/injected_bluetooth_device_store.cc
new file mode 100644
index 00000000000..c71e3e55e3a
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/injected_bluetooth_device_store.cc
@@ -0,0 +1,90 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/injected_bluetooth_device_store.h"
+
+#include <string>
+
+#include "connections/implementation/bluetooth_device_name.h"
+#include "internal/platform/implementation/bluetooth_classic.h"
+#include "internal/platform/bluetooth_utils.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+
+// api::BluetoothDevice implementation which stores a name and address passed to
+// its constructor and trivially returns them to implement virtual functions.
+class InjectedBluetoothDevice : public api::BluetoothDevice {
+ public:
+ InjectedBluetoothDevice(const std::string& name,
+ const std::string& mac_address)
+ : name_(name), mac_address_(mac_address) {}
+
+ ~InjectedBluetoothDevice() override = default;
+
+ // api::BluetoothDevice:
+ std::string GetName() const override { return name_; }
+
+ std::string GetMacAddress() const override { return mac_address_; }
+
+ private:
+ const std::string name_;
+ const std::string mac_address_;
+};
+
+} // namespace
+
+InjectedBluetoothDeviceStore::InjectedBluetoothDeviceStore() = default;
+
+InjectedBluetoothDeviceStore::~InjectedBluetoothDeviceStore() = default;
+
+BluetoothDevice InjectedBluetoothDeviceStore::CreateInjectedBluetoothDevice(
+ const ByteArray& remote_bluetooth_mac_address,
+ const std::string& endpoint_id, const ByteArray& endpoint_info,
+ const ByteArray& service_id_hash, Pcp pcp) {
+ std::string remote_bluetooth_mac_address_str =
+ BluetoothUtils::ToString(remote_bluetooth_mac_address);
+
+ // Valid MAC address is required.
+ if (remote_bluetooth_mac_address_str.empty())
+ return BluetoothDevice(/*device=*/nullptr);
+
+ // Non-empty endpoint info is required.
+ if (endpoint_info.Empty()) return BluetoothDevice(/*device=*/nullptr);
+
+ BluetoothDeviceName name(BluetoothDeviceName::Version::kV1, pcp, endpoint_id,
+ service_id_hash, endpoint_info,
+ /*uwb_address=*/ByteArray(),
+ WebRtcState::kConnectable);
+
+ // Note: BluetoothDeviceName internally verifies that |endpoint_id| and
+ // |service_id_hash| are valid; the check below will fail if they are
+ // malformed.
+ if (!name.IsValid()) return BluetoothDevice(/*device=*/nullptr);
+
+ auto injected_device = std::make_unique<InjectedBluetoothDevice>(
+ static_cast<std::string>(name), remote_bluetooth_mac_address_str);
+ BluetoothDevice device_to_return(injected_device.get());
+
+ // Store underlying device to ensure that it is kept alive for future use.
+ devices_.emplace_back(std::move(injected_device));
+
+ return device_to_return;
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/injected_bluetooth_device_store.h b/chromium/third_party/nearby/src/connections/implementation/injected_bluetooth_device_store.h
new file mode 100644
index 00000000000..0d9a3eaff01
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/injected_bluetooth_device_store.h
@@ -0,0 +1,69 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_INJECTED_BLUETOOTH_DEVICE_STORE_H_
+#define CORE_INTERNAL_INJECTED_BLUETOOTH_DEVICE_STORE_H_
+
+#include <memory>
+#include <vector>
+
+#include "connections/implementation/pcp.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/bluetooth_adapter.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Creates and stores BluetoothDevice objects which have been "injected" (i.e.,
+// passed to Nearby Connections manually by the client instead of through the
+// normal discovery flow).
+class InjectedBluetoothDeviceStore {
+ public:
+ InjectedBluetoothDeviceStore();
+ ~InjectedBluetoothDeviceStore();
+
+ // Creates an injected BluetoothDevice given the provided parameters:
+ // |remote_bluetooth_mac_address|: A 6-byte MAC address.
+ // |endpoint_id|: A string of length 4.
+ // |endpoint_info|: A non-empty ByteArray whose length is <=131 bytes.
+ // |service_id_hash|: A ByteArray whose length is 3.
+ // |pcp|: PCP value to be used for the connection to this device.
+ //
+ // If the provided parameters are malformed or of incorrect length, this
+ // function returns an invalid BluetoothDevice. Clients should use
+ // BluetoothDevice::IsValid() with the returned device to verify that the
+ // parameters were successfully processed.
+ //
+ // Note that successfully-injected devices stay valid for the lifetime of the
+ // InjectedBluetoothDeviceStore and are not cleared until this object is
+ // deleted.
+ BluetoothDevice CreateInjectedBluetoothDevice(
+ const ByteArray& remote_bluetooth_mac_address,
+ const std::string& endpoint_id, const ByteArray& endpoint_info,
+ const ByteArray& service_id_hash, Pcp pcp);
+
+ private:
+ // Devices created by this class. BluetoothDevice objects returned by
+ // CreateInjectedBluetoothDevice() store pointers to underlying
+ // api::BluetoothDevice objects, so this maintains these underlying devices
+ // to ensure that they are not deleted before they are referenced.
+ std::vector<std::unique_ptr<api::BluetoothDevice>> devices_;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_INJECTED_BLUETOOTH_DEVICE_STORE_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/injected_bluetooth_device_store_test.cc b/chromium/third_party/nearby/src/connections/implementation/injected_bluetooth_device_store_test.cc
new file mode 100644
index 00000000000..9e8264e9c18
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/injected_bluetooth_device_store_test.cc
@@ -0,0 +1,123 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/injected_bluetooth_device_store.h"
+
+#include <array>
+
+#include "gtest/gtest.h"
+#include "connections/implementation/bluetooth_device_name.h"
+#include "internal/platform/bluetooth_utils.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/bluetooth_adapter.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+
+// Need to wrap with static_cast<char> to silence -Wc++11-narrowing issue.
+constexpr std::array<char, 6> kTestRemoteBluetoothMacAddress{
+ 0x01, 0x23, 0x45, 0x67, static_cast<char>(0x89), static_cast<char>(0xab)};
+constexpr std::array<char, 2> kTestEndpointInfo{static_cast<char>(0xcd),
+ static_cast<char>(0xef)};
+constexpr std::array<char, 3> kTestServiceIdHash{0x01, 0x23, 0x45};
+
+const char kTestEndpointId[] = "abcd";
+
+class InjectedBluetoothDeviceStoreTest : public testing::Test {
+ protected:
+ InjectedBluetoothDeviceStore store_;
+};
+
+TEST_F(InjectedBluetoothDeviceStoreTest, Success) {
+ ByteArray remote_bluetooth_mac_address(kTestRemoteBluetoothMacAddress);
+ ByteArray endpoint_info(kTestEndpointInfo);
+ ByteArray service_id_hash(kTestServiceIdHash);
+
+ BluetoothDevice device = store_.CreateInjectedBluetoothDevice(
+ remote_bluetooth_mac_address, kTestEndpointId, endpoint_info,
+ service_id_hash, Pcp::kP2pPointToPoint);
+ EXPECT_TRUE(device.IsValid());
+
+ EXPECT_EQ(BluetoothUtils::ToString(remote_bluetooth_mac_address),
+ device.GetMacAddress());
+
+ BluetoothDeviceName name(device.GetName());
+ EXPECT_TRUE(name.IsValid());
+ EXPECT_EQ(kTestEndpointId, name.GetEndpointId());
+ EXPECT_EQ(endpoint_info, name.GetEndpointInfo());
+ EXPECT_EQ(service_id_hash, name.GetServiceIdHash());
+ EXPECT_EQ(Pcp::kP2pPointToPoint, name.GetPcp());
+}
+
+TEST_F(InjectedBluetoothDeviceStoreTest, Fail_InvalidBluetoothMac) {
+ // Use address with only 1 byte.
+ ByteArray remote_bluetooth_mac_address(std::array<char, 1>{0x00});
+ ByteArray endpoint_info(kTestEndpointInfo);
+ ByteArray service_id_hash(kTestServiceIdHash);
+
+ BluetoothDevice device = store_.CreateInjectedBluetoothDevice(
+ remote_bluetooth_mac_address, kTestEndpointId, endpoint_info,
+ service_id_hash, Pcp::kP2pPointToPoint);
+ EXPECT_FALSE(device.IsValid());
+}
+
+TEST_F(InjectedBluetoothDeviceStoreTest, Fail_InvalidEndpointId) {
+ ByteArray remote_bluetooth_mac_address(kTestRemoteBluetoothMacAddress);
+ ByteArray endpoint_info(kTestEndpointInfo);
+ ByteArray service_id_hash(kTestServiceIdHash);
+
+ // Use empty endpoint ID.
+ BluetoothDevice device1 = store_.CreateInjectedBluetoothDevice(
+ remote_bluetooth_mac_address, /*endpoint_id=*/std::string(),
+ endpoint_info, service_id_hash, Pcp::kP2pPointToPoint);
+ EXPECT_FALSE(device1.IsValid());
+
+ // Use endpoint ID of wrong length.
+ const std::string too_long_endpoint_id = "abcde";
+ BluetoothDevice device2 = store_.CreateInjectedBluetoothDevice(
+ remote_bluetooth_mac_address, too_long_endpoint_id, endpoint_info,
+ service_id_hash, Pcp::kP2pPointToPoint);
+ EXPECT_FALSE(device2.IsValid());
+}
+
+TEST_F(InjectedBluetoothDeviceStoreTest, Fail_EmptyEndpointInfo) {
+ ByteArray remote_bluetooth_mac_address(kTestRemoteBluetoothMacAddress);
+ // Use empty endpoint info.
+ ByteArray endpoint_info;
+ ByteArray service_id_hash(kTestServiceIdHash);
+
+ BluetoothDevice device = store_.CreateInjectedBluetoothDevice(
+ remote_bluetooth_mac_address, kTestEndpointId, endpoint_info,
+ service_id_hash, Pcp::kP2pPointToPoint);
+ EXPECT_FALSE(device.IsValid());
+}
+
+TEST_F(InjectedBluetoothDeviceStoreTest, Fail_InvalidServiceIdHash) {
+ ByteArray remote_bluetooth_mac_address(kTestRemoteBluetoothMacAddress);
+ ByteArray endpoint_info(kTestEndpointInfo);
+ // Use address with only 1 byte.
+ ByteArray service_id_hash(std::array<char, 1>{0x00});
+
+ BluetoothDevice device = store_.CreateInjectedBluetoothDevice(
+ remote_bluetooth_mac_address, kTestEndpointId, endpoint_info,
+ service_id_hash, Pcp::kP2pPointToPoint);
+ EXPECT_FALSE(device.IsValid());
+}
+
+} // namespace
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/internal_payload.cc b/chromium/third_party/nearby/src/connections/implementation/internal_payload.cc
new file mode 100644
index 00000000000..5403f9bb8ce
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/internal_payload.cc
@@ -0,0 +1,33 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/internal_payload.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// The definition is necessary before C++17.
+constexpr int InternalPayload::kIndeterminateSize;
+
+InternalPayload::InternalPayload(Payload payload)
+ : payload_(std::move(payload)), payload_id_(payload_.GetId()) {}
+
+Payload InternalPayload::ReleasePayload() { return std::move(payload_); }
+
+Payload::Id InternalPayload::GetId() const { return payload_id_; }
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/internal_payload.h b/chromium/third_party/nearby/src/connections/implementation/internal_payload.h
new file mode 100644
index 00000000000..694e853fb60
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/internal_payload.h
@@ -0,0 +1,106 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_INTERNAL_PAYLOAD_H_
+#define CORE_INTERNAL_INTERNAL_PAYLOAD_H_
+
+#include <cstdint>
+
+#include "connections/payload.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/exception.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Defines the operations layered atop a Payload, for use inside the
+// OfflineServiceController.
+//
+// <p>There will be an extension of this abstract base class per type of
+// Payload.
+class InternalPayload {
+ public:
+ static constexpr int kIndeterminateSize = -1;
+
+ explicit InternalPayload(Payload payload);
+ virtual ~InternalPayload() = default;
+
+ Payload ReleasePayload();
+
+ Payload::Id GetId() const;
+
+ // Returns the PayloadType of the Payload to which this object is bound.
+ //
+ // <p>Note that this is supposed to return the type from the OfflineFrame
+ // proto rather than what is already available via
+ // Payload::getType().
+ //
+ // @return The PayloadType.
+ virtual PayloadTransferFrame::PayloadHeader::PayloadType GetType() const = 0;
+
+ // Deduces the total size of the Payload to which this object is bound.
+ //
+ // @return The total size, or -1 if it cannot be deduced (for example, when
+ // dealing with streaming data).
+ virtual std::int64_t GetTotalSize() const = 0;
+
+ // Breaks off the next chunk from the Payload to which this object is bound.
+ //
+ // <p>Used when we have a complete Payload that we want to break into smaller
+ // byte blobs for sending across a hard boundary (like the other side of
+ // a Binder, or another device altogether).
+ //
+ // @param chunk_size The preferred size of the next chunk. Depending on
+ // payload type, the provided size may be ignored.
+ // @return The next chunk from the Payload, or null if we've reached the end.
+ virtual ByteArray DetachNextChunk(int chunk_size) = 0;
+
+ // Adds the next chunk that comprises the Payload to which this object is
+ // bound.
+ //
+ // <p>Used when we are trying to reconstruct a Payload that lives on the
+ // other side of a hard boundary (like the other side of a Binder, or another
+ // device altogether), one byte blob at a time.
+ //
+ // @param chunk The next chunk; this being null signals that this is the last
+ // chunk, which will typically be used as a trigger to perform whatever state
+ // cleanup may be required by the concrete implementation.
+ virtual Exception AttachNextChunk(const ByteArray& chunk) = 0;
+
+ // Skips current stream pointer to the offset.
+ //
+ // Used when this is a resume outgoing transfer, so we want to skip
+ // some data until the offset position.
+ //
+ // @return the offset really skipped
+ virtual ExceptionOr<size_t> SkipToOffset(size_t offset) = 0;
+
+ // Cleans up any resources used by this Payload. Called when we're stopping
+ // early, e.g. after being cancelled or having no more recipients left.
+ virtual void Close() {}
+
+ protected:
+ Payload payload_;
+ // We're caching the payload ID here because the backing payload will be
+ // released to another owner during the lifetime of an incoming
+ // InternalPayload.
+ Payload::Id payload_id_;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_INTERNAL_PAYLOAD_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/internal_payload_factory.cc b/chromium/third_party/nearby/src/connections/implementation/internal_payload_factory.cc
new file mode 100644
index 00000000000..61699f92f2d
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/internal_payload_factory.cc
@@ -0,0 +1,350 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/internal_payload_factory.h"
+
+#include <cstdint>
+#include <memory>
+
+#include "absl/memory/memory.h"
+#include "connections/payload.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/condition_variable.h"
+#include "internal/platform/file.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/mutex.h"
+#include "internal/platform/pipe.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+namespace {
+
+class BytesInternalPayload : public InternalPayload {
+ public:
+ explicit BytesInternalPayload(Payload payload)
+ : InternalPayload(std::move(payload)),
+ total_size_(payload_.AsBytes().size()),
+ detached_only_chunk_(false) {}
+
+ PayloadTransferFrame::PayloadHeader::PayloadType GetType() const override {
+ return PayloadTransferFrame::PayloadHeader::BYTES;
+ }
+
+ std::int64_t GetTotalSize() const override { return total_size_; }
+
+ // Relinquishes ownership of the payload_; retrieves and returns the stored
+ // ByteArray.
+ ByteArray DetachNextChunk(int chunk_size) override {
+ if (detached_only_chunk_) {
+ return {};
+ }
+
+ detached_only_chunk_ = true;
+ return std::move(payload_).AsBytes();
+ }
+
+ // Does nothing.
+ Exception AttachNextChunk(const ByteArray& chunk) override {
+ return {Exception::kSuccess};
+ }
+
+ ExceptionOr<size_t> SkipToOffset(size_t offset) override {
+ NEARBY_LOGS(WARNING) << "Bytes payload does not support offsets";
+ return {Exception::kIo};
+ }
+
+ private:
+ // We're caching the total size here because the backing payload will be
+ // moved to another owner during the lifetime of an incoming
+ // InternalPayload.
+ const std::int64_t total_size_;
+ bool detached_only_chunk_;
+};
+
+class OutgoingStreamInternalPayload : public InternalPayload {
+ public:
+ explicit OutgoingStreamInternalPayload(Payload payload)
+ : InternalPayload(std::move(payload)) {}
+
+ PayloadTransferFrame::PayloadHeader::PayloadType GetType() const override {
+ return PayloadTransferFrame::PayloadHeader::STREAM;
+ }
+
+ std::int64_t GetTotalSize() const override { return -1; }
+
+ ByteArray DetachNextChunk(int chunk_size) override {
+ InputStream* input_stream = payload_.AsStream();
+ if (!input_stream) return {};
+
+ ExceptionOr<ByteArray> bytes_read = input_stream->Read(chunk_size);
+ if (!bytes_read.ok()) {
+ input_stream->Close();
+ return {};
+ }
+
+ ByteArray scoped_bytes_read = std::move(bytes_read.result());
+
+ if (scoped_bytes_read.Empty()) {
+ NEARBY_LOGS(INFO) << "No more data for outgoing payload " << this
+ << ", closing InputStream.";
+
+ input_stream->Close();
+ return {};
+ }
+
+ return scoped_bytes_read;
+ }
+
+ Exception AttachNextChunk(const ByteArray& chunk) override {
+ return {Exception::kIo};
+ }
+
+ ExceptionOr<size_t> SkipToOffset(size_t offset) override {
+ InputStream* stream = payload_.AsStream();
+ if (stream == nullptr) return {Exception::kIo};
+
+ ExceptionOr<size_t> real_offset = stream->Skip(offset);
+ if (real_offset.ok() && real_offset.GetResult() == offset) {
+ return real_offset;
+ }
+ // Close the outgoing stream on any error
+ stream->Close();
+ if (!real_offset.ok()) {
+ return real_offset;
+ }
+ NEARBY_LOGS(WARNING) << "Skip offset: " << real_offset.GetResult()
+ << ", expected offset: " << offset << " for payload "
+ << this;
+ return {Exception::kIo};
+ }
+
+ void Close() override {
+ // Ignore the potential Exception returned by close(), as a counterpart
+ // to Java's closeQuietly().
+ InputStream* stream = payload_.AsStream();
+ if (stream) stream->Close();
+ }
+};
+
+class IncomingStreamInternalPayload : public InternalPayload {
+ public:
+ IncomingStreamInternalPayload(Payload payload, OutputStream& output_stream)
+ : InternalPayload(std::move(payload)), output_stream_(&output_stream) {}
+
+ PayloadTransferFrame::PayloadHeader::PayloadType GetType() const override {
+ return PayloadTransferFrame::PayloadHeader::STREAM;
+ }
+
+ std::int64_t GetTotalSize() const override { return -1; }
+
+ ByteArray DetachNextChunk(int chunk_size) override { return {}; }
+
+ Exception AttachNextChunk(const ByteArray& chunk) override {
+ if (chunk.Empty()) {
+ NEARBY_LOGS(INFO) << "Received null last chunk for incoming payload "
+ << this << ", closing OutputStream.";
+ output_stream_->Close();
+ return {Exception::kSuccess};
+ }
+
+ return output_stream_->Write(chunk);
+ }
+
+ ExceptionOr<size_t> SkipToOffset(size_t offset) override {
+ NEARBY_LOGS(WARNING) << "Cannot skip offset for an incoming Payload "
+ << this;
+ return {Exception::kIo};
+ }
+
+ void Close() override { output_stream_->Close(); }
+
+ private:
+ OutputStream* output_stream_;
+};
+
+class OutgoingFileInternalPayload : public InternalPayload {
+ public:
+ explicit OutgoingFileInternalPayload(Payload payload)
+ : InternalPayload(std::move(payload)),
+ total_size_{payload_.AsFile()->GetTotalSize()} {}
+
+ PayloadTransferFrame::PayloadHeader::PayloadType GetType() const override {
+ return PayloadTransferFrame::PayloadHeader::FILE;
+ }
+
+ std::int64_t GetTotalSize() const override { return total_size_; }
+
+ ByteArray DetachNextChunk(int chunk_size) override {
+ InputFile* file = payload_.AsFile();
+ if (!file) return {};
+
+ ExceptionOr<ByteArray> bytes_read = file->Read(chunk_size);
+ if (!bytes_read.ok()) {
+ return {};
+ }
+
+ ByteArray bytes = std::move(bytes_read.result());
+
+ if (bytes.Empty()) {
+ // No more data for outgoing payload.
+
+ file->Close();
+ return {};
+ }
+
+ return bytes;
+ }
+
+ Exception AttachNextChunk(const ByteArray& chunk) override {
+ return {Exception::kIo};
+ }
+
+ ExceptionOr<size_t> SkipToOffset(size_t offset) override {
+ NEARBY_LOGS(INFO) << "SkipToOffset " << offset;
+ InputFile* file = payload_.AsFile();
+ if (!file) {
+ return {Exception::kIo};
+ }
+
+ ExceptionOr<size_t> real_offset = file->Skip(offset);
+ if (real_offset.ok() && real_offset.GetResult() == offset) {
+ return real_offset;
+ }
+ // Close the outgoing file on any error
+ file->Close();
+ if (!real_offset.ok()) {
+ return real_offset;
+ }
+ NEARBY_LOGS(WARNING) << "Skip offset: " << real_offset.GetResult()
+ << ", expected offset: " << offset
+ << " for file payload " << this;
+ return {Exception::kIo};
+ }
+
+ void Close() override {
+ InputFile* file = payload_.AsFile();
+ if (file) file->Close();
+ }
+
+ private:
+ std::int64_t total_size_;
+};
+
+class IncomingFileInternalPayload : public InternalPayload {
+ public:
+ IncomingFileInternalPayload(Payload payload, OutputFile output_file,
+ std::int64_t total_size)
+ : InternalPayload(std::move(payload)),
+ output_file_(std::move(output_file)),
+ total_size_(total_size) {}
+
+ PayloadTransferFrame::PayloadHeader::PayloadType GetType() const override {
+ return PayloadTransferFrame::PayloadHeader::FILE;
+ }
+
+ std::int64_t GetTotalSize() const override { return total_size_; }
+
+ ByteArray DetachNextChunk(int chunk_size) override { return {}; }
+
+ Exception AttachNextChunk(const ByteArray& chunk) override {
+ if (chunk.Empty()) {
+ // Received null last chunk for incoming payload.
+ output_file_.Close();
+ return {Exception::kSuccess};
+ }
+
+ return output_file_.Write(chunk);
+ }
+
+ ExceptionOr<size_t> SkipToOffset(size_t offset) override {
+ NEARBY_LOGS(WARNING) << "Cannot skip offset for an incoming file Payload "
+ << this;
+ return {Exception::kIo};
+ }
+
+ void Close() override { output_file_.Close(); }
+
+ private:
+ OutputFile output_file_;
+ const std::int64_t total_size_;
+};
+
+} // namespace
+
+std::unique_ptr<InternalPayload> CreateOutgoingInternalPayload(
+ Payload payload) {
+ switch (payload.GetType()) {
+ case Payload::Type::kBytes:
+ return absl::make_unique<BytesInternalPayload>(std::move(payload));
+
+ case Payload::Type::kFile: {
+ InputFile* file = payload.AsFile();
+ const PayloadId file_payload_id = file ? file->GetPayloadId() : 0;
+ const PayloadId payload_id = payload.GetId();
+ CHECK(payload_id == file_payload_id);
+ return absl::make_unique<OutgoingFileInternalPayload>(std::move(payload));
+ }
+
+ case Payload::Type::kStream:
+ return absl::make_unique<OutgoingStreamInternalPayload>(
+ std::move(payload));
+
+ default:
+ DCHECK(false); // This should never happen.
+ return {};
+ }
+}
+
+std::unique_ptr<InternalPayload> CreateIncomingInternalPayload(
+ const PayloadTransferFrame& frame) {
+ if (frame.packet_type() != PayloadTransferFrame::DATA) {
+ return {};
+ }
+
+ const Payload::Id payload_id = frame.payload_header().id();
+ switch (frame.payload_header().type()) {
+ case PayloadTransferFrame::PayloadHeader::BYTES: {
+ return absl::make_unique<BytesInternalPayload>(
+ Payload(payload_id, ByteArray(frame.payload_chunk().body())));
+ }
+
+ case PayloadTransferFrame::PayloadHeader::STREAM: {
+ auto pipe = std::make_shared<Pipe>();
+
+ return absl::make_unique<IncomingStreamInternalPayload>(
+ Payload(payload_id,
+ [pipe]() -> InputStream& {
+ return pipe->GetInputStream(); // NOLINT
+ }),
+ pipe->GetOutputStream());
+ }
+
+ case PayloadTransferFrame::PayloadHeader::FILE: {
+ std::int64_t total_size = frame.payload_header().total_size();
+ return absl::make_unique<IncomingFileInternalPayload>(
+ Payload(payload_id, InputFile(payload_id, total_size)),
+ OutputFile(payload_id), total_size);
+ }
+ default:
+ DCHECK(false); // This should never happen.
+ return {};
+ }
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/internal_payload_factory.h b/chromium/third_party/nearby/src/connections/implementation/internal_payload_factory.h
new file mode 100644
index 00000000000..abe3cb49426
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/internal_payload_factory.h
@@ -0,0 +1,37 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_INTERNAL_PAYLOAD_FACTORY_H_
+#define CORE_INTERNAL_INTERNAL_PAYLOAD_FACTORY_H_
+
+#include "connections/implementation/internal_payload.h"
+#include "connections/payload.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Creates an InternalPayload representing an outgoing Payload.
+std::unique_ptr<InternalPayload> CreateOutgoingInternalPayload(Payload payload);
+
+// Creates an InternalPayload representing an incoming Payload from a remote
+// endpoint.
+std::unique_ptr<InternalPayload> CreateIncomingInternalPayload(
+ const PayloadTransferFrame& frame);
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_INTERNAL_PAYLOAD_FACTORY_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/internal_payload_factory_test.cc b/chromium/third_party/nearby/src/connections/implementation/internal_payload_factory_test.cc
new file mode 100644
index 00000000000..7ef7bd2fea8
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/internal_payload_factory_test.cc
@@ -0,0 +1,183 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/internal_payload_factory.h"
+
+#include <string>
+#include <utility>
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "connections/implementation/proto/offline_wire_formats.pb.h"
+#include "connections/implementation/offline_frames.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/pipe.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+
+constexpr char kText[] = "data chunk";
+
+TEST(InternalPayloadFActoryTest, CanCreateIternalPayloadFromBytePayload) {
+ ByteArray data(kText);
+ std::unique_ptr<InternalPayload> internal_payload =
+ CreateOutgoingInternalPayload(Payload{data});
+ EXPECT_NE(internal_payload, nullptr);
+ Payload payload = internal_payload->ReleasePayload();
+ EXPECT_EQ(payload.AsFile(), nullptr);
+ EXPECT_EQ(payload.AsStream(), nullptr);
+ EXPECT_EQ(payload.AsBytes(), ByteArray(kText));
+}
+
+TEST(InternalPayloadFActoryTest, CanCreateIternalPayloadFromStreamPayload) {
+ auto pipe = std::make_shared<Pipe>();
+ std::unique_ptr<InternalPayload> internal_payload =
+ CreateOutgoingInternalPayload(Payload{[pipe]() -> InputStream& {
+ return pipe->GetInputStream(); // NOLINT
+ }});
+ EXPECT_NE(internal_payload, nullptr);
+ Payload payload = internal_payload->ReleasePayload();
+ EXPECT_EQ(payload.AsFile(), nullptr);
+ EXPECT_NE(payload.AsStream(), nullptr);
+ EXPECT_EQ(payload.AsBytes(), ByteArray());
+}
+
+TEST(InternalPayloadFActoryTest, CanCreateIternalPayloadFromFilePayload) {
+ Payload::Id payload_id = Payload::GenerateId();
+ std::unique_ptr<InternalPayload> internal_payload =
+ CreateOutgoingInternalPayload(
+ Payload{payload_id, InputFile(payload_id, 512)});
+ EXPECT_NE(internal_payload, nullptr);
+ Payload payload = internal_payload->ReleasePayload();
+ EXPECT_NE(payload.AsFile(), nullptr);
+ EXPECT_EQ(payload.AsStream(), nullptr);
+ EXPECT_EQ(payload.AsBytes(), ByteArray());
+ EXPECT_EQ(payload.GetId(), payload_id);
+ EXPECT_EQ(payload.AsFile()->GetPayloadId(), payload_id);
+}
+
+TEST(InternalPayloadFActoryTest, CanCreateIternalPayloadFromByteMessage) {
+ PayloadTransferFrame frame;
+ frame.set_packet_type(PayloadTransferFrame::DATA);
+ std::int64_t payload_chunk_offset = 0;
+ ByteArray data(kText);
+ PayloadTransferFrame::PayloadChunk payload_chunk;
+ payload_chunk.set_offset(payload_chunk_offset);
+ payload_chunk.set_body(std::string(std::move(data)));
+ payload_chunk.set_flags(0);
+ auto& header = *frame.mutable_payload_header();
+ header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
+ header.set_id(12345);
+ header.set_total_size(512);
+ *frame.mutable_payload_chunk() = std::move(payload_chunk);
+ std::unique_ptr<InternalPayload> internal_payload =
+ CreateIncomingInternalPayload(frame);
+ EXPECT_NE(internal_payload, nullptr);
+ Payload payload = internal_payload->ReleasePayload();
+ EXPECT_EQ(payload.AsFile(), nullptr);
+ EXPECT_EQ(payload.AsStream(), nullptr);
+ EXPECT_EQ(payload.AsBytes(), ByteArray(kText));
+}
+
+TEST(InternalPayloadFActoryTest, CanCreateIternalPayloadFromStreamMessage) {
+ PayloadTransferFrame frame;
+ frame.set_packet_type(PayloadTransferFrame::DATA);
+ auto& header = *frame.mutable_payload_header();
+ header.set_type(PayloadTransferFrame::PayloadHeader::STREAM);
+ header.set_id(12345);
+ header.set_total_size(0);
+ std::unique_ptr<InternalPayload> internal_payload =
+ CreateIncomingInternalPayload(frame);
+ EXPECT_NE(internal_payload, nullptr);
+ Payload payload = internal_payload->ReleasePayload();
+ EXPECT_EQ(payload.AsFile(), nullptr);
+ EXPECT_NE(payload.AsStream(), nullptr);
+ EXPECT_EQ(payload.AsBytes(), ByteArray());
+ EXPECT_EQ(payload.GetType(), Payload::Type::kStream);
+}
+
+TEST(InternalPayloadFActoryTest, CanCreateIternalPayloadFromFileMessage) {
+ PayloadTransferFrame frame;
+ frame.set_packet_type(PayloadTransferFrame::DATA);
+ auto& header = *frame.mutable_payload_header();
+ header.set_type(PayloadTransferFrame::PayloadHeader::FILE);
+ header.set_id(12345);
+ header.set_total_size(512);
+ std::unique_ptr<InternalPayload> internal_payload =
+ CreateIncomingInternalPayload(frame);
+ EXPECT_NE(internal_payload, nullptr);
+ Payload payload = internal_payload->ReleasePayload();
+ EXPECT_NE(payload.AsFile(), nullptr);
+ EXPECT_EQ(payload.AsStream(), nullptr);
+ EXPECT_EQ(payload.AsBytes(), ByteArray());
+ EXPECT_EQ(payload.GetType(), Payload::Type::kFile);
+ EXPECT_EQ(payload.GetId(), payload.AsFile()->GetPayloadId());
+}
+
+void CreateFileWithContents(Payload::Id payload_id, const ByteArray& contents) {
+ OutputFile file(payload_id);
+ EXPECT_TRUE(file.Write(contents).Ok());
+ EXPECT_TRUE(file.Close().Ok());
+}
+
+TEST(InternalPayloadFActoryTest,
+ SkipToOffset_FilePayloadValidOffset_SkipsOffset) {
+ ByteArray contents("0123456789");
+ constexpr size_t kOffset = 4;
+ size_t size_after_skip = contents.size() - kOffset;
+ Payload::Id payload_id = Payload::GenerateId();
+ CreateFileWithContents(payload_id, contents);
+ std::unique_ptr<InternalPayload> internal_payload =
+ CreateOutgoingInternalPayload(
+ Payload{payload_id, InputFile(payload_id, contents.size())});
+ EXPECT_NE(internal_payload, nullptr);
+
+ ExceptionOr<size_t> result = internal_payload->SkipToOffset(kOffset);
+
+ EXPECT_TRUE(result.ok());
+ EXPECT_EQ(result.GetResult(), kOffset);
+ EXPECT_EQ(internal_payload->GetTotalSize(), contents.size());
+ ByteArray contents_after_skip =
+ internal_payload->DetachNextChunk(size_after_skip);
+ EXPECT_EQ(contents_after_skip, ByteArray("456789"));
+}
+
+TEST(InternalPayloadFActoryTest,
+ SkipToOffset_StreamPayloadValidOffset_SkipsOffset) {
+ ByteArray contents("0123456789");
+ constexpr size_t kOffset = 6;
+ auto pipe = std::make_shared<Pipe>();
+ std::unique_ptr<InternalPayload> internal_payload =
+ CreateOutgoingInternalPayload(Payload{[pipe]() -> InputStream& {
+ return pipe->GetInputStream(); // NOLINT
+ }});
+ EXPECT_NE(internal_payload, nullptr);
+ pipe->GetOutputStream().Write(contents);
+
+ ExceptionOr<size_t> result = internal_payload->SkipToOffset(kOffset);
+
+ EXPECT_TRUE(result.ok());
+ EXPECT_EQ(result.GetResult(), kOffset);
+ EXPECT_EQ(internal_payload->GetTotalSize(), -1);
+ ByteArray contents_after_skip = internal_payload->DetachNextChunk(512);
+ EXPECT_EQ(contents_after_skip, ByteArray("6789"));
+}
+
+} // namespace
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/BUILD b/chromium/third_party/nearby/src/connections/implementation/mediums/BUILD
new file mode 100644
index 00000000000..3784a44191e
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/BUILD
@@ -0,0 +1,112 @@
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+licenses(["notice"])
+
+cc_library(
+ name = "mediums",
+ srcs = [
+ "ble.cc",
+ "bluetooth_classic.cc",
+ "bluetooth_radio.cc",
+ "mediums.cc",
+ "uuid.cc",
+ "webrtc_stub.cc",
+ "wifi_lan.cc",
+ ],
+ hdrs = [
+ "ble.h",
+ "bluetooth_classic.h",
+ "bluetooth_radio.h",
+ "lost_entity_tracker.h",
+ "mediums.h",
+ "uuid.h",
+ "webrtc_stub.h",
+ "wifi_lan.h",
+ ],
+ defines = ["NO_WEBRTC"],
+ visibility = [
+ "//connections/implementation:__subpackages__",
+ ],
+ deps = [
+ ":utils",
+ "//connections:core_types",
+ "//connections/implementation/mediums/ble_v2",
+ "//connections/implementation/proto:offline_wire_formats_cc_proto",
+ "//internal/platform:base",
+ "//internal/platform:cancellation_flag",
+ "//internal/platform:comm",
+ "//internal/platform:logging",
+ "//internal/platform:types",
+ "//proto/mediums:web_rtc_signaling_frames_cc_proto",
+ "@com_google_absl//absl/container:flat_hash_map",
+ "@com_google_absl//absl/container:flat_hash_set",
+ "@com_google_absl//absl/functional:bind_front",
+ "@com_google_absl//absl/strings",
+ "@com_google_absl//absl/strings:str_format",
+ "@com_google_absl//absl/time",
+ ],
+)
+
+cc_library(
+ name = "utils",
+ srcs = [
+ "utils.cc",
+ "webrtc_peer_id.cc",
+ ],
+ hdrs = [
+ "utils.h",
+ "webrtc_peer_id.h",
+ "webrtc_socket_stub.h",
+ ],
+ defines = ["NO_WEBRTC"],
+ visibility = [
+ "//connections/implementation:__pkg__",
+ "//connections/implementation/mediums:__pkg__",
+ "//connections/implementation/mediums/webrtc:__pkg__",
+ ],
+ deps = [
+ "//connections/implementation/proto:offline_wire_formats_cc_proto",
+ "//internal/platform:base",
+ "//internal/platform:types",
+ "@com_google_absl//absl/strings",
+ ],
+)
+
+cc_test(
+ name = "core_internal_mediums_test",
+ size = "small",
+ srcs = [
+ "ble_test.cc",
+ "bluetooth_classic_test.cc",
+ "bluetooth_radio_test.cc",
+ "lost_entity_tracker_test.cc",
+ "uuid_test.cc",
+ "wifi_lan_test.cc",
+ ],
+ defines = ["NO_WEBRTC"],
+ shard_count = 16,
+ deps = [
+ ":mediums",
+ ":utils",
+ "//internal/platform:base",
+ "//internal/platform:comm",
+ "//internal/platform:test_util",
+ "//internal/platform:types",
+ "//internal/platform/implementation/g3", # build_cleaner: keep
+ "@com_github_protobuf_matchers//protobuf-matchers",
+ "@com_google_absl//absl/strings",
+ "@com_google_absl//absl/time",
+ "@com_google_googletest//:gtest_main",
+ ],
+)
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/BUILD.bazel b/chromium/third_party/nearby/src/connections/implementation/mediums/BUILD.bazel
new file mode 100644
index 00000000000..844b07d1ef0
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/BUILD.bazel
@@ -0,0 +1,113 @@
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+licenses(["notice"])
+
+cc_library(
+ name = "mediums",
+ srcs = [
+ "ble.cc",
+ "bluetooth_classic.cc",
+ "bluetooth_radio.cc",
+ "mediums.cc",
+ "uuid.cc",
+ "webrtc_stub.cc",
+ "wifi_lan.cc",
+ ],
+ hdrs = [
+ "ble.h",
+ "bluetooth_classic.h",
+ "bluetooth_radio.h",
+ "lost_entity_tracker.h",
+ "mediums.h",
+ "uuid.h",
+ "webrtc_stub.h",
+ "wifi_lan.h",
+ ],
+ compatible_with = ["//buildenv/target:non_prod"],
+ defines = ["NO_WEBRTC"],
+ visibility = [
+ "//third_party/nearby/connections/implementation:__subpackages__",
+ ],
+ deps = [
+ ":utils",
+ "//third_party/absl/container:flat_hash_map",
+ "//third_party/absl/container:flat_hash_set",
+ "//third_party/absl/functional:bind_front",
+ "//third_party/absl/strings",
+ "//third_party/absl/strings:str_format",
+ "//third_party/absl/time",
+ "//third_party/nearby/connections/implementation/proto:offline_wire_formats_portable_proto",
+ "//third_party/nearby/connections:core_types",
+ "//third_party/nearby/connections/implementation/mediums/ble_v2",
+ "//third_party/nearby/internal/platform:base",
+ "//third_party/nearby/internal/platform:cancellation_flag",
+ "//third_party/nearby/internal/platform:comm",
+ "//third_party/nearby/internal/platform:logging",
+ "//third_party/nearby/internal/platform:types",
+ "//third_party/nearby/proto/mediums:web_rtc_signaling_frames_cc_proto",
+ ],
+)
+
+cc_library(
+ name = "utils",
+ srcs = [
+ "utils.cc",
+ "webrtc_peer_id.cc",
+ ],
+ hdrs = [
+ "utils.h",
+ "webrtc_peer_id.h",
+ "webrtc_socket_stub.h",
+ ],
+ compatible_with = ["//buildenv/target:non_prod"],
+ defines = ["NO_WEBRTC"],
+ visibility = [
+ "//third_party/nearby/connections/implementation:__pkg__",
+ "//third_party/nearby/connections/implementation/mediums:__pkg__",
+ ],
+ deps = [
+ "//third_party/absl/strings",
+ "//third_party/nearby/connections/implementation/proto:offline_wire_formats_portable_proto",
+ "//third_party/nearby/internal/platform:base",
+ "//third_party/nearby/internal/platform:types",
+ ],
+)
+
+cc_test(
+ name = "core_internal_mediums_test",
+ size = "small",
+ srcs = [
+ "ble_test.cc",
+ "bluetooth_classic_test.cc",
+ "bluetooth_radio_test.cc",
+ "lost_entity_tracker_test.cc",
+ "uuid_test.cc",
+ "webrtc_peer_id_test.cc",
+ "wifi_lan_test.cc",
+ ],
+ defines = ["NO_WEBRTC"],
+ shard_count = 16,
+ deps = [
+ ":mediums",
+ ":utils",
+ "//testing/base/public:gunit_main",
+ "//third_party/absl/strings",
+ "//third_party/absl/time",
+ "//third_party/nearby/internal/platform:base",
+ "//third_party/nearby/internal/platform:test_util",
+ "//third_party/nearby/internal/platform/implementation/g3", # build_cleaner: keep
+ "//third_party/nearby/internal/platform:comm",
+ "//third_party/nearby/internal/platform:types",
+ ],
+)
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/ble.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/ble.cc
new file mode 100644
index 00000000000..5e1fe879c02
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/ble.cc
@@ -0,0 +1,361 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/ble.h"
+
+#include <memory>
+#include <string>
+#include <utility>
+
+#include "absl/strings/escaping.h"
+#include "connections/implementation/mediums/ble_v2/ble_advertisement.h"
+#include "connections/implementation/mediums/utils.h"
+#include "internal/platform/prng.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/mutex_lock.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+ByteArray Ble::GenerateHash(const std::string& source, size_t size) {
+ return Utils::Sha256Hash(source, size);
+}
+
+ByteArray Ble::GenerateDeviceToken() {
+ return Utils::Sha256Hash(std::to_string(Prng().NextUint32()),
+ mediums::BleAdvertisement::kDeviceTokenLength);
+}
+
+Ble::Ble(BluetoothRadio& radio) : radio_(radio) {}
+
+bool Ble::IsAvailable() const {
+ MutexLock lock(&mutex_);
+
+ return IsAvailableLocked();
+}
+
+bool Ble::IsAvailableLocked() const { return medium_.IsValid(); }
+
+bool Ble::StartAdvertising(const std::string& service_id,
+ const ByteArray& advertisement_bytes,
+ const std::string& fast_advertisement_service_uuid) {
+ MutexLock lock(&mutex_);
+
+ if (advertisement_bytes.Empty()) {
+ NEARBY_LOGS(INFO)
+ << "Refusing to turn on BLE advertising. Empty advertisement data.";
+ return false;
+ }
+
+ if (advertisement_bytes.size() > kMaxAdvertisementLength) {
+ NEARBY_LOG(INFO,
+ "Refusing to start BLE advertising because the advertisement "
+ "was too long. Expected at most %d bytes but received %d.",
+ kMaxAdvertisementLength, advertisement_bytes.size());
+ return false;
+ }
+
+ if (IsAdvertisingLocked(service_id)) {
+ NEARBY_LOGS(INFO)
+ << "Failed to BLE advertise because we're already advertising.";
+ return false;
+ }
+
+ if (!radio_.IsEnabled()) {
+ NEARBY_LOGS(INFO)
+ << "Can't start BLE scanning because Bluetooth was never turned on";
+ return false;
+ }
+
+ if (!IsAvailableLocked()) {
+ NEARBY_LOGS(INFO) << "Can't turn on BLE advertising. BLE is not available.";
+ return false;
+ }
+
+ NEARBY_LOGS(INFO) << "Turning on BLE advertising (advertisement size="
+ << advertisement_bytes.size() << ")"
+ << ", service id=" << service_id
+ << ", fast advertisement service uuid="
+ << fast_advertisement_service_uuid;
+
+ // Wrap the connections advertisement to the medium advertisement.
+ const bool fast_advertisement = !fast_advertisement_service_uuid.empty();
+ ByteArray service_id_hash{GenerateHash(
+ service_id, mediums::BleAdvertisement::kServiceIdHashLength)};
+ ByteArray medium_advertisement_bytes{mediums::BleAdvertisement{
+ mediums::BleAdvertisement::Version::kV2,
+ mediums::BleAdvertisement::SocketVersion::kV2,
+ fast_advertisement ? ByteArray{} : service_id_hash, advertisement_bytes,
+ GenerateDeviceToken()}};
+ if (medium_advertisement_bytes.Empty()) {
+ NEARBY_LOGS(INFO) << "Failed to BLE advertise because we could not "
+ "create a medium advertisement.";
+ return false;
+ }
+
+ if (!medium_.StartAdvertising(service_id, medium_advertisement_bytes,
+ fast_advertisement_service_uuid)) {
+ NEARBY_LOGS(ERROR)
+ << "Failed to turn on BLE advertising with advertisement bytes="
+ << absl::BytesToHexString(advertisement_bytes.data())
+ << ", size=" << advertisement_bytes.size()
+ << ", fast advertisement service uuid="
+ << fast_advertisement_service_uuid;
+ return false;
+ }
+
+ advertising_info_.Add(service_id);
+ return true;
+}
+
+bool Ble::StopAdvertising(const std::string& service_id) {
+ MutexLock lock(&mutex_);
+
+ if (!IsAdvertisingLocked(service_id)) {
+ NEARBY_LOGS(INFO) << "Can't turn off BLE advertising; it is already off";
+ return false;
+ }
+
+ NEARBY_LOGS(INFO) << "Turned off BLE advertising with service id="
+ << service_id;
+ bool ret = medium_.StopAdvertising(service_id);
+ // Reset our bundle of advertising state to mark that we're no longer
+ // advertising.
+ advertising_info_.Remove(service_id);
+ return ret;
+}
+
+bool Ble::IsAdvertising(const std::string& service_id) {
+ MutexLock lock(&mutex_);
+
+ return IsAdvertisingLocked(service_id);
+}
+
+bool Ble::IsAdvertisingLocked(const std::string& service_id) {
+ return advertising_info_.Existed(service_id);
+}
+
+bool Ble::StartScanning(const std::string& service_id,
+ const std::string& fast_advertisement_service_uuid,
+ DiscoveredPeripheralCallback callback) {
+ MutexLock lock(&mutex_);
+
+ discovered_peripheral_callback_ = std::move(callback);
+
+ if (service_id.empty()) {
+ NEARBY_LOGS(INFO)
+ << "Refusing to start BLE scanning with empty service id.";
+ return false;
+ }
+
+ if (IsScanningLocked(service_id)) {
+ NEARBY_LOGS(INFO) << "Refusing to start scan of BLE peripherals because "
+ "another scanning is already in-progress.";
+ return false;
+ }
+
+ if (!radio_.IsEnabled()) {
+ NEARBY_LOGS(INFO)
+ << "Can't start BLE scanning because Bluetooth was never turned on";
+ return false;
+ }
+
+ if (!IsAvailableLocked()) {
+ NEARBY_LOGS(INFO)
+ << "Can't scan BLE peripherals because BLE isn't available.";
+ return false;
+ }
+
+ if (!medium_.StartScanning(
+ service_id, fast_advertisement_service_uuid,
+ {
+ .peripheral_discovered_cb =
+ [this](BlePeripheral& peripheral,
+ const std::string& service_id,
+ const ByteArray& medium_advertisement_bytes,
+ bool fast_advertisement) {
+ // Don't bother trying to parse zero byte advertisements.
+ if (medium_advertisement_bytes.size() == 0) {
+ NEARBY_LOGS(INFO) << "Skipping zero byte advertisement "
+ << "with service_id: " << service_id;
+ return;
+ }
+ // Unwrap connection BleAdvertisement from medium
+ // BleAdvertisement.
+ auto connection_advertisement_bytes =
+ UnwrapAdvertisementBytes(medium_advertisement_bytes);
+ discovered_peripheral_callback_.peripheral_discovered_cb(
+ peripheral, service_id, connection_advertisement_bytes,
+ fast_advertisement);
+ },
+ .peripheral_lost_cb =
+ [this](BlePeripheral& peripheral,
+ const std::string& service_id) {
+ discovered_peripheral_callback_.peripheral_lost_cb(
+ peripheral, service_id);
+ },
+ })) {
+ NEARBY_LOGS(INFO) << "Failed to start scan of BLE services.";
+ return false;
+ }
+
+ NEARBY_LOGS(INFO) << "Turned on BLE scanning with service id=" << service_id;
+ // Mark the fact that we're currently performing a BLE discovering.
+ scanning_info_.Add(service_id);
+ return true;
+}
+
+bool Ble::StopScanning(const std::string& service_id) {
+ MutexLock lock(&mutex_);
+
+ if (!IsScanningLocked(service_id)) {
+ NEARBY_LOGS(INFO) << "Can't turn off BLE sacanning because we never "
+ "started scanning.";
+ return false;
+ }
+
+ NEARBY_LOG(INFO, "Turned off BLE scanning with service id=%s",
+ service_id.c_str());
+ bool ret = medium_.StopScanning(service_id);
+ scanning_info_.Clear();
+ return ret;
+}
+
+bool Ble::IsScanning(const std::string& service_id) {
+ MutexLock lock(&mutex_);
+
+ return IsScanningLocked(service_id);
+}
+
+bool Ble::IsScanningLocked(const std::string& service_id) {
+ return scanning_info_.Existed(service_id);
+}
+
+bool Ble::StartAcceptingConnections(const std::string& service_id,
+ AcceptedConnectionCallback callback) {
+ MutexLock lock(&mutex_);
+
+ if (service_id.empty()) {
+ NEARBY_LOGS(INFO)
+ << "Refusing to start accepting BLE connections with empty service id.";
+ return false;
+ }
+
+ if (IsAcceptingConnectionsLocked(service_id)) {
+ NEARBY_LOGS(INFO)
+ << "Refusing to start accepting BLE connections for " << service_id
+ << " because another BLE peripheral socket is already in-progress.";
+ return false;
+ }
+
+ if (!radio_.IsEnabled()) {
+ NEARBY_LOGS(INFO) << "Can't start accepting BLE connections for "
+ << service_id << " because Bluetooth isn't enabled.";
+ return false;
+ }
+
+ if (!IsAvailableLocked()) {
+ NEARBY_LOGS(INFO) << "Can't start accepting BLE connections for "
+ << service_id << " because BLE isn't available.";
+ return false;
+ }
+
+ if (!medium_.StartAcceptingConnections(service_id, callback)) {
+ NEARBY_LOGS(INFO) << "Failed to accept connections callback for "
+ << service_id << " .";
+ return false;
+ }
+
+ accepting_connections_info_.Add(service_id);
+ return true;
+}
+
+bool Ble::StopAcceptingConnections(const std::string& service_id) {
+ MutexLock lock(&mutex_);
+
+ if (!IsAcceptingConnectionsLocked(service_id)) {
+ NEARBY_LOGS(INFO)
+ << "Can't stop accepting BLE connections because it was never started.";
+ return false;
+ }
+
+ bool ret = medium_.StopAcceptingConnections(service_id);
+ // Reset our bundle of accepting connections state to mark that we're no
+ // longer accepting connections.
+ accepting_connections_info_.Remove(service_id);
+ return ret;
+}
+
+bool Ble::IsAcceptingConnections(const std::string& service_id) {
+ MutexLock lock(&mutex_);
+
+ return IsAcceptingConnectionsLocked(service_id);
+}
+
+bool Ble::IsAcceptingConnectionsLocked(const std::string& service_id) {
+ return accepting_connections_info_.Existed(service_id);
+}
+
+BleSocket Ble::Connect(BlePeripheral& peripheral, const std::string& service_id,
+ CancellationFlag* cancellation_flag) {
+ MutexLock lock(&mutex_);
+ NEARBY_LOGS(INFO) << "BLE::Connect: service=" << &peripheral;
+ // Socket to return. To allow for NRVO to work, it has to be a single object.
+ BleSocket socket;
+
+ if (service_id.empty()) {
+ NEARBY_LOGS(INFO) << "Refusing to create BLE socket with empty service_id.";
+ return socket;
+ }
+
+ if (!radio_.IsEnabled()) {
+ NEARBY_LOGS(INFO) << "Can't create client BLE socket to " << &peripheral
+ << " because Bluetooth isn't enabled.";
+ return socket;
+ }
+
+ if (!IsAvailableLocked()) {
+ NEARBY_LOGS(INFO) << "Can't create client BLE socket [service_id="
+ << service_id << "]; BLE isn't available.";
+ return socket;
+ }
+
+ if (cancellation_flag->Cancelled()) {
+ NEARBY_LOGS(INFO) << "Can't create client BLE socket due to cancel.";
+ return socket;
+ }
+
+ socket = medium_.Connect(peripheral, service_id, cancellation_flag);
+ if (!socket.IsValid()) {
+ NEARBY_LOGS(INFO) << "Failed to Connect via BLE [service=" << service_id
+ << "]";
+ }
+
+ return socket;
+}
+
+ByteArray Ble::UnwrapAdvertisementBytes(
+ const ByteArray& medium_advertisement_data) {
+ mediums::BleAdvertisement medium_ble_advertisement{medium_advertisement_data};
+ if (!medium_ble_advertisement.IsValid()) {
+ return ByteArray{};
+ }
+
+ return medium_ble_advertisement.GetData();
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/ble.h b/chromium/third_party/nearby/src/connections/implementation/mediums/ble.h
new file mode 100644
index 00000000000..83f0f0f7a88
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/ble.h
@@ -0,0 +1,188 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MEDIUMS_BLE_H_
+#define CORE_INTERNAL_MEDIUMS_BLE_H_
+
+#include <cstdint>
+#include <string>
+
+#include "absl/container/flat_hash_map.h"
+#include "absl/container/flat_hash_set.h"
+#include "connections/implementation/mediums/bluetooth_radio.h"
+#include "connections/listeners.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/cancellation_flag.h"
+#include "internal/platform/ble.h"
+#include "internal/platform/multi_thread_executor.h"
+#include "internal/platform/mutex.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+class Ble {
+ public:
+ using DiscoveredPeripheralCallback = BleMedium::DiscoveredPeripheralCallback;
+ using AcceptedConnectionCallback = BleMedium::AcceptedConnectionCallback;
+
+ explicit Ble(BluetoothRadio& bluetooth_radio);
+ ~Ble() = default;
+
+ // Returns true, if Ble communications are supported by a platform.
+ bool IsAvailable() const ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Sets custom advertisement data, and then enables Ble advertising.
+ // Returns true, if data is successfully set, and false otherwise.
+ bool StartAdvertising(const std::string& service_id,
+ const ByteArray& advertisement_bytes,
+ const std::string& fast_advertisement_service_uuid)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Disables Ble advertising.
+ bool StopAdvertising(const std::string& service_id)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ bool IsAdvertising(const std::string& service_id) ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Enables Ble scanning mode. Will report any discoverable peripherals in
+ // range through a callback. Returns true, if scanning mode was enabled,
+ // false otherwise.
+ bool StartScanning(const std::string& service_id,
+ const std::string& fast_advertisement_service_uuid,
+ DiscoveredPeripheralCallback callback)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Disables Ble discovery mode.
+ bool StopScanning(const std::string& service_id) ABSL_LOCKS_EXCLUDED(mutex_);
+
+ bool IsScanning(const std::string& service_id) ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Starts a worker thread, creates a Ble socket, associates it with a
+ // service id.
+ bool StartAcceptingConnections(const std::string& service_id,
+ AcceptedConnectionCallback callback)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Closes socket corresponding to a service id.
+ bool StopAcceptingConnections(const std::string& service_id)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ bool IsAcceptingConnections(const std::string& service_id)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns true if this object owns a valid platform implementation.
+ bool IsMediumValid() const ABSL_LOCKS_EXCLUDED(mutex_) {
+ MutexLock lock(&mutex_);
+ return medium_.IsValid();
+ }
+
+ // Returns true if this object has a valid BluetoothAdapter reference.
+ bool IsAdapterValid() const ABSL_LOCKS_EXCLUDED(mutex_) {
+ MutexLock lock(&mutex_);
+ return adapter_.IsValid();
+ }
+
+ // Establishes connection to Ble peripheral that was might be started on
+ // another peripheral with StartAcceptingConnections() using the same
+ // service_id. Blocks until connection is established, or server-side is
+ // terminated. Returns socket instance. On success, BleSocket.IsValid() return
+ // true.
+ BleSocket Connect(BlePeripheral& peripheral, const std::string& service_id,
+ CancellationFlag* cancellation_flag)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ private:
+ struct AdvertisingInfo {
+ bool Empty() const { return service_ids.empty(); }
+ void Clear() { service_ids.clear(); }
+ void Add(const std::string& service_id) { service_ids.emplace(service_id); }
+ void Remove(const std::string& service_id) {
+ service_ids.erase(service_id);
+ }
+ bool Existed(const std::string& service_id) const {
+ return service_ids.contains(service_id);
+ }
+
+ absl::flat_hash_set<std::string> service_ids;
+ };
+
+ struct ScanningInfo {
+ bool Empty() const { return service_ids.empty(); }
+ void Clear() { service_ids.clear(); }
+ void Add(const std::string& service_id) { service_ids.emplace(service_id); }
+ void Remove(const std::string& service_id) {
+ service_ids.erase(service_id);
+ }
+ bool Existed(const std::string& service_id) const {
+ return service_ids.contains(service_id);
+ }
+
+ absl::flat_hash_set<std::string> service_ids;
+ };
+
+ struct AcceptingConnectionsInfo {
+ bool Empty() const { return service_ids.empty(); }
+ void Clear() { service_ids.clear(); }
+ void Add(const std::string& service_id) { service_ids.emplace(service_id); }
+ void Remove(const std::string& service_id) {
+ service_ids.erase(service_id);
+ }
+ bool Existed(const std::string& service_id) const {
+ return service_ids.contains(service_id);
+ }
+
+ absl::flat_hash_set<std::string> service_ids;
+ };
+
+ static constexpr int kMaxAdvertisementLength = 512;
+
+ static ByteArray GenerateHash(const std::string& source, size_t size);
+ static ByteArray GenerateDeviceToken();
+
+ // Same as IsAvailable(), but must be called with mutex_ held.
+ bool IsAvailableLocked() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Same as IsAdvertising(), but must be called with mutex_ held.
+ bool IsAdvertisingLocked(const std::string& service_id)
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Same as IsDiscovering(), but must be called with mutex_ held.
+ bool IsScanningLocked(const std::string& service_id)
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Same as IsAcceptingConnections(), but must be called with mutex_ held.
+ bool IsAcceptingConnectionsLocked(const std::string& service_id)
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Extract connection advertisement from medium advertisement.
+ ByteArray UnwrapAdvertisementBytes(
+ const ByteArray& medium_advertisement_data);
+
+ mutable Mutex mutex_;
+ BluetoothRadio& radio_ ABSL_GUARDED_BY(mutex_);
+ BluetoothAdapter& adapter_ ABSL_GUARDED_BY(mutex_){
+ radio_.GetBluetoothAdapter()};
+ BleMedium medium_ ABSL_GUARDED_BY(mutex_){adapter_};
+ AdvertisingInfo advertising_info_ ABSL_GUARDED_BY(mutex_);
+ ScanningInfo scanning_info_ ABSL_GUARDED_BY(mutex_);
+ DiscoveredPeripheralCallback discovered_peripheral_callback_;
+ AcceptingConnectionsInfo accepting_connections_info_ ABSL_GUARDED_BY(mutex_);
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MEDIUMS_BLE_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/ble_test.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_test.cc
new file mode 100644
index 00000000000..17f53df2d3b
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_test.cc
@@ -0,0 +1,264 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/ble.h"
+
+#include <string>
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "connections/implementation/mediums/bluetooth_radio.h"
+#include "internal/platform/medium_environment.h"
+#include "internal/platform/ble.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+
+using FeatureFlags = FeatureFlags::Flags;
+
+constexpr FeatureFlags kTestCases[] = {
+ FeatureFlags{
+ .enable_cancellation_flag = true,
+ },
+ FeatureFlags{
+ .enable_cancellation_flag = false,
+ },
+};
+
+constexpr absl::Duration kWaitDuration = absl::Milliseconds(1000);
+constexpr absl::string_view kServiceID{"com.google.location.nearby.apps.test"};
+constexpr absl::string_view kAdvertisementString{"\x0a\x0b\x0c\x0d"};
+constexpr absl::string_view kFastAdvertisementServiceUuid{"\xf3\xfe"};
+
+class BleTest : public ::testing::TestWithParam<FeatureFlags> {
+ protected:
+ using DiscoveredPeripheralCallback = BleMedium::DiscoveredPeripheralCallback;
+
+ BleTest() { env_.Stop(); }
+
+ MediumEnvironment& env_{MediumEnvironment::Instance()};
+};
+
+TEST_P(BleTest, CanStartAcceptingConnectionsAndConnect) {
+ FeatureFlags feature_flags = GetParam();
+ env_.SetFeatureFlags(feature_flags);
+ env_.Start();
+ BluetoothRadio radio_a;
+ BluetoothRadio radio_b;
+ Ble ble_a{radio_a};
+ Ble ble_b{radio_b};
+ radio_a.Enable();
+ radio_b.Enable();
+ std::string service_id(kServiceID);
+ ByteArray advertisement_bytes{std::string(kAdvertisementString)};
+ std::string fast_advertisement_service_uuid(kFastAdvertisementServiceUuid);
+ CountDownLatch found_latch(1);
+ CountDownLatch accept_latch(1);
+
+ ble_a.StartAdvertising(service_id, advertisement_bytes,
+ fast_advertisement_service_uuid);
+ ble_a.StartAcceptingConnections(
+ service_id,
+ {
+ .accepted_cb = [&accept_latch](
+ BleSocket socket,
+ const std::string&) { accept_latch.CountDown(); },
+ });
+ BlePeripheral discovered_peripheral;
+ ble_b.StartScanning(
+ service_id, fast_advertisement_service_uuid,
+ {
+ .peripheral_discovered_cb =
+ [&found_latch, &discovered_peripheral](
+ BlePeripheral& peripheral, const std::string& service_id,
+ const ByteArray& advertisement_bytes,
+ bool fast_advertisement) {
+ discovered_peripheral = peripheral;
+ NEARBY_LOG(
+ INFO,
+ "Discovered peripheral=%p [impl=%p], fast advertisement=%d",
+ &peripheral, &peripheral.GetImpl(), fast_advertisement);
+ found_latch.CountDown();
+ },
+ });
+
+ EXPECT_TRUE(found_latch.Await(kWaitDuration).result());
+ ASSERT_TRUE(discovered_peripheral.IsValid());
+ CancellationFlag flag;
+ BleSocket socket = ble_b.Connect(discovered_peripheral, service_id, &flag);
+ EXPECT_TRUE(accept_latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(socket.IsValid());
+ ble_b.StopScanning(service_id);
+ ble_a.StopAdvertising(service_id);
+ env_.Stop();
+}
+
+TEST_P(BleTest, CanCancelConnect) {
+ FeatureFlags feature_flags = GetParam();
+ env_.SetFeatureFlags(feature_flags);
+ env_.Start();
+ BluetoothRadio radio_a;
+ BluetoothRadio radio_b;
+ Ble ble_a{radio_a};
+ Ble ble_b{radio_b};
+ radio_a.Enable();
+ radio_b.Enable();
+ std::string service_id(kServiceID);
+ ByteArray advertisement_bytes{std::string(kAdvertisementString)};
+ std::string fast_advertisement_service_uuid(kFastAdvertisementServiceUuid);
+ CountDownLatch found_latch(1);
+ CountDownLatch accept_latch(1);
+
+ ble_a.StartAdvertising(service_id, advertisement_bytes,
+ fast_advertisement_service_uuid);
+ ble_a.StartAcceptingConnections(
+ service_id,
+ {
+ .accepted_cb = [&accept_latch](
+ BleSocket socket,
+ const std::string&) { accept_latch.CountDown(); },
+ });
+ BlePeripheral discovered_peripheral;
+ ble_b.StartScanning(
+ service_id, fast_advertisement_service_uuid,
+ {
+ .peripheral_discovered_cb =
+ [&found_latch, &discovered_peripheral](
+ BlePeripheral& peripheral, const std::string& service_id,
+ const ByteArray& advertisement_bytes,
+ bool fast_advertisement) {
+ discovered_peripheral = peripheral;
+ NEARBY_LOG(
+ INFO,
+ "Discovered peripheral=%p [impl=%p], fast advertisement=%d",
+ &peripheral, &peripheral.GetImpl(), fast_advertisement);
+ found_latch.CountDown();
+ },
+ });
+
+ EXPECT_TRUE(found_latch.Await(kWaitDuration).result());
+ ASSERT_TRUE(discovered_peripheral.IsValid());
+ CancellationFlag flag(true);
+ BleSocket socket = ble_b.Connect(discovered_peripheral, service_id, &flag);
+ // If FeatureFlag is disabled, Cancelled is false as no-op.
+ if (!feature_flags.enable_cancellation_flag) {
+ EXPECT_TRUE(accept_latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(socket.IsValid());
+ } else {
+ EXPECT_FALSE(accept_latch.Await(kWaitDuration).result());
+ EXPECT_FALSE(socket.IsValid());
+ }
+ ble_b.StopScanning(service_id);
+ ble_a.StopAdvertising(service_id);
+ env_.Stop();
+}
+
+INSTANTIATE_TEST_SUITE_P(ParametrisedBleTest, BleTest,
+ ::testing::ValuesIn(kTestCases));
+
+TEST_F(BleTest, CanConstructValidObject) {
+ env_.Start();
+ BluetoothRadio radio_a;
+ BluetoothRadio radio_b;
+ Ble ble_a{radio_a};
+ Ble ble_b{radio_b};
+
+ EXPECT_TRUE(ble_a.IsMediumValid());
+ EXPECT_TRUE(ble_a.IsAdapterValid());
+ EXPECT_TRUE(ble_a.IsAvailable());
+ EXPECT_TRUE(ble_b.IsMediumValid());
+ EXPECT_TRUE(ble_b.IsAdapterValid());
+ EXPECT_TRUE(ble_b.IsAvailable());
+ EXPECT_NE(&radio_a.GetBluetoothAdapter(), &radio_b.GetBluetoothAdapter());
+ env_.Stop();
+}
+
+TEST_F(BleTest, CanStartAdvertising) {
+ env_.Start();
+ BluetoothRadio radio_a;
+ BluetoothRadio radio_b;
+ Ble ble_a{radio_a};
+ Ble ble_b{radio_b};
+ radio_a.Enable();
+ radio_b.Enable();
+ std::string service_id(kServiceID);
+ ByteArray advertisement_bytes{std::string(kAdvertisementString)};
+ std::string fast_advertisement_service_uuid(kFastAdvertisementServiceUuid);
+ CountDownLatch found_latch(1);
+
+ ble_b.StartScanning(
+ service_id, fast_advertisement_service_uuid,
+ DiscoveredPeripheralCallback{
+ .peripheral_discovered_cb =
+ [&found_latch](
+ BlePeripheral& peripheral, const std::string& service_id,
+ const ByteArray& advertisement_bytes,
+ bool fast_advertisement) { found_latch.CountDown(); },
+ });
+
+ EXPECT_TRUE(ble_a.StartAdvertising(service_id, advertisement_bytes,
+ fast_advertisement_service_uuid));
+ EXPECT_TRUE(found_latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(ble_a.StopAdvertising(service_id));
+ EXPECT_TRUE(ble_b.StopScanning(service_id));
+ env_.Stop();
+}
+
+TEST_F(BleTest, CanStartDiscovery) {
+ env_.Start();
+ BluetoothRadio radio_a;
+ BluetoothRadio radio_b;
+ Ble ble_a{radio_a};
+ Ble ble_b{radio_b};
+ radio_a.Enable();
+ radio_b.Enable();
+ std::string service_id(kServiceID);
+ ByteArray advertisement_bytes{std::string(kAdvertisementString)};
+ std::string fast_advertisement_service_uuid(kFastAdvertisementServiceUuid);
+ CountDownLatch accept_latch(1);
+ CountDownLatch lost_latch(1);
+
+ ble_b.StartAdvertising(service_id, advertisement_bytes,
+ fast_advertisement_service_uuid);
+
+ EXPECT_TRUE(ble_a.StartScanning(
+ service_id, fast_advertisement_service_uuid,
+ DiscoveredPeripheralCallback{
+ .peripheral_discovered_cb =
+ [&accept_latch](
+ BlePeripheral& peripheral, const std::string& service_id,
+ const ByteArray& advertisement_bytes,
+ bool fast_advertisement) { accept_latch.CountDown(); },
+ .peripheral_lost_cb =
+ [&lost_latch](BlePeripheral& peripheral,
+ const std::string& service_id) {
+ lost_latch.CountDown();
+ },
+ }));
+ EXPECT_TRUE(accept_latch.Await(kWaitDuration).result());
+ ble_b.StopAdvertising(service_id);
+ EXPECT_TRUE(lost_latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(ble_a.StopScanning(service_id));
+ env_.Stop();
+}
+
+} // namespace
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/BUILD b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/BUILD
new file mode 100644
index 00000000000..5044fb84bee
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/BUILD
@@ -0,0 +1,72 @@
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+licenses(["notice"])
+
+cc_library(
+ name = "ble_v2",
+ srcs = [
+ "advertisement_read_result.cc",
+ "ble_advertisement.cc",
+ "ble_advertisement_header.cc",
+ "ble_packet.cc",
+ "bloom_filter.cc",
+ ],
+ hdrs = [
+ "advertisement_read_result.h",
+ "ble_advertisement.h",
+ "ble_advertisement_header.h",
+ "ble_packet.h",
+ "ble_peripheral.h",
+ "bloom_filter.h",
+ "discovered_peripheral_callback.h",
+ ],
+ copts = ["-DCORE_ADAPTER_DLL"],
+ visibility = [
+ "//connections/implementation:__subpackages__",
+ ],
+ deps = [
+ "//connections:core_types",
+ "//internal/platform:base",
+ "//internal/platform:logging",
+ "//internal/platform:types",
+ "//internal/platform:util",
+ "@aappleby_smhasher//:libmurmur3",
+ "@com_google_absl//absl/container:flat_hash_map",
+ "@com_google_absl//absl/container:flat_hash_set",
+ "@com_google_absl//absl/numeric:int128",
+ "@com_google_absl//absl/strings",
+ "@com_google_absl//absl/time",
+ ],
+)
+
+cc_test(
+ name = "ble_v2_test",
+ srcs = [
+ "advertisement_read_result_test.cc",
+ "ble_advertisement_header_test.cc",
+ "ble_advertisement_test.cc",
+ "ble_packet_test.cc",
+ "ble_peripheral_test.cc",
+ "bloom_filter_test.cc",
+ ],
+ deps = [
+ ":ble_v2",
+ "//internal/platform:base",
+ "//internal/platform:comm",
+ "//internal/platform/implementation/g3", # buildcleaner: keep
+ "@com_github_protobuf_matchers//protobuf-matchers",
+ "@com_google_absl//absl/time",
+ "@com_google_googletest//:gtest_main",
+ ],
+)
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/advertisement_read_result.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/advertisement_read_result.cc
new file mode 100644
index 00000000000..82578c0cde1
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/advertisement_read_result.cc
@@ -0,0 +1,139 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/ble_v2/advertisement_read_result.h"
+
+#include <algorithm>
+#include <vector>
+
+#include "absl/container/flat_hash_set.h"
+#include "absl/time/clock.h"
+#include "internal/platform/mutex_lock.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+const AdvertisementReadResult::Config AdvertisementReadResult::kDefaultConfig{
+ .backoff_multiplier = 2.0,
+ .base_backoff_duration = absl::Seconds(1),
+ .max_backoff_duration = absl::Minutes(5),
+};
+
+// Adds a successfully read advertisement for the specified slot to this read
+// result. This is fundamentally different from RecordLastReadStatus() because
+// we can report a read failure, but still manage to read some advertisements.
+void AdvertisementReadResult::AddAdvertisement(std::int32_t slot,
+ const ByteArray& advertisement) {
+ MutexLock lock(&mutex_);
+
+ // Blindly remove from the advertisements map to make sure any existing
+ // key-value pair is destroyed.
+ advertisements_.emplace(slot, advertisement);
+}
+
+// Determines whether or not an advertisement was successfully read at the
+// specified slot.
+bool AdvertisementReadResult::HasAdvertisement(std::int32_t slot) const {
+ MutexLock lock(&mutex_);
+
+ return advertisements_.contains(slot);
+}
+
+// Retrieves all raw advertisements that were successfully read.
+std::vector<const ByteArray*> AdvertisementReadResult::GetAdvertisements()
+ const {
+ MutexLock lock(&mutex_);
+
+ std::vector<const ByteArray*> all_advertisements;
+ all_advertisements.reserve(advertisements_.size());
+ for (const auto& item : advertisements_) {
+ all_advertisements.emplace_back(&item.second);
+ }
+
+ return all_advertisements;
+}
+
+// Determines what stage we're in for retrying a read from an advertisement
+// GATT server.
+AdvertisementReadResult::RetryStatus
+AdvertisementReadResult::EvaluateRetryStatus() const {
+ MutexLock lock(&mutex_);
+
+ // Check if we have already succeeded reading this advertisement.
+ if (status_ == Status::kSuccess) {
+ return RetryStatus::kPreviouslySucceeded;
+ }
+
+ // Check if we have recently failed to read this advertisement.
+ if (GetDurationSinceReadLocked() < backoff_duration_) {
+ return RetryStatus::kTooSoon;
+ }
+
+ return RetryStatus::kRetry;
+}
+
+// Records the status of the latest read, and updates the next backoff
+// duration for subsequent reads. Be sure to also call
+// AddAdvertisement() if any advertisements were read.
+void AdvertisementReadResult::RecordLastReadStatus(bool is_success) {
+ MutexLock lock(&mutex_);
+
+ // Update the last read timestamp.
+ last_read_timestamp_ = SystemClock::ElapsedRealtime();
+
+ // Update the backoff duration.
+ if (is_success) {
+ // Reset the backoff duration now that we had a successful read.
+ backoff_duration_ = config_.base_backoff_duration;
+ } else {
+ // Determine whether or not we were already failing before. If we were, we
+ // should increase the backoff duration.
+ if (status_ == Status::kFailure) {
+ // Use exponential backoff to determine the next backoff duration. This
+ // simply involves multiplying our current backoff duration by some
+ // multiplier.
+ absl::Duration next_backoff_duration =
+ config_.backoff_multiplier * backoff_duration_;
+ // Update the backoff duration, making sure not to blow past the
+ // ceiling.
+ backoff_duration_ =
+ std::min(next_backoff_duration, config_.max_backoff_duration);
+ } else {
+ // This is our first time failing, so we should only backoff for the
+ // initial duration.
+ backoff_duration_ = config_.base_backoff_duration;
+ }
+ }
+
+ // Update the internal result.
+ status_ = is_success ? Status::kSuccess : Status::kFailure;
+}
+
+// Returns how much time has passed since we last tried reading from an
+// advertisement GATT server.
+absl::Duration AdvertisementReadResult::GetDurationSinceRead() const {
+ MutexLock lock(&mutex_);
+ return GetDurationSinceReadLocked();
+}
+
+absl::Duration AdvertisementReadResult::GetDurationSinceReadLocked() const {
+ return SystemClock::ElapsedRealtime() - last_read_timestamp_;
+}
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/advertisement_read_result.h b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/advertisement_read_result.h
new file mode 100644
index 00000000000..712f56e302a
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/advertisement_read_result.h
@@ -0,0 +1,104 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MEDIUMS_BLE_V2_ADVERTISEMENT_READ_RESULT_H_
+#define CORE_INTERNAL_MEDIUMS_BLE_V2_ADVERTISEMENT_READ_RESULT_H_
+
+#include <cstdint>
+#include <vector>
+
+#include "absl/container/flat_hash_map.h"
+#include "absl/container/flat_hash_set.h"
+#include "absl/time/clock.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/mutex.h"
+#include "internal/platform/system_clock.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+// Representation of a GATT advertisement read result. This object helps us
+// determine whether or not we need to retry GATT reads.
+class AdvertisementReadResult {
+ public:
+ // We need a long enough duration such that we always trigger a read
+ // retry AND we always connect to it without delay. The former case
+ // helps us initialize an AdvertisementReadResult so that we
+ // unconditionally try reading on the first sighting. And the latter
+ // case helps us connect immediately when we initialize a dummy read
+ // result for fast advertisements (which don't use the GATT server).
+
+ struct Config {
+ // How much to multiply the backoff duration by with every failure to read
+ // from the advertisement GATT server. This should never be below 1!
+ float backoff_multiplier;
+ // The initial backoff duration when we fail to read from an advertisement
+ // GATT server.
+ absl::Duration base_backoff_duration;
+ // The maximum backoff duration allowed between advertisement GATT server
+ // reads.
+ absl::Duration max_backoff_duration;
+ };
+
+ static const Config kDefaultConfig;
+ explicit AdvertisementReadResult(const Config& config = kDefaultConfig)
+ : config_(config) {}
+ ~AdvertisementReadResult() = default;
+
+ enum class RetryStatus {
+ kUnknown = 0,
+ kRetry = 1,
+ kPreviouslySucceeded = 2,
+ kTooSoon = 3,
+ };
+
+ void AddAdvertisement(std::int32_t slot, const ByteArray& advertisement)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ bool HasAdvertisement(std::int32_t slot) const ABSL_LOCKS_EXCLUDED(mutex_);
+ std::vector<const ByteArray*> GetAdvertisements() const
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ RetryStatus EvaluateRetryStatus() const ABSL_LOCKS_EXCLUDED(mutex_);
+ void RecordLastReadStatus(bool is_success) ABSL_LOCKS_EXCLUDED(mutex_);
+ absl::Duration GetDurationSinceRead() const ABSL_LOCKS_EXCLUDED(mutex_);
+
+ private:
+ enum class Status {
+ kUnknown = 0,
+ kSuccess = 1,
+ kFailure = 2,
+ };
+
+ absl::Duration GetDurationSinceReadLocked() const
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ mutable Mutex mutex_;
+
+ // Maps slot numbers to the GATT advertisement found in that slot.
+ absl::flat_hash_map<std::int32_t, ByteArray> advertisements_
+ ABSL_GUARDED_BY(mutex_);
+
+ Config config_;
+ absl::Duration backoff_duration_ ABSL_GUARDED_BY(mutex_);
+ absl::Time last_read_timestamp_ ABSL_GUARDED_BY(mutex_);
+ Status status_ ABSL_GUARDED_BY(mutex_) = Status::kUnknown;
+};
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MEDIUMS_BLE_V2_ADVERTISEMENT_READ_RESULT_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/advertisement_read_result_test.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/advertisement_read_result_test.cc
new file mode 100644
index 00000000000..94b79ac7986
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/advertisement_read_result_test.cc
@@ -0,0 +1,143 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/ble_v2/advertisement_read_result.h"
+
+#include "gtest/gtest.h"
+#include "absl/time/clock.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+namespace {
+
+constexpr char kAdvertisementBytes[] = "\x0A\x0B\x0C";
+
+// Default values may be too big and impractical to wait for in the test.
+// For the test platform, we redefine them to some reasonable values.
+const absl::Duration kAdvertisementBaseBackoffDuration = absl::Seconds(1);
+const absl::Duration kAdvertisementMaxBackoffDuration = absl::Seconds(6);
+
+const AdvertisementReadResult::Config test_config{
+ .backoff_multiplier =
+ AdvertisementReadResult::kDefaultConfig.backoff_multiplier,
+ .base_backoff_duration = kAdvertisementBaseBackoffDuration,
+ .max_backoff_duration = kAdvertisementMaxBackoffDuration,
+};
+
+TEST(AdvertisementReadResultTest, AdvertisementExists) {
+ AdvertisementReadResult advertisement_read_result(test_config);
+ advertisement_read_result.RecordLastReadStatus(/* is_success= */ true);
+
+ std::int32_t slot = 6;
+ advertisement_read_result.AddAdvertisement(slot,
+ ByteArray(kAdvertisementBytes));
+
+ EXPECT_TRUE(advertisement_read_result.HasAdvertisement(slot));
+}
+
+TEST(AdvertisementReadResultTest, AdvertisementNonExistent) {
+ AdvertisementReadResult advertisement_read_result(test_config);
+ advertisement_read_result.RecordLastReadStatus(/* is_success= */ true);
+
+ std::int32_t slot = 6;
+
+ EXPECT_FALSE(advertisement_read_result.HasAdvertisement(slot));
+}
+
+TEST(AdvertisementReadResultTest, EvaluateRetryStatusInitialized) {
+ AdvertisementReadResult advertisement_read_result(test_config);
+
+ EXPECT_EQ(advertisement_read_result.EvaluateRetryStatus(),
+ AdvertisementReadResult::RetryStatus::kRetry);
+}
+
+TEST(AdvertisementReadResultTest, EvaluateRetryStatusSuccess) {
+ AdvertisementReadResult advertisement_read_result(test_config);
+ advertisement_read_result.RecordLastReadStatus(/* is_success= */ true);
+
+ EXPECT_EQ(advertisement_read_result.EvaluateRetryStatus(),
+ AdvertisementReadResult::RetryStatus::kPreviouslySucceeded);
+}
+
+TEST(AdvertisementReadResultTest, EvaluateRetryStatusTooSoon) {
+ AdvertisementReadResult advertisement_read_result(test_config);
+ advertisement_read_result.RecordLastReadStatus(/* is_success= */ false);
+
+ // Sleep for some time, but not long enough to warrant a retry.
+ absl::SleepFor(kAdvertisementBaseBackoffDuration / 2);
+
+ EXPECT_EQ(advertisement_read_result.EvaluateRetryStatus(),
+ AdvertisementReadResult::RetryStatus::kTooSoon);
+}
+
+TEST(AdvertisementReadResultTest, EvaluateRetryStatusRetry) {
+ AdvertisementReadResult advertisement_read_result(test_config);
+ advertisement_read_result.RecordLastReadStatus(/* is_success= */ false);
+
+ // Sleep long enough to warrant a retry.
+ absl::SleepFor(kAdvertisementBaseBackoffDuration);
+
+ EXPECT_EQ(advertisement_read_result.EvaluateRetryStatus(),
+ AdvertisementReadResult::RetryStatus::kRetry);
+}
+
+TEST(AdvertisementReadResultTest, ReportStatusExponentialBackoff) {
+ AdvertisementReadResult advertisement_read_result(test_config);
+ advertisement_read_result.RecordLastReadStatus(/* is_success= */ false);
+
+ // Record an additional failure so our backoff duration increases.
+ advertisement_read_result.RecordLastReadStatus(/* is_success= */ false);
+
+ // Sleep for the backoff duration. We shouldn't trigger a retry because the
+ // backoff should have increased from failing a second time.
+ absl::SleepFor(kAdvertisementBaseBackoffDuration);
+
+ EXPECT_EQ(advertisement_read_result.EvaluateRetryStatus(),
+ AdvertisementReadResult::RetryStatus::kTooSoon);
+}
+
+TEST(AdvertisementReadResultTest, ReportStatusExponentialBackoffMax) {
+ AdvertisementReadResult advertisement_read_result(test_config);
+ advertisement_read_result.RecordLastReadStatus(/* is_success= */ false);
+
+ // Record an absurd amount of failures so we hit the maximum backoff duration.
+ for (std::int32_t i = 0; i < 1000; i++) {
+ advertisement_read_result.RecordLastReadStatus(/* is_success= */ false);
+ }
+
+ // Sleep for the maximum backoff duration. This should be enough to warrant a
+ // retry.
+ absl::SleepFor(kAdvertisementMaxBackoffDuration);
+
+ EXPECT_EQ(advertisement_read_result.EvaluateRetryStatus(),
+ AdvertisementReadResult::RetryStatus::kRetry);
+}
+
+TEST(AdvertisementReadResultTest, GetDurationSinceRead) {
+ AdvertisementReadResult advertisement_read_result(test_config);
+ advertisement_read_result.RecordLastReadStatus(/* is_success= */ true);
+
+ absl::Duration sleepTime = absl::Milliseconds(420);
+ absl::SleepFor(sleepTime);
+
+ EXPECT_GE(advertisement_read_result.GetDurationSinceRead(), sleepTime);
+}
+
+} // namespace
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_advertisement.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_advertisement.cc
new file mode 100644
index 00000000000..000c13873cc
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_advertisement.cc
@@ -0,0 +1,245 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/ble_v2/ble_advertisement.h"
+
+#include <inttypes.h>
+
+#include "absl/strings/str_cat.h"
+#include "internal/platform/base_input_stream.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+BleAdvertisement::BleAdvertisement(Version version,
+ SocketVersion socket_version,
+ const ByteArray &service_id_hash,
+ const ByteArray &data,
+ const ByteArray &device_token) {
+ DoInitialize(/*fast_advertisement=*/service_id_hash.Empty(), version,
+ socket_version, service_id_hash, data, device_token);
+}
+
+void BleAdvertisement::DoInitialize(bool fast_advertisement, Version version,
+ SocketVersion socket_version,
+ const ByteArray &service_id_hash,
+ const ByteArray &data,
+ const ByteArray &device_token) {
+ // Check that the given input is valid.
+ fast_advertisement_ = fast_advertisement;
+ if (!fast_advertisement_) {
+ if (service_id_hash.size() != kServiceIdHashLength) return;
+ }
+ if (!IsSupportedVersion(version) ||
+ !IsSupportedSocketVersion(socket_version) ||
+ (!device_token.Empty() && device_token.size() != kDeviceTokenLength)) {
+ return;
+ }
+
+ int advertisement_Length = ComputeAdvertisementLength(
+ data.size(), device_token.size(), fast_advertisement_);
+ int max_advertisement_length = fast_advertisement
+ ? kMaxFastAdvertisementLength
+ : kMaxAdvertisementLength;
+ if (advertisement_Length > max_advertisement_length) {
+ return;
+ }
+
+ version_ = version;
+ socket_version_ = socket_version;
+ if (!fast_advertisement_) service_id_hash_ = service_id_hash;
+ data_ = data;
+ device_token_ = device_token;
+}
+
+BleAdvertisement::BleAdvertisement(const ByteArray &ble_advertisement_bytes) {
+ if (ble_advertisement_bytes.Empty()) {
+ NEARBY_LOG(INFO,
+ "Cannot deserialize BleAdvertisement: null bytes passed in.");
+ return;
+ }
+
+ if (ble_advertisement_bytes.size() < kVersionLength) {
+ NEARBY_LOG(
+ INFO,
+ "Cannot deserialize BleAdvertisement: expecting min %d raw bytes to "
+ "parse the version, got %" PRIu64,
+ kVersionLength, ble_advertisement_bytes.size());
+ return;
+ }
+
+ ByteArray advertisement_bytes{ble_advertisement_bytes};
+ BaseInputStream base_input_stream{advertisement_bytes};
+ // The first 1 byte is supposed to be the version, socket version and the fast
+ // advertisement flag.
+ auto version_byte = static_cast<char>(base_input_stream.ReadUint8());
+
+ // Version.
+ version_ = static_cast<Version>((version_byte & kVersionBitmask) >> 5);
+ if (!IsSupportedVersion(version_)) {
+ NEARBY_LOG(INFO,
+ "Cannot deserialize BleAdvertisement: unsupported Version %u",
+ version_);
+ return;
+ }
+
+ // Socket version.
+ socket_version_ =
+ static_cast<SocketVersion>((version_byte & kSocketVersionBitmask) >> 2);
+ if (!IsSupportedSocketVersion(socket_version_)) {
+ NEARBY_LOG(
+ INFO,
+ "Cannot deserialize BleAdvertisement: unsupported SocketVersion %u",
+ socket_version_);
+ version_ = Version::kUndefined;
+ return;
+ }
+
+ // Fast advertisement flag.
+ fast_advertisement_ =
+ static_cast<bool>((version_byte & kFastAdvertisementFlagBitmask) >> 1);
+
+ // The next 3 bytes are supposed to be the service_id_hash if not fast
+ // advertisement.
+ if (!fast_advertisement_) {
+ service_id_hash_ = base_input_stream.ReadBytes(kServiceIdHashLength);
+ }
+
+ // Data length.
+ int expected_data_size =
+ fast_advertisement_
+ ? static_cast<int>(
+ base_input_stream.ReadBytes(kFastDataSizeLength).data()[0])
+ : static_cast<int>(base_input_stream.ReadUint32());
+ if (expected_data_size < 0) {
+ NEARBY_LOG(INFO,
+ "Cannot deserialize BleAdvertisement: negative data size %d",
+ expected_data_size);
+ version_ = Version::kUndefined;
+ return;
+ }
+
+ // Data.
+ // Check that the stated data size is the same as what we received.
+ data_ = base_input_stream.ReadBytes(expected_data_size);
+ if (data_.size() != expected_data_size) {
+ NEARBY_LOG(INFO,
+ "Cannot deserialize BleAdvertisement: expected data to be %u "
+ "bytes, got %" PRIu64 " bytes ",
+ expected_data_size, data_.size());
+ version_ = Version::kUndefined;
+ return;
+ }
+
+ // Device token. If the number of remaining bytes are valid for device token,
+ // then read it.
+ if (base_input_stream.IsAvailable(kDeviceTokenLength)) {
+ device_token_ = base_input_stream.ReadBytes(kDeviceTokenLength);
+ }
+}
+
+BleAdvertisement::operator ByteArray() const {
+ if (!IsValid()) {
+ return ByteArray{};
+ }
+
+ // The first 3 bits are the Version.
+ char version_byte = (static_cast<char>(version_) << 5) & kVersionBitmask;
+ // The next 3 bits are the Socket version. 2 bits left are reserved.
+ version_byte |=
+ (static_cast<char>(socket_version_) << 2) & kSocketVersionBitmask;
+ // The next 1 bit is the fast advertisement flag. 1 bit left is reserved.
+ version_byte |= (static_cast<char>(fast_advertisement_ ? 1 : 0) << 1) &
+ kFastAdvertisementFlagBitmask;
+
+ // Serialize Data size bytes
+ ByteArray data_size_bytes{static_cast<size_t>(
+ fast_advertisement_ ? kFastDataSizeLength : kDataSizeLength)};
+ auto *data_size_bytes_write_ptr = data_size_bytes.data();
+ SerializeDataSize(fast_advertisement_, data_size_bytes_write_ptr,
+ data_.size());
+
+ // clang-format on
+ if (fast_advertisement_) {
+ std::string out =
+ absl::StrCat(std::string(1, version_byte), std::string(data_size_bytes),
+ std::string(data_), std::string(device_token_));
+ return ByteArray{std::move(out)};
+ } else {
+ std::string out = absl::StrCat(
+ std::string(1, version_byte), std::string(service_id_hash_),
+ std::string(data_size_bytes), std::string(data_),
+ std::string(device_token_));
+ return ByteArray{std::move(out)};
+ }
+ // clang-format on
+}
+
+bool BleAdvertisement::operator==(const BleAdvertisement &rhs) const {
+ return this->GetVersion() == rhs.GetVersion() &&
+ this->GetSocketVersion() == rhs.GetSocketVersion() &&
+ this->GetServiceIdHash() == rhs.GetServiceIdHash() &&
+ this->GetData() == rhs.GetData() &&
+ this->GetDeviceToken() == rhs.GetDeviceToken();
+}
+
+bool BleAdvertisement::operator<(const BleAdvertisement &rhs) const {
+ if (this->GetVersion() != rhs.GetVersion()) {
+ return this->GetVersion() < rhs.GetVersion();
+ }
+ if (this->GetSocketVersion() != rhs.GetSocketVersion()) {
+ return this->GetSocketVersion() < rhs.GetSocketVersion();
+ }
+ if (this->GetServiceIdHash() != rhs.GetServiceIdHash()) {
+ return this->GetServiceIdHash() < rhs.GetServiceIdHash();
+ }
+ if (this->GetDeviceToken() != rhs.GetDeviceToken()) {
+ return this->GetDeviceToken() < rhs.GetDeviceToken();
+ }
+ return this->GetData() < rhs.GetData();
+}
+
+bool BleAdvertisement::IsSupportedVersion(Version version) const {
+ return version >= Version::kV1 && version <= Version::kV2;
+}
+
+bool BleAdvertisement::IsSupportedSocketVersion(
+ SocketVersion socket_version) const {
+ return socket_version >= SocketVersion::kV1 &&
+ socket_version <= SocketVersion::kV2;
+}
+
+void BleAdvertisement::SerializeDataSize(bool fast_advertisement,
+ char *data_size_bytes_write_ptr,
+ size_t data_size) const {
+ // Get a raw representation of the data size bytes in memory.
+ char *data_size_bytes = reinterpret_cast<char *>(&data_size);
+
+ const int data_size_length =
+ fast_advertisement ? kFastDataSizeLength : kDataSizeLength;
+
+ // Append these raw bytes to advertisement bytes, keeping in mind that we need
+ // to convert from Little Endian to Big Endian in the process.
+ for (int i = 0; i < data_size_length; ++i) {
+ data_size_bytes_write_ptr[i] = data_size_bytes[data_size_length - i - 1];
+ }
+}
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_advertisement.h b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_advertisement.h
new file mode 100644
index 00000000000..4cde94189bd
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_advertisement.h
@@ -0,0 +1,139 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MEDIUMS_BLE_V2_BLE_ADVERTISEMENT_H_
+#define CORE_INTERNAL_MEDIUMS_BLE_V2_BLE_ADVERTISEMENT_H_
+
+#include <utility>
+
+#include "internal/platform/byte_array.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+// Represents the format of the Mediums BLE Advertisement used in Advertising +
+// Discovery.
+//
+// [VERSION][SOCKET_VERSION][FAST_ADVERTISEMENT_FLAG][1_RESERVED_BIT][SERVICE_ID_HASH][DATA_SIZE][DATA][DEVICE_TOKEN]
+//
+// For fast advertisement, we remove SERVICE_ID_HASH since we already have one
+// copy in Nearby Connections(b/138447288)
+// [VERSION][SOCKET_VERSION][FAST_ADVERTISEMENT_FLAG][1_RESERVED_BIT][DATA_SIZE][DATA][DEVICE_TOKEN]
+//
+// See go/nearby-ble-design for more information.
+class BleAdvertisement {
+ public:
+ // Versions of the BleAdvertisement.
+ enum class Version {
+ kUndefined = 0,
+ kV1 = 1,
+ kV2 = 2,
+ // Version is only allocated 3 bits in the BleAdvertisement, so this can
+ // never go beyond V7.
+ };
+
+ // Versions of the BLESocket.
+ enum class SocketVersion {
+ kUndefined = 0,
+ kV1 = 1,
+ kV2 = 2,
+ // SocketVersion is only allocated 3 bits in the BleAdvertisement, so this
+ // can never go beyond V7.
+ };
+
+ static constexpr int kServiceIdHashLength = 3;
+ static constexpr int kDeviceTokenLength = 2;
+
+ BleAdvertisement() = default;
+ BleAdvertisement(Version version, SocketVersion socket_version,
+ const ByteArray &service_id_hash, const ByteArray &data,
+ const ByteArray &device_token);
+ explicit BleAdvertisement(const ByteArray &ble_advertisement_bytes);
+ BleAdvertisement(const BleAdvertisement &) = default;
+ BleAdvertisement &operator=(const BleAdvertisement &) = default;
+ BleAdvertisement(BleAdvertisement &&) = default;
+ BleAdvertisement &operator=(BleAdvertisement &&) = default;
+ ~BleAdvertisement() = default;
+
+ explicit operator ByteArray() const;
+ // Operator overloads when comparing BleAdvertisement.
+ bool operator==(const BleAdvertisement &rhs) const;
+ bool operator<(const BleAdvertisement &rhs) const;
+
+ bool IsValid() const { return IsSupportedVersion(version_); }
+ Version GetVersion() const { return version_; }
+ SocketVersion GetSocketVersion() const { return socket_version_; }
+ bool IsFastAdvertisement() const { return fast_advertisement_; }
+ ByteArray GetServiceIdHash() const { return service_id_hash_; }
+ ByteArray &GetData() & { return data_; }
+ const ByteArray &GetData() const & { return data_; }
+ ByteArray &&GetData() && { return std::move(data_); }
+ const ByteArray &&GetData() const && { return std::move(data_); }
+ ByteArray GetDeviceToken() const { return device_token_; }
+
+ private:
+ void DoInitialize(bool fast_advertisement, Version version,
+ SocketVersion socket_version,
+ const ByteArray &service_id_hash, const ByteArray &data,
+ const ByteArray &device_token);
+ bool IsSupportedVersion(Version version) const;
+ bool IsSupportedSocketVersion(SocketVersion socket_version) const;
+ void SerializeDataSize(bool fast_advertisement,
+ char *data_size_bytes_write_ptr,
+ size_t data_size) const;
+ int ComputeAdvertisementLength(int data_length, int total_optional_length,
+ bool fast_advertisement) const {
+ // The advertisement length is the minimum length + the length of the data +
+ // the length of in-use optional fields.
+ return fast_advertisement ? (kMinFastAdvertisementLegth + data_length +
+ total_optional_length)
+ : (kMinAdvertisementLength + data_length +
+ total_optional_length);
+ }
+
+ static constexpr int kVersionLength = 1;
+ static constexpr int kVersionBitmask = 0x0E0;
+ static constexpr int kSocketVersionBitmask = 0x01C;
+ static constexpr int kFastAdvertisementFlagBitmask = 0x002;
+ static constexpr int kDataSizeLength = 4; // Length of one int.
+ static constexpr int kFastDataSizeLength = 1; // Length of one byte.
+ static constexpr int kMinAdvertisementLength =
+ kVersionLength + kServiceIdHashLength + kDataSizeLength;
+ // The maximum length for a Gatt characteristic value is 512 bytes, so make
+ // sure the entire advertisement is less than that. The data can take up
+ // whatever space is remaining after the bytes preceding it.
+ static constexpr int kMaxAdvertisementLength = 512;
+ static constexpr int kMinFastAdvertisementLegth =
+ kVersionLength + kFastDataSizeLength;
+ // The maximum length for the scan response is 31 bytes. However, with the
+ // required header that comes before the service data, this leaves the
+ // advertiser with 27 leftover bytes.
+ static constexpr int kMaxFastAdvertisementLength = 27;
+
+ Version version_{Version::kUndefined};
+ SocketVersion socket_version_{SocketVersion::kUndefined};
+ bool fast_advertisement_ = false;
+ ByteArray service_id_hash_;
+ ByteArray data_;
+ ByteArray device_token_;
+};
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MEDIUMS_BLE_V2_BLE_ADVERTISEMENT_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_advertisement_header.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_advertisement_header.cc
new file mode 100644
index 00000000000..a1379c18c69
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_advertisement_header.cc
@@ -0,0 +1,138 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/ble_v2/ble_advertisement_header.h"
+
+#include <inttypes.h>
+
+#include "absl/strings/str_cat.h"
+#include "internal/platform/base64_utils.h"
+#include "internal/platform/base_input_stream.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+BleAdvertisementHeader::BleAdvertisementHeader(
+ Version version, bool extended_advertisement, int num_slots,
+ const ByteArray &service_id_bloom_filter,
+ const ByteArray &advertisement_hash, int psm) {
+ if (version != Version::kV2 || num_slots <= 0 ||
+ service_id_bloom_filter.size() != kServiceIdBloomFilterLength ||
+ advertisement_hash.size() != kAdvertisementHashLength) {
+ return;
+ }
+
+ version_ = version;
+ extended_advertisement_ = extended_advertisement;
+ num_slots_ = num_slots;
+ service_id_bloom_filter_ = service_id_bloom_filter;
+ advertisement_hash_ = advertisement_hash;
+ psm_ = psm;
+}
+
+BleAdvertisementHeader::BleAdvertisementHeader(
+ const ByteArray &ble_advertisement_header_bytes) {
+ if (ble_advertisement_header_bytes.Empty()) {
+ NEARBY_LOG(
+ ERROR,
+ "Cannot deserialize BLEAdvertisementHeader: failed Base64 decoding");
+ return;
+ }
+
+ if (ble_advertisement_header_bytes.size() < kMinAdvertisementHeaderLength) {
+ NEARBY_LOG(ERROR,
+ "Cannot deserialize BleAdvertisementHeader: expecting min %u "
+ "raw bytes, got %" PRIu64 " instead",
+ kMinAdvertisementHeaderLength,
+ ble_advertisement_header_bytes.size());
+ return;
+ }
+
+ ByteArray advertisement_header_bytes{ble_advertisement_header_bytes};
+ BaseInputStream base_input_stream{advertisement_header_bytes};
+ // The first 1 byte is supposed to be the version and number of slots.
+ auto version_and_num_slots_byte =
+ static_cast<char>(base_input_stream.ReadUint8());
+ // The upper 3 bits are supposed to be the version.
+ version_ =
+ static_cast<Version>((version_and_num_slots_byte & kVersionBitmask) >> 5);
+ if (version_ != Version::kV2) {
+ NEARBY_LOG(
+ ERROR,
+ "Cannot deserialize BleAdvertisementHeader: unsupported Version %d",
+ version_);
+ return;
+ }
+ // The next 1 bit is supposed to be the extended advertisement flag.
+ extended_advertisement_ =
+ ((version_and_num_slots_byte & kExtendedAdvertismentBitMask) >> 4) == 1;
+ // The lower 4 bits are supposed to be the number of slots.
+ num_slots_ = static_cast<int>(version_and_num_slots_byte & kNumSlotsBitmask);
+ if (num_slots_ <= 0) {
+ version_ = Version::kUndefined;
+ return;
+ }
+
+ // The next 10 bytes are supposed to be the service_id_bloom_filter.
+ service_id_bloom_filter_ =
+ base_input_stream.ReadBytes(kServiceIdBloomFilterLength);
+
+ // The next 4 bytes are supposed to be the advertisement_hash.
+ advertisement_hash_ = base_input_stream.ReadBytes(kAdvertisementHashLength);
+
+ // The next 2 bytes are PSM value.
+ if (base_input_stream.IsAvailable(sizeof(std::uint16_t))) {
+ psm_ = static_cast<int>(base_input_stream.ReadUint16());
+ }
+}
+
+BleAdvertisementHeader::operator ByteArray() const {
+ if (!IsValid()) {
+ return ByteArray();
+ }
+
+ // The first 3 bits are the Version.
+ char version_and_num_slots_byte =
+ (static_cast<char>(version_) << 5) & kVersionBitmask;
+ // The next 1 bit is extended advertisement flag.
+ version_and_num_slots_byte |=
+ (static_cast<char>(extended_advertisement_) << 4) &
+ kExtendedAdvertismentBitMask;
+ // The next 5 bits are the number of slots.
+ version_and_num_slots_byte |=
+ static_cast<char>(num_slots_) & kNumSlotsBitmask;
+
+ // Convert psm_ value to 2-bytes.
+ ByteArray psm_byte{sizeof(std::uint16_t)};
+ char *data = psm_byte.data();
+ data[0] = psm_ & 0xFF00;
+ data[1] = psm_ & 0x00FF;
+
+ // clang-format off
+ std::string out = absl::StrCat(std::string(1, version_and_num_slots_byte),
+ std::string(service_id_bloom_filter_),
+ std::string(advertisement_hash_),
+ std::string(psm_byte));
+ // clang-format on
+
+ return ByteArray(std::move(out));
+}
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_advertisement_header.h b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_advertisement_header.h
new file mode 100644
index 00000000000..24dd3584b09
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_advertisement_header.h
@@ -0,0 +1,101 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MEDIUMS_BLE_V2_BLE_ADVERTISEMENT_HEADER_H_
+#define CORE_INTERNAL_MEDIUMS_BLE_V2_BLE_ADVERTISEMENT_HEADER_H_
+
+#include <string>
+
+#include "internal/platform/byte_array.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+// Represents the format of the Mediums BLE Advertisement Header used in
+// Advertising + Discovery.
+//
+// [VERSION][NUM_SLOTS][SERVICE_ID_BLOOM_FILTER][ADVERTISEMENT_HASH][L2_CAP_PSM]
+//
+// See go/nearby-ble-design for more information.
+//
+// Note. The object constructed by default constructor or the parameterized
+// constructor with invalid value(s) is treated as invalid instance. Caller
+// should be responsible to call IsValid() to check the instance is invalid in
+// advance before continue on.
+class BleAdvertisementHeader {
+ public:
+ // Versions of the BleAdvertisementHeader.
+ enum class Version {
+ kUndefined = 0,
+ kV1 = 1,
+ kV2 = 2,
+ // Version is only allocated 3 bits in the BleAdvertisementHeader, so this
+ // can never go beyond V7.
+ //
+ // V1 is not present because it's an old format used in Nearby Connections
+ // before this logic was pushed down into Nearby Mediums. V1 put
+ // everything in the service data, while V2 puts the data inside a GATT
+ // characteristic so the two are not compatible.
+ };
+
+ BleAdvertisementHeader() = default;
+ BleAdvertisementHeader(Version version, bool extended_advertisement,
+ int num_slots,
+ const ByteArray &service_id_bloom_filter,
+ const ByteArray &advertisement_hash, int psm);
+ explicit BleAdvertisementHeader(
+ const ByteArray &ble_advertisement_header_bytes);
+ BleAdvertisementHeader(const BleAdvertisementHeader &) = default;
+ BleAdvertisementHeader &operator=(const BleAdvertisementHeader &) = default;
+ BleAdvertisementHeader(BleAdvertisementHeader &&) = default;
+ BleAdvertisementHeader &operator=(BleAdvertisementHeader &&) = default;
+ ~BleAdvertisementHeader() = default;
+
+ explicit operator ByteArray() const;
+
+ bool IsValid() const { return version_ == Version::kV2; }
+ Version GetVersion() const { return version_; }
+ bool IsExtendedAdvertisement() const { return extended_advertisement_; }
+ int GetNumSlots() const { return num_slots_; }
+ ByteArray GetServiceIdBloomFilter() const { return service_id_bloom_filter_; }
+ ByteArray GetAdvertisementHash() const { return advertisement_hash_; }
+ int GetPsmValue() const { return psm_; }
+
+ private:
+ static constexpr int kVersionAndNumSlotsLength = 1;
+ static constexpr int kServiceIdBloomFilterLength = 10;
+ static constexpr int kAdvertisementHashLength = 4;
+ static constexpr int kMinAdvertisementHeaderLength =
+ kVersionAndNumSlotsLength + kServiceIdBloomFilterLength +
+ kAdvertisementHashLength;
+ static constexpr int kVersionBitmask = 0x0E0;
+ static constexpr int kExtendedAdvertismentBitMask = 0x010;
+ static constexpr int kNumSlotsBitmask = 0x00F;
+
+ Version version_ = Version::kUndefined;
+ bool extended_advertisement_ = false;
+ int num_slots_ = 0;
+ ByteArray service_id_bloom_filter_;
+ ByteArray advertisement_hash_;
+ int psm_ = 0;
+};
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MEDIUMS_BLE_V2_BLE_ADVERTISEMENT_HEADER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_advertisement_header_test.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_advertisement_header_test.cc
new file mode 100644
index 00000000000..cb300ba7018
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_advertisement_header_test.cc
@@ -0,0 +1,208 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/ble_v2/ble_advertisement_header.h"
+
+#include "gtest/gtest.h"
+#include "internal/platform/base64_utils.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+namespace {
+
+constexpr BleAdvertisementHeader::Version kVersion =
+ BleAdvertisementHeader::Version::kV2;
+constexpr int kNumSlots = 2;
+constexpr std::int16_t kPsmValue = 1;
+constexpr absl::string_view kServiceIDBloomFilter{
+ "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a"};
+constexpr absl::string_view kAdvertisementHash{"\x0a\x0b\x0c\x0d"};
+
+TEST(BleAdvertisementHeaderTest, ConstructionWorks) {
+ ByteArray service_id_bloom_filter{std::string(kServiceIDBloomFilter)};
+ ByteArray advertisement_hash{std::string(kAdvertisementHash)};
+
+ BleAdvertisementHeader ble_advertisement_header{
+ kVersion, false, kNumSlots, service_id_bloom_filter,
+ advertisement_hash, kPsmValue};
+
+ EXPECT_TRUE(ble_advertisement_header.IsValid());
+ EXPECT_EQ(kVersion, ble_advertisement_header.GetVersion());
+ EXPECT_FALSE(ble_advertisement_header.IsExtendedAdvertisement());
+ EXPECT_EQ(kNumSlots, ble_advertisement_header.GetNumSlots());
+ EXPECT_EQ(service_id_bloom_filter,
+ ble_advertisement_header.GetServiceIdBloomFilter());
+ EXPECT_EQ(advertisement_hash,
+ ble_advertisement_header.GetAdvertisementHash());
+ EXPECT_EQ(kPsmValue, ble_advertisement_header.GetPsmValue());
+}
+
+TEST(BleAdvertisementHeaderTest, ConstructionFailsWithBadVersion) {
+ auto bad_version = static_cast<BleAdvertisementHeader::Version>(666);
+
+ ByteArray service_id_bloom_filter{std::string(kServiceIDBloomFilter)};
+ ByteArray advertisement_hash{std::string(kAdvertisementHash)};
+
+ BleAdvertisementHeader ble_advertisement_header{
+ bad_version, false, kNumSlots, service_id_bloom_filter,
+ advertisement_hash, kPsmValue};
+
+ EXPECT_FALSE(ble_advertisement_header.IsValid());
+}
+
+TEST(BleAdvertisementHeaderTest, ConstructionFailsWitZeroNumSlot) {
+ int num_slot = 0;
+
+ ByteArray service_id_bloom_filter{std::string(kServiceIDBloomFilter)};
+ ByteArray advertisement_hash{std::string(kAdvertisementHash)};
+
+ BleAdvertisementHeader ble_advertisement_header{
+ kVersion, false, num_slot, service_id_bloom_filter,
+ advertisement_hash, kPsmValue};
+
+ EXPECT_FALSE(ble_advertisement_header.IsValid());
+}
+
+TEST(BleAdvertisementHeaderTest,
+ ConstructionFailsWithShortServiceIdBloomFilter) {
+ char short_service_id_bloom_filter[] = "\x01\x02\x03\x04\x05\x06\x07\x08\x09";
+
+ ByteArray short_service_id_bloom_filter_bytes{short_service_id_bloom_filter};
+ ByteArray advertisement_hash{std::string(kAdvertisementHash)};
+
+ BleAdvertisementHeader ble_advertisement_header{
+ kVersion, false,
+ kNumSlots, short_service_id_bloom_filter_bytes,
+ advertisement_hash, kPsmValue};
+
+ EXPECT_FALSE(ble_advertisement_header.IsValid());
+}
+
+TEST(BleAdvertisementHeaderTest,
+ ConstructionFailsWithLongServiceIdBloomFilter) {
+ char long_service_id_bloom_filter[] =
+ "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b";
+
+ ByteArray service_id_bloom_filter{long_service_id_bloom_filter};
+ ByteArray advertisement_hash{std::string(kAdvertisementHash)};
+
+ BleAdvertisementHeader ble_advertisement_header{
+ kVersion, false, kNumSlots, service_id_bloom_filter,
+ advertisement_hash, kPsmValue};
+
+ EXPECT_FALSE(ble_advertisement_header.IsValid());
+}
+
+TEST(BleAdvertisementHeaderTest, ConstructionFailsWithShortAdvertisementHash) {
+ char short_advertisement_hash[] = "\x0a\x0b\x0c";
+
+ ByteArray service_id_bloom_filter{std::string(kServiceIDBloomFilter)};
+ ByteArray advertisement_hash{short_advertisement_hash};
+
+ BleAdvertisementHeader ble_advertisement_header{
+ kVersion, false, kNumSlots, service_id_bloom_filter,
+ advertisement_hash, kPsmValue};
+
+ EXPECT_FALSE(ble_advertisement_header.IsValid());
+}
+
+TEST(BleAdvertisementHeaderTest, ConstructionFailsWithLongAdvertisementHash) {
+ char long_advertisement_hash[] = "\x0a\x0b\x0c\x0d\x0e";
+
+ ByteArray service_id_bloom_filter{std::string(kServiceIDBloomFilter)};
+ ByteArray advertisement_hash{long_advertisement_hash};
+ BleAdvertisementHeader ble_advertisement_header{
+ kVersion, false, kNumSlots, service_id_bloom_filter,
+ advertisement_hash, kPsmValue};
+
+ EXPECT_FALSE(ble_advertisement_header.IsValid());
+}
+
+TEST(BleAdvertisementHeaderTest, ConstructionFromSerializedStringWorks) {
+ ByteArray service_id_bloom_filter{std::string(kServiceIDBloomFilter)};
+ ByteArray advertisement_hash{std::string(kAdvertisementHash)};
+
+ BleAdvertisementHeader org_ble_advertisement_header{
+ kVersion, false, kNumSlots, service_id_bloom_filter,
+ advertisement_hash, kPsmValue};
+ auto ble_advertisement_header_bytes = ByteArray(org_ble_advertisement_header);
+
+ BleAdvertisementHeader ble_advertisement_header{
+ ble_advertisement_header_bytes};
+
+ EXPECT_TRUE(ble_advertisement_header.IsValid());
+ EXPECT_EQ(kVersion, ble_advertisement_header.GetVersion());
+ EXPECT_FALSE(ble_advertisement_header.IsExtendedAdvertisement());
+ EXPECT_EQ(kNumSlots, ble_advertisement_header.GetNumSlots());
+ EXPECT_EQ(service_id_bloom_filter,
+ ble_advertisement_header.GetServiceIdBloomFilter());
+ EXPECT_EQ(advertisement_hash,
+ ble_advertisement_header.GetAdvertisementHash());
+ EXPECT_EQ(kPsmValue, ble_advertisement_header.GetPsmValue());
+}
+
+TEST(BleAdvertisementHeaderTest, ConstructionFromExtraBytesWorks) {
+ ByteArray service_id_bloom_filter{std::string(kServiceIDBloomFilter)};
+ ByteArray advertisement_hash{std::string(kAdvertisementHash)};
+
+ BleAdvertisementHeader ble_advertisement_header{
+ kVersion, false, kNumSlots, service_id_bloom_filter,
+ advertisement_hash, kPsmValue};
+ auto ble_advertisement_header_bytes = ByteArray(ble_advertisement_header);
+
+ ByteArray long_ble_advertisement_header_bytes{
+ ble_advertisement_header_bytes.size() + 1};
+ long_ble_advertisement_header_bytes.CopyAt(0, ble_advertisement_header_bytes);
+
+ BleAdvertisementHeader long_ble_advertisement_header{
+ long_ble_advertisement_header_bytes};
+
+ EXPECT_TRUE(long_ble_advertisement_header.IsValid());
+ EXPECT_EQ(kVersion, long_ble_advertisement_header.GetVersion());
+ EXPECT_FALSE(ble_advertisement_header.IsExtendedAdvertisement());
+ EXPECT_EQ(kNumSlots, long_ble_advertisement_header.GetNumSlots());
+ EXPECT_EQ(service_id_bloom_filter,
+ long_ble_advertisement_header.GetServiceIdBloomFilter());
+ EXPECT_EQ(advertisement_hash,
+ long_ble_advertisement_header.GetAdvertisementHash());
+ EXPECT_EQ(kPsmValue, long_ble_advertisement_header.GetPsmValue());
+}
+
+TEST(BleAdvertisementHeaderTest, ConstructionFromShortLengthFails) {
+ ByteArray service_id_bloom_filter{std::string(kServiceIDBloomFilter)};
+ ByteArray advertisement_hash{std::string(kAdvertisementHash)};
+
+ BleAdvertisementHeader ble_advertisement_header{
+ kVersion, false, kNumSlots, service_id_bloom_filter,
+ advertisement_hash, kPsmValue};
+ auto ble_advertisement_header_bytes = ByteArray(ble_advertisement_header);
+
+ ByteArray short_ble_advertisement_header_bytes{
+ ble_advertisement_header_bytes.size() - 3};
+ short_ble_advertisement_header_bytes.CopyAt(0,
+ ble_advertisement_header_bytes);
+
+ BleAdvertisementHeader short_ble_advertisement_header{
+ short_ble_advertisement_header_bytes};
+
+ EXPECT_FALSE(short_ble_advertisement_header.IsValid());
+}
+
+} // namespace
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_advertisement_test.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_advertisement_test.cc
new file mode 100644
index 00000000000..dbdb531b082
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_advertisement_test.cc
@@ -0,0 +1,455 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/ble_v2/ble_advertisement.h"
+
+#include <algorithm>
+
+#include "gtest/gtest.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+namespace {
+
+constexpr BleAdvertisement::Version kVersion = BleAdvertisement::Version::kV2;
+constexpr BleAdvertisement::SocketVersion kSocketVersion =
+ BleAdvertisement::SocketVersion::kV2;
+constexpr absl::string_view kServiceIDHashBytes{"\x0a\x0b\x0c"};
+constexpr absl::string_view kData{
+ "How much wood can a woodchuck chuck if a wood chuck would chuck wood?"};
+constexpr absl::string_view kFastData{"Fast Advertise"};
+constexpr absl::string_view kDeviceToken{"\x04\x20"};
+// kAdvertisementLength/kFastAdvertisementLength corresponds to the length of a
+// specific BleAdvertisement packed with the kData/kFastData given above. Be
+// sure to update this if kData/kFastData ever changes.
+constexpr size_t kAdvertisementLength = 77;
+constexpr size_t kFastAdvertisementLength = 16;
+constexpr size_t kLongAdvertisementLength = kAdvertisementLength + 1000;
+
+TEST(BleAdvertisementTest, ConstructionWorksV1) {
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ ByteArray data{std::string(kData)};
+ ByteArray device_token{std::string(kDeviceToken)};
+
+ BleAdvertisement ble_advertisement{BleAdvertisement::Version::kV1,
+ BleAdvertisement::SocketVersion::kV1,
+ service_id_hash, data, device_token};
+
+ EXPECT_TRUE(ble_advertisement.IsValid());
+ EXPECT_FALSE(ble_advertisement.IsFastAdvertisement());
+ EXPECT_EQ(BleAdvertisement::Version::kV1, ble_advertisement.GetVersion());
+ EXPECT_EQ(BleAdvertisement::SocketVersion::kV1,
+ ble_advertisement.GetSocketVersion());
+ EXPECT_EQ(service_id_hash, ble_advertisement.GetServiceIdHash());
+ EXPECT_EQ(data.size(), ble_advertisement.GetData().size());
+ EXPECT_EQ(data, ble_advertisement.GetData());
+ EXPECT_EQ(device_token, ble_advertisement.GetDeviceToken());
+}
+
+TEST(BleAdvertisementTest, ConstructionWorksV1ForFastAdvertisement) {
+ ByteArray fast_data{std::string(kFastData)};
+ ByteArray device_token{std::string(kDeviceToken)};
+
+ BleAdvertisement ble_advertisement{BleAdvertisement::Version::kV1,
+ BleAdvertisement::SocketVersion::kV1,
+ ByteArray{}, fast_data, device_token};
+
+ EXPECT_TRUE(ble_advertisement.IsValid());
+ EXPECT_TRUE(ble_advertisement.IsFastAdvertisement());
+ EXPECT_EQ(BleAdvertisement::Version::kV1, ble_advertisement.GetVersion());
+ EXPECT_EQ(BleAdvertisement::SocketVersion::kV1,
+ ble_advertisement.GetSocketVersion());
+ EXPECT_EQ(fast_data.size(), ble_advertisement.GetData().size());
+ EXPECT_EQ(fast_data, ble_advertisement.GetData());
+ EXPECT_EQ(device_token, ble_advertisement.GetDeviceToken());
+}
+
+TEST(BleAdvertisementTest, ConstructionFailsWithBadVersion) {
+ BleAdvertisement::Version bad_version =
+ static_cast<BleAdvertisement::Version>(666);
+
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ ByteArray data{std::string(kData)};
+ ByteArray device_token{std::string(kDeviceToken)};
+
+ BleAdvertisement ble_advertisement{bad_version, kSocketVersion,
+ service_id_hash, data, device_token};
+ EXPECT_FALSE(ble_advertisement.IsValid());
+
+ BleAdvertisement fast_ble_advertisement{bad_version, kSocketVersion,
+ ByteArray{}, data, device_token};
+ EXPECT_FALSE(fast_ble_advertisement.IsValid());
+}
+
+TEST(BleAdvertisementTest, ConstructionFailsWithBadSocketVersion) {
+ BleAdvertisement::SocketVersion bad_socket_version =
+ static_cast<BleAdvertisement::SocketVersion>(666);
+
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ ByteArray data{std::string(kData)};
+ ByteArray device_token{std::string(kDeviceToken)};
+
+ BleAdvertisement ble_advertisement{kVersion, bad_socket_version,
+ service_id_hash, data, device_token};
+ EXPECT_FALSE(ble_advertisement.IsValid());
+
+ BleAdvertisement fast_ble_advertisement{kVersion, bad_socket_version,
+ ByteArray{}, data, device_token};
+ EXPECT_FALSE(fast_ble_advertisement.IsValid());
+}
+
+TEST(BleAdvertisementTest, ConstructionFailsWithShortServiceIdHash) {
+ char short_service_id_hash_bytes[] = "\x0a\x0b";
+
+ ByteArray bad_service_id_hash{short_service_id_hash_bytes};
+ ByteArray data{std::string(kData)};
+ ByteArray device_token{std::string(kDeviceToken)};
+
+ BleAdvertisement ble_advertisement{kVersion, kSocketVersion,
+ bad_service_id_hash, data, device_token};
+
+ EXPECT_FALSE(ble_advertisement.IsValid());
+}
+
+TEST(BleAdvertisementTest, ConstructionFailsWithLongServiceIdHash) {
+ char long_service_id_hash_bytes[] = "\x0a\x0b\x0c\x0d";
+
+ ByteArray bad_service_id_hash{long_service_id_hash_bytes};
+ ByteArray data{std::string(kData)};
+ ByteArray device_token{std::string(kDeviceToken)};
+
+ BleAdvertisement ble_advertisement{kVersion, kSocketVersion,
+ bad_service_id_hash, data, device_token};
+
+ EXPECT_FALSE(ble_advertisement.IsValid());
+}
+
+TEST(BleAdvertisementTest, ConstructionFailsWithLongData) {
+ // BleAdvertisement shouldn't be able to support data with the max GATT
+ // attribute length because it needs some room for the preceding fields.
+ char long_data[512]{};
+
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ ByteArray bad_data{long_data, 512};
+ ByteArray device_token{std::string(kDeviceToken)};
+
+ BleAdvertisement ble_advertisement{kVersion, kSocketVersion, service_id_hash,
+ bad_data, device_token};
+ EXPECT_FALSE(ble_advertisement.IsValid());
+
+ BleAdvertisement fast_ble_advertisement{kVersion, kSocketVersion, ByteArray{},
+ bad_data, device_token};
+ EXPECT_FALSE(fast_ble_advertisement.IsValid());
+}
+
+TEST(BleAdvertisementTest, ConstructionWorksWithEmptyDeviceToken) {
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ ByteArray data{std::string(kData)};
+
+ BleAdvertisement ble_advertisement{kVersion, kSocketVersion, service_id_hash,
+ data, ByteArray{}};
+
+ EXPECT_TRUE(ble_advertisement.IsValid());
+ EXPECT_FALSE(ble_advertisement.IsFastAdvertisement());
+ EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
+ EXPECT_EQ(kSocketVersion, ble_advertisement.GetSocketVersion());
+ EXPECT_EQ(service_id_hash, ble_advertisement.GetServiceIdHash());
+ EXPECT_EQ(data.size(), ble_advertisement.GetData().size());
+ EXPECT_EQ(data, ble_advertisement.GetData());
+ EXPECT_TRUE(ble_advertisement.GetDeviceToken().Empty());
+}
+
+TEST(BleAdvertisementTest,
+ ConstructionWorksWithEmptyDeviceTokenForFastAdvertisement) {
+ ByteArray fast_data{std::string(kFastData)};
+
+ BleAdvertisement ble_advertisement{kVersion, kSocketVersion, ByteArray{},
+ fast_data, ByteArray{}};
+
+ EXPECT_TRUE(ble_advertisement.IsValid());
+ EXPECT_TRUE(ble_advertisement.IsFastAdvertisement());
+ EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
+ EXPECT_EQ(kSocketVersion, ble_advertisement.GetSocketVersion());
+ EXPECT_EQ(fast_data.size(), ble_advertisement.GetData().size());
+ EXPECT_EQ(fast_data, ble_advertisement.GetData());
+ EXPECT_TRUE(ble_advertisement.GetDeviceToken().Empty());
+}
+
+TEST(BleAdvertisementTest, ConstructionFailsWithWrongSizeofDeviceToken) {
+ char wrong_device_token_bytes_1[] = "\x04\x2\x10"; // over 2 bytes
+ char wrong_device_token_bytes_2[] = "\x04"; // 1 byte
+
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ ByteArray data{std::string(kData)};
+ ByteArray bad_device_token_1{wrong_device_token_bytes_1};
+ ByteArray bad_device_token_2{wrong_device_token_bytes_2};
+
+ BleAdvertisement ble_advertisement_1{
+ kVersion, kSocketVersion, service_id_hash, data, bad_device_token_1};
+ EXPECT_FALSE(ble_advertisement_1.IsValid());
+
+ BleAdvertisement ble_advertisement_2{
+ kVersion, kSocketVersion, service_id_hash, data, bad_device_token_2};
+ EXPECT_FALSE(ble_advertisement_2.IsValid());
+
+ BleAdvertisement fast_ble_advertisement_1{
+ kVersion, kSocketVersion, ByteArray{}, data, bad_device_token_1};
+ EXPECT_FALSE(fast_ble_advertisement_1.IsValid());
+
+ BleAdvertisement fast_ble_advertisement_2{
+ kVersion, kSocketVersion, ByteArray{}, data, bad_device_token_2};
+ EXPECT_FALSE(fast_ble_advertisement_2.IsValid());
+}
+
+TEST(BleAdvertisementTest, ConstructionFromSerializedBytesWorks) {
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ ByteArray data{std::string(kData)};
+ ByteArray device_token{std::string(kDeviceToken)};
+
+ BleAdvertisement org_ble_advertisement{kVersion, kSocketVersion,
+ service_id_hash, data, device_token};
+
+ ByteArray ble_advertisement_bytes{org_ble_advertisement};
+ BleAdvertisement ble_advertisement{ble_advertisement_bytes};
+
+ EXPECT_TRUE(ble_advertisement.IsValid());
+ EXPECT_FALSE(ble_advertisement.IsFastAdvertisement());
+ EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
+ EXPECT_EQ(kSocketVersion, ble_advertisement.GetSocketVersion());
+ EXPECT_EQ(service_id_hash, ble_advertisement.GetServiceIdHash());
+ EXPECT_EQ(data.size(), ble_advertisement.GetData().size());
+ EXPECT_EQ(data, ble_advertisement.GetData());
+ EXPECT_EQ(device_token, ble_advertisement.GetDeviceToken());
+}
+
+TEST(BleAdvertisementTest,
+ ConstructionFromSerializedBytesWorksForAdvertisement) {
+ ByteArray fast_data{std::string(kFastData)};
+ ByteArray device_token{std::string(kDeviceToken)};
+
+ BleAdvertisement org_ble_advertisement{kVersion, kSocketVersion, ByteArray{},
+ fast_data, device_token};
+
+ ByteArray ble_advertisement_bytes{org_ble_advertisement};
+ BleAdvertisement ble_advertisement{ble_advertisement_bytes};
+
+ EXPECT_TRUE(ble_advertisement.IsValid());
+ EXPECT_TRUE(ble_advertisement.IsFastAdvertisement());
+ EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
+ EXPECT_EQ(kSocketVersion, ble_advertisement.GetSocketVersion());
+ EXPECT_EQ(fast_data.size(), ble_advertisement.GetData().size());
+ EXPECT_EQ(fast_data, ble_advertisement.GetData());
+ EXPECT_EQ(device_token, ble_advertisement.GetDeviceToken());
+}
+
+TEST(BleAdvertisementTest, ConstructionFromSerializedBytesWithEmptyDataWorks) {
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ ByteArray device_token{std::string(kDeviceToken)};
+
+ BleAdvertisement org_ble_advertisement{
+ kVersion, kSocketVersion, service_id_hash, ByteArray(), device_token};
+ ByteArray ble_advertisement_bytes{org_ble_advertisement};
+ BleAdvertisement ble_advertisement{ble_advertisement_bytes};
+
+ EXPECT_TRUE(ble_advertisement.IsValid());
+ EXPECT_FALSE(ble_advertisement.IsFastAdvertisement());
+ EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
+ EXPECT_EQ(kSocketVersion, ble_advertisement.GetSocketVersion());
+ EXPECT_EQ(service_id_hash, ble_advertisement.GetServiceIdHash());
+ EXPECT_TRUE(ble_advertisement.GetData().Empty());
+ EXPECT_EQ(device_token, ble_advertisement.GetDeviceToken());
+}
+
+TEST(BleAdvertisementTest,
+ ConstructionFromSerializedBytesWithEmptyDataWorksForFastAdvertisement) {
+ ByteArray device_token{std::string(kDeviceToken)};
+
+ BleAdvertisement org_ble_advertisement{kVersion, kSocketVersion, ByteArray{},
+ ByteArray(), device_token};
+ ByteArray ble_advertisement_bytes{org_ble_advertisement};
+ BleAdvertisement ble_advertisement{ble_advertisement_bytes};
+
+ EXPECT_TRUE(ble_advertisement.IsValid());
+ EXPECT_TRUE(ble_advertisement.IsFastAdvertisement());
+ EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
+ EXPECT_EQ(kSocketVersion, ble_advertisement.GetSocketVersion());
+ EXPECT_TRUE(ble_advertisement.GetData().Empty());
+ EXPECT_EQ(device_token, ble_advertisement.GetDeviceToken());
+}
+
+TEST(BleAdvertisementTest, ConstructionFromExtraSerializedBytesWorks) {
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ ByteArray data{std::string(kData)};
+ ByteArray device_token{std::string(kDeviceToken)};
+
+ BleAdvertisement org_ble_advertisement{kVersion, kSocketVersion,
+ service_id_hash, data, device_token};
+ ByteArray org_ble_advertisement_bytes{org_ble_advertisement};
+
+ // Copy the bytes into a new array with extra bytes. We must explicitly
+ // define how long our array is because we can't use variable length arrays.
+ char raw_ble_advertisement_bytes[kLongAdvertisementLength]{};
+ memcpy(raw_ble_advertisement_bytes, org_ble_advertisement_bytes.data(),
+ std::min(sizeof(raw_ble_advertisement_bytes),
+ org_ble_advertisement_bytes.size()));
+
+ // Re-parse the Ble advertisement using our extra long advertisement bytes.
+ ByteArray long_ble_advertisement_bytes{raw_ble_advertisement_bytes,
+ kLongAdvertisementLength};
+ BleAdvertisement long_ble_advertisement{long_ble_advertisement_bytes};
+
+ EXPECT_TRUE(long_ble_advertisement.IsValid());
+ EXPECT_FALSE(long_ble_advertisement.IsFastAdvertisement());
+ EXPECT_EQ(kVersion, long_ble_advertisement.GetVersion());
+ EXPECT_EQ(kSocketVersion, long_ble_advertisement.GetSocketVersion());
+ EXPECT_EQ(service_id_hash, long_ble_advertisement.GetServiceIdHash());
+ EXPECT_EQ(data.size(), long_ble_advertisement.GetData().size());
+ EXPECT_EQ(data, long_ble_advertisement.GetData());
+ EXPECT_EQ(device_token, long_ble_advertisement.GetDeviceToken());
+}
+
+TEST(BleAdvertisementTest,
+ ConstructionFromExtraSerializedBytesWorksForFastAdvertisement) {
+ ByteArray fast_data{std::string(kFastData)};
+ ByteArray device_token{std::string(kDeviceToken)};
+
+ BleAdvertisement org_ble_advertisement{kVersion, kSocketVersion, ByteArray{},
+ fast_data, device_token};
+ ByteArray org_ble_advertisement_bytes{org_ble_advertisement};
+
+ // Copy the bytes into a new array with extra bytes. We must explicitly
+ // define how long our array is because we can't use variable length arrays.
+ char raw_ble_advertisement_bytes[kLongAdvertisementLength]{};
+ memcpy(raw_ble_advertisement_bytes, org_ble_advertisement_bytes.data(),
+ std::min(sizeof(raw_ble_advertisement_bytes),
+ org_ble_advertisement_bytes.size()));
+
+ // Re-parse the Ble advertisement using our extra long advertisement bytes.
+ ByteArray long_ble_advertisement_bytes{raw_ble_advertisement_bytes,
+ kLongAdvertisementLength};
+ BleAdvertisement long_ble_advertisement{long_ble_advertisement_bytes};
+
+ EXPECT_TRUE(long_ble_advertisement.IsValid());
+ EXPECT_TRUE(long_ble_advertisement.IsFastAdvertisement());
+ EXPECT_EQ(kVersion, long_ble_advertisement.GetVersion());
+ EXPECT_EQ(kSocketVersion, long_ble_advertisement.GetSocketVersion());
+ EXPECT_EQ(fast_data.size(), long_ble_advertisement.GetData().size());
+ EXPECT_EQ(fast_data, long_ble_advertisement.GetData());
+ EXPECT_EQ(device_token, long_ble_advertisement.GetDeviceToken());
+}
+
+TEST(BleAdvertisementTest, ConstructionFromNullBytesFails) {
+ BleAdvertisement ble_advertisement{ByteArray{}};
+
+ EXPECT_FALSE(ble_advertisement.IsValid());
+}
+
+TEST(BleAdvertisementTest, ConstructionFromShortLengthSerializedBytesFails) {
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ ByteArray data{std::string(kData)};
+ ByteArray device_token{std::string(kDeviceToken)};
+
+ BleAdvertisement org_ble_advertisement{kVersion, kSocketVersion,
+ service_id_hash, data, device_token};
+ ByteArray org_ble_advertisement_bytes{org_ble_advertisement};
+
+ // Cut off the advertisement so that it's too short.
+ ByteArray short_ble_advertisement_bytes{org_ble_advertisement_bytes.data(),
+ 7};
+ BleAdvertisement short_ble_advertisement{short_ble_advertisement_bytes};
+
+ EXPECT_FALSE(short_ble_advertisement.IsValid());
+}
+
+TEST(BleAdvertisementTest,
+ ConstructionFromShortLengthSerializedBytesFailsForFastAdvertisement) {
+ ByteArray fast_data{std::string(kFastData)};
+ ByteArray device_token{std::string(kDeviceToken)};
+
+ BleAdvertisement org_ble_advertisement{kVersion, kSocketVersion, ByteArray{},
+ fast_data, device_token};
+ ByteArray org_ble_advertisement_bytes{org_ble_advertisement};
+
+ // Cut off the advertisement so that it's too short.
+ ByteArray short_ble_advertisement_bytes{org_ble_advertisement_bytes.data(),
+ 2};
+ BleAdvertisement short_ble_advertisement{short_ble_advertisement_bytes};
+
+ EXPECT_FALSE(short_ble_advertisement.IsValid());
+}
+
+TEST(BleAdvertisementTest,
+ ConstructionFromSerializedBytesWithInvalidDataLengthFails) {
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ ByteArray data{std::string(kData)};
+ ByteArray device_token{std::string(kDeviceToken)};
+
+ BleAdvertisement org_ble_advertisement{kVersion, kSocketVersion,
+ service_id_hash, data, device_token};
+ ByteArray org_ble_advertisement_bytes{org_ble_advertisement};
+
+ // Corrupt the DATA_SIZE bits. Start by making a raw copy of the Ble
+ // advertisement bytes so we can modify it. We must explicitly define how
+ // long our array is because we can't use variable length arrays.
+ char raw_ble_advertisement_bytes[kAdvertisementLength];
+ memcpy(raw_ble_advertisement_bytes, org_ble_advertisement_bytes.data(),
+ kAdvertisementLength);
+
+ // The data size field lives in indices 4-7. Corrupt it.
+ memset(raw_ble_advertisement_bytes + 4, 0xFF, 4);
+
+ // Try to parse the Ble advertisement using our corrupted advertisement bytes.
+ ByteArray corrupted_ble_advertisement_bytes{raw_ble_advertisement_bytes,
+ kAdvertisementLength};
+ BleAdvertisement corrupted_ble_advertisement{
+ corrupted_ble_advertisement_bytes};
+
+ EXPECT_FALSE(corrupted_ble_advertisement.IsValid());
+}
+
+TEST(BleAdvertisementTest,
+ ConstructionFromSerializedBytesWithInvalidDataLengthFails2) {
+ ByteArray fast_data{std::string(kFastData)};
+ ByteArray device_token{std::string(kDeviceToken)};
+
+ BleAdvertisement org_ble_advertisement{kVersion, kSocketVersion, ByteArray{},
+ fast_data, device_token};
+ ByteArray org_ble_advertisement_bytes{org_ble_advertisement};
+
+ // Corrupt the DATA_SIZE bits. Start by making a raw copy of the Ble
+ // advertisement bytes so we can modify it. We must explicitly define how
+ // long our array is because we can't use variable length arrays.
+ char raw_ble_advertisement_bytes[kFastAdvertisementLength];
+ memcpy(raw_ble_advertisement_bytes, org_ble_advertisement_bytes.data(),
+ kFastAdvertisementLength);
+
+ // The data size field lives in index 1. Corrupt it.
+ memset(raw_ble_advertisement_bytes + 1, 0xFF, 1);
+
+ // Try to parse the Ble advertisement using our corrupted advertisement bytes.
+ ByteArray corrupted_ble_advertisement_bytes{raw_ble_advertisement_bytes,
+ kFastAdvertisementLength};
+ BleAdvertisement corrupted_ble_advertisement{
+ corrupted_ble_advertisement_bytes};
+
+ EXPECT_FALSE(corrupted_ble_advertisement.IsValid());
+}
+
+} // namespace
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_packet.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_packet.cc
new file mode 100644
index 00000000000..ddeeadf6de1
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_packet.cc
@@ -0,0 +1,73 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/ble_v2/ble_packet.h"
+
+#include "absl/strings/str_cat.h"
+#include "internal/platform/base_input_stream.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+BlePacket::BlePacket(const ByteArray& service_id_hash, const ByteArray& data) {
+ if (service_id_hash.size() != kServiceIdHashLength ||
+ data.size() > kMaxDataSize) {
+ return;
+ }
+ service_id_hash_ = service_id_hash;
+ data_ = data;
+}
+
+BlePacket::BlePacket(const ByteArray& ble_packet_bytes) {
+ if (ble_packet_bytes.Empty()) {
+ NEARBY_LOG(ERROR, "Cannot deserialize BlePacket: null bytes passed in");
+ return;
+ }
+
+ if (ble_packet_bytes.size() < kServiceIdHashLength) {
+ NEARBY_LOG(
+ INFO,
+ "Cannot deserialize BlePacket: expecting min %u raw bytes, got %zu",
+ kServiceIdHashLength, ble_packet_bytes.size());
+ return;
+ }
+
+ ByteArray packet_bytes{ble_packet_bytes};
+ BaseInputStream base_input_stream{packet_bytes};
+ // The first 3 bytes are supposed to be the service_id_hash.
+ service_id_hash_ = base_input_stream.ReadBytes(kServiceIdHashLength);
+
+ // The rest bytes are supposed to be the data.
+ data_ = base_input_stream.ReadBytes(ble_packet_bytes.size() -
+ kServiceIdHashLength);
+}
+
+BlePacket::operator ByteArray() const {
+ if (!IsValid()) {
+ return ByteArray();
+ }
+
+ std::string out =
+ absl::StrCat(std::string(service_id_hash_), std::string(data_));
+
+ return ByteArray(std::move(out));
+}
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_packet.h b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_packet.h
new file mode 100644
index 00000000000..f83af7c7c7d
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_packet.h
@@ -0,0 +1,64 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MEDIUMS_BLE_V2_BLE_PACKET_H_
+#define CORE_INTERNAL_MEDIUMS_BLE_V2_BLE_PACKET_H_
+
+#include <limits>
+
+#include "internal/platform/byte_array.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+// Represents the format of data sent over Ble sockets.
+//
+// [SERVICE_ID_HASH][DATA]
+//
+// See go/nearby-ble-design for more information.
+class BlePacket {
+ public:
+ static const std::uint32_t kServiceIdHashLength = 3;
+
+ BlePacket() = default;
+ BlePacket(const ByteArray& service_id_hash, const ByteArray& data);
+ explicit BlePacket(const ByteArray& ble_packet_byte);
+ BlePacket(const BlePacket&) = default;
+ BlePacket& operator=(const BlePacket&) = default;
+ BlePacket(BlePacket&&) = default;
+ BlePacket& operator=(BlePacket&&) = default;
+ ~BlePacket() = default;
+
+ explicit operator ByteArray() const;
+
+ bool IsValid() const { return !service_id_hash_.Empty(); }
+ ByteArray GetServiceIdHash() const { return service_id_hash_; }
+ ByteArray GetData() const { return data_; }
+
+ private:
+ static const std::uint32_t kMaxDataSize =
+ std::numeric_limits<int32_t>::max() - kServiceIdHashLength;
+
+ ByteArray service_id_hash_;
+ ByteArray data_;
+};
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MEDIUMS_BLE_V2_BLE_PACKET_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_packet_test.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_packet_test.cc
new file mode 100644
index 00000000000..4c6f393ba6e
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_packet_test.cc
@@ -0,0 +1,111 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/ble_v2/ble_packet.h"
+
+#include "gtest/gtest.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+constexpr absl::string_view kServiceIDHash{"\x0a\x0b\x0c"};
+constexpr absl::string_view kData{"\x01\x02\x03\x04\x05"};
+
+TEST(BlePacketTest, ConstructionWorks) {
+ ByteArray service_id_hash{std::string(kServiceIDHash)};
+ ByteArray data{std::string(kData)};
+
+ BlePacket ble_packet{service_id_hash, data};
+
+ EXPECT_TRUE(ble_packet.IsValid());
+ EXPECT_EQ(service_id_hash, ble_packet.GetServiceIdHash());
+ EXPECT_EQ(data, ble_packet.GetData());
+}
+
+TEST(BlePacketTest, ConstructionWorksWithEmptyData) {
+ char empty_data[] = "";
+
+ ByteArray service_id_hash{std::string(kServiceIDHash)};
+ ByteArray data{empty_data};
+
+ BlePacket ble_packet{service_id_hash, data};
+
+ EXPECT_TRUE(ble_packet.IsValid());
+ EXPECT_EQ(service_id_hash, ble_packet.GetServiceIdHash());
+ EXPECT_EQ(data, ble_packet.GetData());
+}
+
+TEST(BlePacketTest, ConstructionFailsWithShortServiceIdHash) {
+ char short_service_id_hash[] = "\x0a\x0b";
+
+ ByteArray service_id_hash{short_service_id_hash};
+ ByteArray data{std::string(kData)};
+
+ BlePacket ble_packet(service_id_hash, data);
+
+ EXPECT_FALSE(ble_packet.IsValid());
+}
+
+TEST(BlePacketTest, ConstructionFailsWithLongServiceIdHash) {
+ char long_service_id_hash[] = "\x0a\x0b\x0c\x0d";
+
+ ByteArray service_id_hash{long_service_id_hash};
+ ByteArray data{std::string(kData)};
+
+ BlePacket ble_packet{service_id_hash, data};
+
+ EXPECT_FALSE(ble_packet.IsValid());
+}
+
+TEST(BlePacketTest, ConstructionFromSerializedBytesWorks) {
+ ByteArray service_id_hash{std::string(kServiceIDHash)};
+ ByteArray data{std::string(kData)};
+
+ BlePacket org_ble_packet{service_id_hash, data};
+ ByteArray ble_packet_bytes{org_ble_packet};
+
+ BlePacket ble_packet{ble_packet_bytes};
+
+ EXPECT_TRUE(ble_packet.IsValid());
+ EXPECT_EQ(service_id_hash, ble_packet.GetServiceIdHash());
+ EXPECT_EQ(data, ble_packet.GetData());
+}
+
+TEST(BlePacketTest, ConstructionFromNullBytesFails) {
+ BlePacket ble_packet{ByteArray{}};
+
+ EXPECT_FALSE(ble_packet.IsValid());
+}
+
+TEST(BlePacketTest, ConstructionFromShortLengthDataFails) {
+ ByteArray service_id_hash{std::string(kServiceIDHash)};
+ ByteArray data{std::string(kData)};
+
+ BlePacket org_ble_packet{service_id_hash, data};
+ ByteArray org_ble_packet_bytes{org_ble_packet};
+
+ // Cut off the packet so that it's too short
+ ByteArray short_ble_packet_bytes{ByteArray{org_ble_packet_bytes.data(), 2}};
+
+ BlePacket short_ble_packet{short_ble_packet_bytes};
+
+ EXPECT_FALSE(short_ble_packet.IsValid());
+}
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_peripheral.h b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_peripheral.h
new file mode 100644
index 00000000000..e3ef5c36eab
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_peripheral.h
@@ -0,0 +1,49 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MEDIUMS_BLE_V2_BLE_PERIPHERAL_H_
+#define CORE_INTERNAL_MEDIUMS_BLE_V2_BLE_PERIPHERAL_H_
+
+#include "internal/platform/byte_array.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+class BlePeripheral {
+ public:
+ BlePeripheral() = default;
+ explicit BlePeripheral(const ByteArray& id) : id_(id) {}
+ BlePeripheral(const BlePeripheral&) = default;
+ BlePeripheral& operator=(const BlePeripheral&) = default;
+ BlePeripheral(BlePeripheral&&) = default;
+ BlePeripheral& operator=(BlePeripheral&&) = default;
+ ~BlePeripheral() = default;
+
+ bool IsValid() const { return !id_.Empty(); }
+ ByteArray GetId() const { return id_; }
+
+ private:
+ // A unique identifier for this peripheral. It can be the BLE advertisement it
+ // was found on, or even simply the BLE MAC address.
+ ByteArray id_;
+};
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MEDIUMS_BLE_V2_BLE_PERIPHERAL_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_peripheral_test.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_peripheral_test.cc
new file mode 100644
index 00000000000..56b4b6640ea
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/ble_peripheral_test.cc
@@ -0,0 +1,47 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/ble_v2/ble_peripheral.h"
+
+#include "gtest/gtest.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+namespace {
+
+constexpr absl::string_view kId{"AB12"};
+
+TEST(BlePeripheralTest, ConstructionWorks) {
+ ByteArray id{std::string(kId)};
+
+ BlePeripheral ble_peripheral{id};
+
+ EXPECT_TRUE(ble_peripheral.IsValid());
+ EXPECT_EQ(id, ble_peripheral.GetId());
+}
+
+TEST(BlePeripheralTest, ConstructionEmptyFails) {
+ BlePeripheral ble_peripheral;
+
+ EXPECT_FALSE(ble_peripheral.IsValid());
+ EXPECT_TRUE(ble_peripheral.GetId().Empty());
+}
+
+} // namespace
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/bloom_filter.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/bloom_filter.cc
new file mode 100644
index 00000000000..36bc7c797b9
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/bloom_filter.cc
@@ -0,0 +1,105 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/ble_v2/bloom_filter.h"
+
+#include "absl/numeric/int128.h"
+#include "absl/strings/numbers.h"
+#include "src/MurmurHash3.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+BloomFilterBase::BloomFilterBase(const ByteArray& bytes, BitSet* bit_set)
+ : bits_(bit_set) {
+ const char* bytes_read_ptr = bytes.data();
+ for (size_t byte_index = 0; byte_index < bytes.size(); byte_index++) {
+ for (size_t bit_index = 0; bit_index < 8; bit_index++) {
+ bits_->Set((byte_index * 8) + bit_index,
+ (*bytes_read_ptr >> bit_index) & 0x01);
+ }
+ bytes_read_ptr++;
+ }
+}
+
+BloomFilterBase::operator ByteArray() const {
+ // Gets a binary string representation of the bitset where the leftmost
+ // character corresponds to bitset position (total size) - 1.
+ //
+ // If the bitset's internal representation is:
+ // [position 0] 0 0 1 1 0 0 0 1 0 1 0 1 [position 11]
+ // The string representation will be outputted like this:
+ // "1 0 1 0 1 0 0 0 1 1 0 0"
+ std::string bitset_binary_string = bits_->ToString();
+
+ ByteArray result_bytes(GetMinBytesForBits());
+ char* result_bytes_write_ptr = result_bytes.data();
+ // We go through the string backwards because the rightmost character
+ // corresponds to position 0 in the bitset.
+ for (size_t i = bits_->Size(); i > 0; i -= 8) {
+ std::string byte_binary_string = bitset_binary_string.substr(i - 8, 8);
+ std::uint32_t byte_value;
+ absl::numbers_internal::safe_strtou32_base(byte_binary_string, &byte_value,
+ /* base= */ 2);
+ *result_bytes_write_ptr = static_cast<char>(byte_value & 0x000000FF);
+ result_bytes_write_ptr++;
+ }
+ return result_bytes;
+}
+
+void BloomFilterBase::Add(const std::string& s) {
+ std::vector<std::int32_t> hashes = GetHashes(s);
+ for (int32_t hash : hashes) {
+ size_t position = static_cast<size_t>(hash) % bits_->Size();
+ bits_->Set(position, true);
+ }
+}
+
+bool BloomFilterBase::PossiblyContains(const std::string& s) {
+ std::vector<std::int32_t> hashes = GetHashes(s);
+ for (int32_t hash : hashes) {
+ size_t position = static_cast<size_t>(hash) % bits_->Size();
+ if (!bits_->Test(position)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+std::vector<std::int32_t> BloomFilterBase::GetHashes(const std::string& s) {
+ std::vector<std::int32_t> hashes(kHasherNumberOfRepetitions, 0);
+
+ absl::uint128 hash128;
+ MurmurHash3_x64_128(s.data(), s.size(), 0, &hash128);
+ std::uint64_t hash64 =
+ absl::Uint128Low64(hash128); // the lower 64 bits of the 128-bit hash
+ std::int32_t hash1 = static_cast<std::int32_t>(
+ hash64 & 0x00000000FFFFFFFF); // the lower 32 bits of the 64-bit hash
+ std::int32_t hash2 = static_cast<std::int32_t>(
+ (hash64 >> 32) & 0x0FFFFFFFF); // the upper 32 bits of the 64-bit hash
+ for (size_t i = 1; i <= kHasherNumberOfRepetitions; i++) {
+ std::int32_t combinedHash = static_cast<std::int32_t>(hash1 + (i * hash2));
+ // Flip all the bits if it's negative (guaranteed positive number)
+ if (combinedHash < 0) combinedHash = ~combinedHash;
+ hashes[i - 1] = combinedHash;
+ }
+ return hashes;
+}
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/bloom_filter.h b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/bloom_filter.h
new file mode 100644
index 00000000000..18f69d3eb2f
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/bloom_filter.h
@@ -0,0 +1,101 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MEDIUMS_BLE_V2_BLOOM_FILTER_H_
+#define CORE_INTERNAL_MEDIUMS_BLE_V2_BLOOM_FILTER_H_
+
+#include <bitset>
+#include <vector>
+
+#include "internal/platform/byte_array.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+/**
+ * A bloom filter that gives access to the underlying BitSet. The implementation
+ * is copied from our Java version of Bloom filter, which in turn copies from
+ * Guava's BloomFilter.
+ *
+ * BloomFilter is templatized on the size of the byte array and not the size of
+ * the bit set to ensure the bit set's length is a multiple of 8 (and can
+ * neatly be returned as a ByteArray).
+ */
+class BloomFilterBase {
+ public:
+ explicit operator ByteArray() const;
+
+ void Add(const std::string& s);
+ bool PossiblyContains(const std::string& s);
+
+ protected:
+ class BitSet {
+ public:
+ virtual ~BitSet() = default;
+ virtual std::string ToString() const = 0;
+ virtual void Set(size_t pos, bool value) = 0;
+ virtual bool Test(size_t pos) const = 0;
+ virtual size_t Size() const = 0;
+ };
+
+ BloomFilterBase(const ByteArray& bytes, BitSet* bit_set);
+ virtual ~BloomFilterBase() = default;
+
+ constexpr static int kHasherNumberOfRepetitions = 5;
+ std::vector<std::int32_t> GetHashes(const std::string& s);
+
+ private:
+ int GetMinBytesForBits() const { return (bits_->Size() + 7) >> 3; }
+
+ BitSet* bits_;
+};
+
+template <size_t CapacityInBytes>
+class BloomFilter final : public BloomFilterBase {
+ public:
+ BloomFilter() : BloomFilterBase(ByteArray{}, &bits_) {}
+ explicit BloomFilter(const ByteArray& bytes)
+ : BloomFilterBase(bytes, &bits_) {}
+ BloomFilter(const BloomFilter&) = default;
+ BloomFilter& operator=(const BloomFilter&) = default;
+ BloomFilter(BloomFilter&& other) : BloomFilterBase(ByteArray{}, &bits_) {
+ *this = std::move(other);
+ }
+ BloomFilter& operator=(BloomFilter&& other) {
+ std::swap((*this).bits_, other.bits_);
+ return *this;
+ }
+ ~BloomFilter() override = default;
+
+ private:
+ class BitSetImpl final : public BitSet {
+ public:
+ std::string ToString() const override { return bits_.to_string(); }
+ void Set(size_t pos, bool value) override { bits_.set(pos, value); }
+ bool Test(size_t pos) const override { return bits_.test(pos); }
+ size_t Size() const override { return bits_.size(); }
+
+ private:
+ std::bitset<CapacityInBytes * 8> bits_;
+ } bits_;
+};
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MEDIUMS_BLE_V2_BLOOM_FILTER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/bloom_filter_test.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/bloom_filter_test.cc
new file mode 100644
index 00000000000..c2bf7b155c2
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/bloom_filter_test.cc
@@ -0,0 +1,207 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/ble_v2/bloom_filter.h"
+
+#include <algorithm>
+
+#include "gtest/gtest.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+namespace {
+
+constexpr size_t kByteArrayLength = 100;
+
+TEST(BloomFilterTest, EmptyFilterReturnsEmptyArray) {
+ BloomFilter<kByteArrayLength> bloom_filter;
+
+ ByteArray bloom_filter_bytes(bloom_filter);
+ std::string empty_string(kByteArrayLength, '\0');
+
+ EXPECT_EQ(empty_string, std::string(bloom_filter_bytes));
+}
+
+TEST(BloomFilterTest, EmptyFilterNeverContains) {
+ BloomFilter<kByteArrayLength> bloom_filter;
+
+ EXPECT_FALSE(bloom_filter.PossiblyContains("ELEMENT_1"));
+ EXPECT_FALSE(bloom_filter.PossiblyContains("ELEMENT_2"));
+ EXPECT_FALSE(bloom_filter.PossiblyContains("ELEMENT_3"));
+}
+
+TEST(BloomFilterTest, AddSuccess) {
+ BloomFilter<kByteArrayLength> bloom_filter;
+
+ EXPECT_FALSE(bloom_filter.PossiblyContains("ELEMENT_1"));
+
+ bloom_filter.Add("ELEMENT_1");
+
+ EXPECT_TRUE(bloom_filter.PossiblyContains("ELEMENT_1"));
+}
+
+TEST(BloomFilterTest, AddOnlyGivenArg) {
+ BloomFilter<kByteArrayLength> bloom_filter;
+
+ bloom_filter.Add("ELEMENT_1");
+
+ EXPECT_TRUE(bloom_filter.PossiblyContains("ELEMENT_1"));
+ EXPECT_FALSE(bloom_filter.PossiblyContains("ELEMENT_2"));
+ EXPECT_FALSE(bloom_filter.PossiblyContains("ELEMENT_3"));
+}
+
+TEST(BloomFilterTest, AddMultipleArgs) {
+ BloomFilter<kByteArrayLength> bloom_filter;
+
+ bloom_filter.Add("ELEMENT_1");
+ bloom_filter.Add("ELEMENT_2");
+
+ EXPECT_TRUE(bloom_filter.PossiblyContains("ELEMENT_1"));
+ EXPECT_TRUE(bloom_filter.PossiblyContains("ELEMENT_2"));
+ EXPECT_FALSE(bloom_filter.PossiblyContains("ELEMENT_3"));
+}
+
+TEST(BloomFilterTest, AddMultipleArgsReturnsNonemptyArray) {
+ BloomFilter<10> bloom_filter;
+
+ bloom_filter.Add("ELEMENT_1");
+ bloom_filter.Add("ELEMENT_2");
+ bloom_filter.Add("ELEMENT_3");
+
+ ByteArray bloom_filter_bytes(bloom_filter);
+ std::string empty_string(kByteArrayLength, '\0');
+
+ EXPECT_NE(std::string(bloom_filter_bytes), empty_string);
+}
+
+TEST(BloomFilterTest, CopyConstructorAndAssignmentSuccess) {
+ BloomFilter<kByteArrayLength> bloom_filter;
+
+ EXPECT_FALSE(bloom_filter.PossiblyContains("ELEMENT_1"));
+
+ bloom_filter.Add("ELEMENT_1");
+
+ BloomFilter<kByteArrayLength> bloom_filter_copy_1{bloom_filter};
+ BloomFilter<kByteArrayLength> bloom_filter_copy_2 = bloom_filter;
+
+ EXPECT_TRUE(bloom_filter.PossiblyContains("ELEMENT_1"));
+ EXPECT_TRUE(bloom_filter_copy_1.PossiblyContains("ELEMENT_1"));
+ EXPECT_TRUE(bloom_filter_copy_2.PossiblyContains("ELEMENT_1"));
+}
+
+TEST(BloomFilterTest, MoveConstructorSuccess) {
+ BloomFilter<kByteArrayLength> bloom_filter;
+
+ bloom_filter.Add("ELEMENT_1");
+
+ BloomFilter<kByteArrayLength> bloom_filter_move{std::move(bloom_filter)};
+
+ EXPECT_TRUE(bloom_filter_move.PossiblyContains("ELEMENT_1"));
+}
+
+TEST(BloomFilterTest, MoveAssignmentSuccess) {
+ BloomFilter<kByteArrayLength> bloom_filter;
+
+ bloom_filter.Add("ELEMENT_1");
+
+ BloomFilter<kByteArrayLength> bloom_filter_move = std::move(bloom_filter);
+
+ EXPECT_TRUE(bloom_filter_move.PossiblyContains("ELEMENT_1"));
+}
+
+/**
+ * This test was added because of a bug where the BloomFilter doesn't utilize
+ * all bits given. Functionally, the filter still works, but we just have a much
+ * higher false positive rate. The bug was caused by confusing bit length and
+ * byte length, which made our BloomFilter only set bits on the first byteLength
+ * (bitLength / 8) bits rather than the whole bitLength bits.
+ *
+ * <p>Here, we're verifying that the bits set are somewhat scattered. So instead
+ * of something like [ 0, 1, 1, 0, 0, 0, 0, ..., 0 ], we should be getting
+ * something like [ 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, ..., 1, 0].
+ */
+TEST(BloomFilterTest, RandomnessNoEndBias) {
+ BloomFilter<kByteArrayLength> bloom_filter;
+
+ // Add one element to our BloomFilter.
+ bloom_filter.Add("ELEMENT_1");
+
+ std::int32_t non_zero_count = 0;
+ std::int32_t longest_zero_streak = 0;
+ std::int32_t current_zero_streak = 0;
+
+ // Record the amount of non-zero bytes and the longest streak of zero bytes in
+ // the resulting BloomFilter. This is an approximation of reasonable
+ // distribution since we're recording by bytes instead of bits.
+ ByteArray bloom_filter_bytes(bloom_filter);
+ const char* bloom_filter_bytes_read_ptr = bloom_filter_bytes.data();
+ for (int i = 0; i < bloom_filter_bytes.size(); i++) {
+ if (*bloom_filter_bytes_read_ptr == '\0') {
+ current_zero_streak++;
+ } else {
+ // Increment the number of non-zero bytes we've seen, update the longest
+ // zero streak, and then reset the current zero streak.
+ non_zero_count++;
+ longest_zero_streak = std::max(longest_zero_streak, current_zero_streak);
+ current_zero_streak = 0;
+ }
+ bloom_filter_bytes_read_ptr++;
+ }
+ // Update the longest zero streak again for the tail case.
+ longest_zero_streak = std::min(longest_zero_streak, current_zero_streak);
+
+ // Since randomness is hard to measure within one unit test, we instead do a
+ // sanity check. All non-zero bytes should not be packed into one end of the
+ // array.
+ //
+ // In this case, the size of one end is approximated to be:
+ // kByteArrayLength / nonZeroCount.
+ // Therefore, the longest zero streak should be less than:
+ // kByteArrayLength - one end of the array.
+ std::int32_t longest_acceptable_zero_streak =
+ kByteArrayLength - (kByteArrayLength / non_zero_count);
+
+ EXPECT_TRUE(longest_zero_streak <= longest_acceptable_zero_streak);
+}
+
+TEST(BloomFilterTest, RandomnessFalsePositiveRate) {
+ BloomFilter<10> bloom_filter;
+
+ // Add 5 distinct elements to the BloomFilter.
+ bloom_filter.Add("ELEMENT_1");
+ bloom_filter.Add("ELEMENT_2");
+ bloom_filter.Add("ELEMENT_3");
+ bloom_filter.Add("ELEMENT_4");
+ bloom_filter.Add("ELEMENT_5");
+
+ std::int32_t false_positives = 0;
+ // Now test 100 other elements and record the number of false positives.
+ for (int i = 5; i < 105; i++) {
+ false_positives +=
+ bloom_filter.PossiblyContains("ELEMENT_" + std::to_string(i)) ? 1 : 0;
+ }
+
+ // We expect the false positive rate to be 3% with 5 elements in a 10 byte
+ // filter. Thus, we give a little leeway and verify that the false positive
+ // rate is no more than 5%.
+ EXPECT_LE(false_positives, 5);
+}
+
+} // namespace
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/discovered_peripheral_callback.h b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/discovered_peripheral_callback.h
new file mode 100644
index 00000000000..ce920242ad3
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/ble_v2/discovered_peripheral_callback.h
@@ -0,0 +1,45 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MEDIUMS_BLE_V2_DISCOVERED_PERIPHERAL_CALLBACK_H_
+#define CORE_INTERNAL_MEDIUMS_BLE_V2_DISCOVERED_PERIPHERAL_CALLBACK_H_
+
+#include "connections/implementation/mediums/ble_v2/ble_peripheral.h"
+#include "connections/listeners.h"
+#include "internal/platform/byte_array.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+/** Callback that is invoked when a {@link BlePeripheral} is discovered. */
+struct DiscoveredPeripheralCallback {
+ std::function<void(BlePeripheral& peripheral, const std::string& service_id,
+ const ByteArray& advertisement_byts,
+ bool fast_advertisement)>
+ peripheral_discovered_cb =
+ DefaultCallback<BlePeripheral&, const std::string&, const ByteArray&,
+ bool>();
+ std::function<void(BlePeripheral& peripheral, const std::string& service_id)>
+ peripheral_lost_cb =
+ DefaultCallback<BlePeripheral&, const std::string&>();
+};
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MEDIUMS_BLE_V2_DISCOVERED_PERIPHERAL_CALLBACK_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/bluetooth_classic.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/bluetooth_classic.cc
new file mode 100644
index 00000000000..9d3eb084dfe
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/bluetooth_classic.cc
@@ -0,0 +1,434 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/bluetooth_classic.h"
+
+#include <memory>
+#include <string>
+#include <utility>
+
+#include "connections/implementation/mediums/uuid.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/mutex_lock.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+BluetoothClassic::BluetoothClassic(BluetoothRadio& radio) : radio_(radio) {}
+
+BluetoothClassic::~BluetoothClassic() {
+ // Destructor is not taking locks, but methods it is calling are.
+ StopDiscovery();
+ while (!server_sockets_.empty()) {
+ StopAcceptingConnections(server_sockets_.begin()->first);
+ }
+ TurnOffDiscoverability();
+
+ // All the AcceptLoopRunnable objects in here should already have gotten an
+ // opportunity to shut themselves down cleanly in the calls to
+ // StopAcceptingConnections() above.
+ accept_loops_runner_.Shutdown();
+}
+
+bool BluetoothClassic::IsAvailable() const {
+ MutexLock lock(&mutex_);
+
+ return IsAvailableLocked();
+}
+
+bool BluetoothClassic::IsAvailableLocked() const {
+ return medium_.IsValid() && adapter_.IsValid();
+}
+
+bool BluetoothClassic::TurnOnDiscoverability(const std::string& device_name) {
+ MutexLock lock(&mutex_);
+
+ if (device_name.empty()) {
+ NEARBY_LOG(INFO,
+ "Refusing to turn on BT discoverability. Empty device name.");
+ return false;
+ }
+
+ if (!radio_.IsEnabled()) {
+ NEARBY_LOG(INFO, "Can't turn on BT discoverability. BT is off.");
+ return false;
+ }
+
+ if (!IsAvailableLocked()) {
+ NEARBY_LOG(INFO, "Can't turn on BT discoverability. BT is not available.");
+ return false;
+ }
+
+ if (IsDiscoverable()) {
+ NEARBY_LOG(INFO,
+ "Refusing to turn on BT discoverability; new name='%s'; "
+ "current name='%s'",
+ device_name.c_str(), adapter_.GetName().c_str());
+ return false;
+ }
+
+ if (!ModifyDeviceName(device_name)) {
+ NEARBY_LOG(INFO,
+ "Failed to turn on BT discoverability; "
+ "failed to set name to %s",
+ device_name.c_str());
+ return false;
+ }
+
+ if (!ModifyScanMode(ScanMode::kConnectableDiscoverable)) {
+ NEARBY_LOG(INFO,
+ "Failed to turn on BT discoverability; "
+ "failed to set scan_mode to %d",
+ ScanMode::kConnectableDiscoverable);
+
+ // Don't forget to perform this rollback of the partial state changes we've
+ // made til now.
+ RestoreDeviceName();
+ return false;
+ }
+
+ NEARBY_LOG(INFO, "Turned on BT discoverability with device_name=%s",
+ device_name.c_str());
+ return true;
+}
+
+bool BluetoothClassic::TurnOffDiscoverability() {
+ MutexLock lock(&mutex_);
+
+ if (!IsDiscoverable()) {
+ NEARBY_LOG(INFO, "Can't turn off BT discoverability; it is already off");
+ return false;
+ }
+
+ RestoreScanMode();
+ RestoreDeviceName();
+
+ NEARBY_LOG(INFO, "Turned Bluetooth discoverability off");
+ return true;
+}
+
+bool BluetoothClassic::IsDiscoverable() const {
+ return (!original_device_name_.empty() &&
+ (adapter_.GetScanMode() == ScanMode::kConnectableDiscoverable));
+}
+
+bool BluetoothClassic::ModifyDeviceName(const std::string& device_name) {
+ if (original_device_name_.empty()) {
+ original_device_name_ = adapter_.GetName();
+ }
+
+ return adapter_.SetName(device_name);
+}
+
+bool BluetoothClassic::ModifyScanMode(ScanMode scan_mode) {
+ if (original_scan_mode_ == ScanMode::kUnknown) {
+ original_scan_mode_ = adapter_.GetScanMode();
+ }
+
+ if (!adapter_.SetScanMode(scan_mode)) {
+ original_scan_mode_ = ScanMode::kUnknown;
+ return false;
+ }
+
+ return true;
+}
+
+bool BluetoothClassic::RestoreScanMode() {
+ if (original_scan_mode_ == ScanMode::kUnknown ||
+ !adapter_.SetScanMode(original_scan_mode_)) {
+ NEARBY_LOG(INFO, "Failed to restore original Bluetooth scan mode to %d",
+ original_scan_mode_);
+ return false;
+ }
+
+ // Regardless of whether or not we could actually restore the Bluetooth scan
+ // mode, reset our relevant state.
+ original_scan_mode_ = ScanMode::kUnknown;
+ return true;
+}
+
+bool BluetoothClassic::RestoreDeviceName() {
+ if (original_device_name_.empty() ||
+ !adapter_.SetName(original_device_name_)) {
+ NEARBY_LOG(INFO, "Failed to restore original Bluetooth device name to %s",
+ original_device_name_.c_str());
+ return false;
+ }
+ original_device_name_.clear();
+ return true;
+}
+
+bool BluetoothClassic::StartDiscovery(DiscoveredDeviceCallback callback) {
+ MutexLock lock(&mutex_);
+
+ if (!radio_.IsEnabled()) {
+ NEARBY_LOG(INFO, "Can't discover BT devices because BT isn't enabled.");
+ return false;
+ }
+
+ if (!IsAvailableLocked()) {
+ NEARBY_LOG(INFO, "Can't discover BT devices because BT isn't available.");
+ return false;
+ }
+
+ if (IsDiscovering()) {
+ NEARBY_LOG(INFO,
+ "Refusing to start discovery of BT devices because another "
+ "discovery is already in-progress.");
+ return false;
+ }
+
+ if (!medium_.StartDiscovery(callback)) {
+ NEARBY_LOG(INFO, "Failed to start discovery of BT devices.");
+ return false;
+ }
+
+ // Mark the fact that we're currently performing a Bluetooth scan.
+ scan_info_.valid = true;
+
+ return true;
+}
+
+bool BluetoothClassic::StopDiscovery() {
+ MutexLock lock(&mutex_);
+
+ if (!IsDiscovering()) {
+ NEARBY_LOG(INFO,
+ "Can't stop discovery of BT devices because it never started.");
+ return false;
+ }
+
+ if (!medium_.StopDiscovery()) {
+ NEARBY_LOG(INFO, "Failed to stop discovery of Bluetooth devices.");
+ return false;
+ }
+
+ scan_info_.valid = false;
+ return true;
+}
+
+bool BluetoothClassic::IsDiscovering() const { return scan_info_.valid; }
+
+bool BluetoothClassic::StartAcceptingConnections(
+ const std::string& service_name, AcceptedConnectionCallback callback) {
+ MutexLock lock(&mutex_);
+
+ if (service_name.empty()) {
+ NEARBY_LOG(
+ INFO,
+ "Refusing to start accepting BT connections; service name is empty.");
+ return false;
+ }
+
+ if (!radio_.IsEnabled()) {
+ NEARBY_LOG(INFO,
+ "Can't create BT server socket [service=%s]; BT is disabled.",
+ service_name.c_str());
+ return false;
+ }
+
+ if (!IsAvailableLocked()) {
+ NEARBY_LOG(
+ INFO,
+ "Can't start accepting BT connections [service=%s]; BT not available.",
+ service_name.c_str());
+ return false;
+ }
+
+ if (IsAcceptingConnectionsLocked(service_name)) {
+ NEARBY_LOG(INFO,
+ "Refusing to start accepting BT connections [service=%s]; BT "
+ "server is already in-progress with the same name.",
+ service_name.c_str());
+ return false;
+ }
+
+ BluetoothServerSocket socket = medium_.ListenForService(
+ service_name, GenerateUuidFromString(service_name));
+ if (!socket.IsValid()) {
+ NEARBY_LOG(INFO, "Failed to start accepting Bluetooth connections for %s.",
+ service_name.c_str());
+ return false;
+ }
+
+ // Mark the fact that there's an in-progress Bluetooth server accepting
+ // connections.
+ auto owned_socket =
+ server_sockets_.emplace(service_name, std::move(socket)).first->second;
+
+ // Start the accept loop on a dedicated thread - this stays alive and
+ // listening for new incoming connections until StopAcceptingConnections() is
+ // invoked.
+ accept_loops_runner_.Execute(
+ "bt-accept",
+ [callback = std::move(callback), server_socket = std::move(owned_socket),
+ service_name]() mutable {
+ while (true) {
+ BluetoothSocket client_socket = server_socket.Accept();
+ if (!client_socket.IsValid()) {
+ server_socket.Close();
+ break;
+ }
+
+ callback.accepted_cb(std::move(client_socket));
+ }
+ });
+
+ return true;
+}
+
+bool BluetoothClassic::IsAcceptingConnections(const std::string& service_name) {
+ MutexLock lock(&mutex_);
+
+ return IsAcceptingConnectionsLocked(service_name);
+}
+
+bool BluetoothClassic::IsAcceptingConnectionsLocked(
+ const std::string& service_name) {
+ return server_sockets_.find(service_name) != server_sockets_.end();
+}
+
+bool BluetoothClassic::StopAcceptingConnections(
+ const std::string& service_name) {
+ MutexLock lock(&mutex_);
+
+ if (service_name.empty()) {
+ NEARBY_LOG(INFO,
+ "Unable to stop accepting BT connections because the "
+ "service_name is empty.");
+ return false;
+ }
+
+ const auto& it = server_sockets_.find(service_name);
+ if (it == server_sockets_.end()) {
+ NEARBY_LOG(INFO,
+ "Can't stop accepting BT connections for %s because it was "
+ "never started.",
+ service_name.c_str());
+ return false;
+ }
+
+ // Closing the BluetoothServerSocket will kick off the suicide of the thread
+ // in accept_loops_thread_pool_ that blocks on BluetoothServerSocket.accept().
+ // That may take some time to complete, but there's no particular reason to
+ // wait around for it.
+ auto item = server_sockets_.extract(it);
+
+ // Store a handle to the BluetoothServerSocket, so we can use it after
+ // removing the entry from server_sockets_; making it scoped
+ // is a bonus that takes care of deallocation before we leave this method.
+ BluetoothServerSocket& listening_socket = item.mapped();
+
+ // Regardless of whether or not we fail to close the existing
+ // BluetoothServerSocket, remove it from server_sockets_ so that it
+ // frees up this service for another round.
+
+ // Finally, close the BluetoothServerSocket.
+ if (!listening_socket.Close().Ok()) {
+ NEARBY_LOG(INFO, "Failed to close BT server socket for %s.",
+ service_name.c_str());
+ return false;
+ }
+
+ return true;
+}
+
+BluetoothSocket BluetoothClassic::Connect(BluetoothDevice& bluetooth_device,
+ const std::string& service_name,
+ CancellationFlag* cancellation_flag) {
+ for (int attempts_count = 0; attempts_count < kConnectAttemptsLimit;
+ attempts_count++) {
+ auto wrapper_result =
+ AttemptToConnect(bluetooth_device, service_name, cancellation_flag);
+ if (wrapper_result.IsValid()) {
+ return wrapper_result;
+ }
+ }
+ return BluetoothSocket();
+}
+
+BluetoothSocket BluetoothClassic::AttemptToConnect(
+ BluetoothDevice& bluetooth_device, const std::string& service_name,
+ CancellationFlag* cancellation_flag) {
+ MutexLock lock(&mutex_);
+ NEARBY_LOG(INFO, "BluetoothClassic::Connect: device=%p", &bluetooth_device);
+ // Socket to return. To allow for NRVO to work, it has to be a single object.
+ BluetoothSocket socket;
+
+ if (service_name.empty()) {
+ NEARBY_LOG(
+ INFO,
+ "Refusing to create client BT socket because service_name is empty.");
+ return socket;
+ }
+
+ if (!radio_.IsEnabled()) {
+ NEARBY_LOG(INFO,
+ "Can't create client BT socket [service=%s]: BT isn't enabled.",
+ service_name.c_str());
+ return socket;
+ }
+
+ if (!IsAvailableLocked()) {
+ NEARBY_LOG(
+ INFO, "Can't create client BT socket [service=%s]; BT isn't available.",
+ service_name.c_str());
+ return socket;
+ }
+
+ if (cancellation_flag->Cancelled()) {
+ NEARBY_LOGS(INFO) << "Can't create client BT socket due to cancel.";
+ return socket;
+ }
+
+ socket = medium_.ConnectToService(bluetooth_device,
+ GenerateUuidFromString(service_name),
+ cancellation_flag);
+ if (!socket.IsValid()) {
+ NEARBY_LOG(INFO, "Failed to Connect via BT [service=%s]",
+ service_name.c_str());
+ }
+
+ return socket;
+}
+
+BluetoothDevice BluetoothClassic::GetRemoteDevice(
+ const std::string& mac_address) {
+ MutexLock lock(&mutex_);
+
+ if (!IsAvailableLocked()) {
+ return {};
+ }
+
+ return medium_.GetRemoteDevice(mac_address);
+}
+
+std::string BluetoothClassic::GetMacAddress() const {
+ MutexLock lock(&mutex_);
+
+ if (!IsAvailableLocked()) {
+ return {};
+ }
+
+ return medium_.GetMacAddress();
+}
+
+std::string BluetoothClassic::GenerateUuidFromString(const std::string& data) {
+ return std::string(Uuid(data));
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/bluetooth_classic.h b/chromium/third_party/nearby/src/connections/implementation/mediums/bluetooth_classic.h
new file mode 100644
index 00000000000..40e974ef5f0
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/bluetooth_classic.h
@@ -0,0 +1,210 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MEDIUMS_BLUETOOTH_CLASSIC_H_
+#define CORE_INTERNAL_MEDIUMS_BLUETOOTH_CLASSIC_H_
+
+#include <cstdint>
+#include <string>
+
+#include "absl/container/flat_hash_map.h"
+#include "connections/implementation/mediums/bluetooth_radio.h"
+#include "connections/listeners.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/cancellation_flag.h"
+#include "internal/platform/bluetooth_adapter.h"
+#include "internal/platform/bluetooth_classic.h"
+#include "internal/platform/multi_thread_executor.h"
+#include "internal/platform/mutex.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+class BluetoothClassic {
+ public:
+ using DiscoveredDeviceCallback = BluetoothClassicMedium::DiscoveryCallback;
+ using ScanMode = BluetoothAdapter::ScanMode;
+
+ // Callback that is invoked when a new connection is accepted.
+ struct AcceptedConnectionCallback {
+ std::function<void(BluetoothSocket socket)> accepted_cb =
+ DefaultCallback<BluetoothSocket>();
+ };
+
+ explicit BluetoothClassic(BluetoothRadio& bluetooth_radio);
+ ~BluetoothClassic();
+
+ // Returns true, if BT communications are supported by a platform.
+ bool IsAvailable() const ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Sets custom device name, and then enables BT discoverable mode.
+ // Returns true, if name and scan mode are successfully set, and false
+ // otherwise.
+ // Called by server.
+ bool TurnOnDiscoverability(const std::string& device_name)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Disables BT discoverability, and restores scan mode and device name to
+ // what they were before the call to TurnOnDiscoverability().
+ // Returns false if no successful call TurnOnDiscoverability() was previously
+ // made, otherwise returns true.
+ // Called by server.
+ bool TurnOffDiscoverability() ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Enables BT discovery mode. Will report any discoverable devices in range
+ // through a callback.
+ // Returns true, if discovery mode was enabled, false otherwise.
+ // Called by client.
+ bool StartDiscovery(DiscoveredDeviceCallback callback)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Disables BT discovery mode.
+ // Returns true, if discovery mode was previously enabled, false otherwise.
+ // Called by client.
+ bool StopDiscovery() ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Starts a worker thread, creates a BT server socket, associates it with a
+ // service name; in a worker thread repeatedly calls ServerSocket::Accept().
+ // Any connected sockets returned from Accept() are passed to a callback.
+ // Returns true, if server socket was successfully created, false otherwise.
+ // Called by server.
+ bool StartAcceptingConnections(const std::string& service_name,
+ AcceptedConnectionCallback callback)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns true, if object is currently running a Accept() loop.
+ bool IsAcceptingConnections(const std::string& service_name)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Closes server socket corresponding to a service name. This automatically
+ // terminates Accept() loop, if it were running.
+ // Called by server.
+ bool StopAcceptingConnections(const std::string& service_name)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns true if this object owns a valid platform implementation.
+ bool IsMediumValid() const ABSL_LOCKS_EXCLUDED(mutex_) {
+ MutexLock lock(&mutex_);
+ return medium_.IsValid();
+ }
+
+ // Returns true if this object has a valid BluetoothAdapter reference.
+ bool IsAdapterValid() const ABSL_LOCKS_EXCLUDED(mutex_) {
+ MutexLock lock(&mutex_);
+ return adapter_.IsValid();
+ }
+
+ // Establishes connection to BT service with internal retry for maximum
+ // attempts of kConnectAttemptsLimit.
+ // Blocks until connection is established, or server-side is terminated.
+ // Returns socket instance. On success, BluetoothSocket.IsValid() return true.
+ // Called by client.
+ BluetoothSocket Connect(BluetoothDevice& bluetooth_device,
+ const std::string& service_name,
+ CancellationFlag* cancellation_flag)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ std::string GetMacAddress() const ABSL_LOCKS_EXCLUDED(mutex_);
+
+ BluetoothDevice GetRemoteDevice(const std::string& mac_address)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ private:
+ struct ScanInfo {
+ bool valid = false;
+ };
+
+ static constexpr int kMaxConcurrentAcceptLoops = 5;
+
+ static constexpr int kConnectAttemptsLimit = 3;
+
+ // Constructs UUID object from arbitrary string, using MD5 hash, and then
+ // converts UUID to a readable UUID string and returns it.
+ static std::string GenerateUuidFromString(const std::string& data);
+
+ // Same as IsAvailable(), but must be called with mutex_ held.
+ bool IsAvailableLocked() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Same as IsAcceptingConnections(), but must be called with mutex_ held.
+ bool IsAcceptingConnectionsLocked(const std::string& service_name)
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Returns true, if discoverability is enabled with TurnOnDiscoverability().
+ bool IsDiscoverable() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Assignes a different name to BT adapter.
+ // Returns true if successful. Stores original device name.
+ bool ModifyDeviceName(const std::string& device_name)
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Changes current scan mode. This is an implementation of
+ // Turn<On/Off>Discoveradility() method. Stores original scan mode.
+ bool ModifyScanMode(ScanMode scan_mode) ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Restores original device name (the one before the very first call to
+ // ModifyDeviceName()). Returns true if successful.
+ bool RestoreScanMode() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Restores original device scan mode (the one before the very first call to
+ // ModifyScanMode()). Returns true if successful.
+ bool RestoreDeviceName() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Returns true if device is currently in discovery mode.
+ bool IsDiscovering() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Establishes connection to BT service that was might be started on another
+ // device with StartAcceptingConnections() using the same service_name.
+ // Blocks until connection is established, or server-side is terminated.
+ // Returns socket instance. On success, BluetoothSocket.IsValid() return true.
+ // Called by client.
+ BluetoothSocket AttemptToConnect(BluetoothDevice& bluetooth_device,
+ const std::string& service_name,
+ CancellationFlag* cancellation_flag);
+
+ mutable Mutex mutex_;
+ BluetoothRadio& radio_ ABSL_GUARDED_BY(mutex_);
+ BluetoothAdapter& adapter_ ABSL_GUARDED_BY(mutex_){
+ radio_.GetBluetoothAdapter()};
+ BluetoothClassicMedium medium_ ABSL_GUARDED_BY(mutex_){adapter_};
+
+ // A bundle of state required to do a Bluetooth Classic scan. When non-null,
+ // we are currently performing a Bluetooth scan.
+ ScanInfo scan_info_ ABSL_GUARDED_BY(mutex_);
+
+ // The original scan mode (that controls visibility to scanners) of the device
+ // before we modified it. Restored when we stop advertising.
+ ScanMode original_scan_mode_ ABSL_GUARDED_BY(mutex_) = ScanMode::kUnknown;
+
+ // The original Bluetooth device name, before we modified it. If non-empty, we
+ // are currently Bluetooth discoverable. Restored when we stop advertising.
+ std::string original_device_name_ ABSL_GUARDED_BY(mutex_);
+
+ // A thread pool dedicated to running all the accept loops from
+ // StartAcceptingConnections().
+ MultiThreadExecutor accept_loops_runner_{kMaxConcurrentAcceptLoops};
+
+ // A map of service Name -> ServerSocket. If map is non-empty, we
+ // are currently listening for incoming connections.
+ // BluetoothServerSocket instances are used from accept_loops_runner_,
+ // and thus require pointer stability.
+ absl::flat_hash_map<std::string, BluetoothServerSocket> server_sockets_
+ ABSL_GUARDED_BY(mutex_);
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MEDIUMS_BLUETOOTH_CLASSIC_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/bluetooth_classic_test.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/bluetooth_classic_test.cc
new file mode 100644
index 00000000000..f1ef2266615
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/bluetooth_classic_test.cc
@@ -0,0 +1,291 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/bluetooth_classic.h"
+
+#include <string>
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "absl/time/time.h"
+#include "connections/implementation/mediums/bluetooth_radio.h"
+#include "internal/platform/medium_environment.h"
+#include "internal/platform/bluetooth_classic.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/system_clock.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+
+using FeatureFlags = FeatureFlags::Flags;
+
+constexpr FeatureFlags kTestCases[] = {
+ FeatureFlags{
+ .enable_cancellation_flag = true,
+ },
+ FeatureFlags{
+ .enable_cancellation_flag = false,
+ },
+};
+
+constexpr absl::Duration kWaitDuration = absl::Milliseconds(1000);
+
+class BluetoothClassicTest : public ::testing::TestWithParam<FeatureFlags> {
+ protected:
+ using DiscoveryCallback = BluetoothClassicMedium::DiscoveryCallback;
+
+ BluetoothClassicTest() {
+ env_.Start();
+ env_.Reset();
+ radio_a_ = std::make_unique<BluetoothRadio>();
+ radio_b_ = std::make_unique<BluetoothRadio>();
+ bt_a_ = std::make_unique<BluetoothClassic>(*radio_a_);
+ bt_b_ = std::make_unique<BluetoothClassic>(*radio_b_);
+ radio_a_->GetBluetoothAdapter().SetName("Device-A");
+ radio_b_->GetBluetoothAdapter().SetName("Device-B");
+ radio_a_->Enable();
+ radio_b_->Enable();
+ env_.Sync();
+ }
+
+ ~BluetoothClassicTest() override {
+ env_.Sync(false);
+ radio_a_->Disable();
+ radio_b_->Disable();
+ bt_a_.reset();
+ bt_b_.reset();
+ env_.Sync(false);
+ radio_a_.reset();
+ radio_b_.reset();
+ env_.Reset();
+ env_.Stop();
+ }
+
+ MediumEnvironment& env_{MediumEnvironment::Instance()};
+
+ std::unique_ptr<BluetoothRadio> radio_a_;
+ std::unique_ptr<BluetoothRadio> radio_b_;
+ std::unique_ptr<BluetoothClassic> bt_a_;
+ std::unique_ptr<BluetoothClassic> bt_b_;
+};
+
+TEST_P(BluetoothClassicTest, CanConnect) {
+ FeatureFlags feature_flags = GetParam();
+ env_.SetFeatureFlags(feature_flags);
+
+ constexpr absl::string_view kDeviceName{"Simulated BT device #1"};
+ constexpr absl::string_view kServiceName{"service name"};
+
+ BluetoothRadio& radio_for_client = *radio_a_;
+ BluetoothRadio& radio_for_server = *radio_b_;
+ BluetoothClassic& bt_client = *bt_a_;
+ BluetoothClassic& bt_server = *bt_b_;
+
+ EXPECT_TRUE(radio_for_client.IsEnabled());
+ EXPECT_TRUE(radio_for_server.IsEnabled());
+
+ EXPECT_TRUE(bt_server.TurnOnDiscoverability(std::string(kDeviceName)));
+ EXPECT_EQ(radio_for_server.GetBluetoothAdapter().GetName(),
+ std::string(kDeviceName));
+ CountDownLatch latch(1);
+ BluetoothDevice discovered_device;
+ EXPECT_TRUE(bt_client.StartDiscovery({
+ .device_discovered_cb =
+ [&latch, &discovered_device](BluetoothDevice& device) {
+ discovered_device = device;
+ NEARBY_LOG(INFO, "Discovered device=%p [impl=%p]", &device,
+ &device.GetImpl());
+ latch.CountDown();
+ },
+ }));
+ EXPECT_TRUE(latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(bt_server.TurnOffDiscoverability());
+ ASSERT_TRUE(discovered_device.IsValid());
+ BluetoothSocket socket_for_server;
+ CountDownLatch accept_latch(1);
+ EXPECT_TRUE(bt_server.StartAcceptingConnections(
+ std::string(kServiceName),
+ {
+ .accepted_cb =
+ [&socket_for_server, &accept_latch](BluetoothSocket socket) {
+ socket_for_server = std::move(socket);
+ accept_latch.CountDown();
+ },
+ }));
+ CancellationFlag flag;
+ BluetoothSocket socket_for_client =
+ bt_client.Connect(discovered_device, std::string(kServiceName), &flag);
+ EXPECT_TRUE(accept_latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(bt_server.StopAcceptingConnections(std::string(kServiceName)));
+ EXPECT_TRUE(socket_for_server.IsValid());
+ EXPECT_TRUE(socket_for_client.IsValid());
+ EXPECT_TRUE(socket_for_server.GetRemoteDevice().IsValid());
+ EXPECT_TRUE(socket_for_client.GetRemoteDevice().IsValid());
+}
+
+TEST_P(BluetoothClassicTest, CanCancelConnect) {
+ FeatureFlags feature_flags = GetParam();
+ env_.SetFeatureFlags(feature_flags);
+
+ constexpr absl::string_view kDeviceName{"Simulated BT device #1"};
+ constexpr absl::string_view kServiceName{"service name"};
+
+ BluetoothRadio& radio_for_client = *radio_a_;
+ BluetoothRadio& radio_for_server = *radio_b_;
+ BluetoothClassic& bt_client = *bt_a_;
+ BluetoothClassic& bt_server = *bt_b_;
+
+ EXPECT_TRUE(radio_for_client.IsEnabled());
+ EXPECT_TRUE(radio_for_server.IsEnabled());
+
+ EXPECT_TRUE(bt_server.TurnOnDiscoverability(std::string(kDeviceName)));
+ EXPECT_EQ(radio_for_server.GetBluetoothAdapter().GetName(),
+ std::string(kDeviceName));
+ CountDownLatch latch(1);
+ BluetoothDevice discovered_device;
+ EXPECT_TRUE(bt_client.StartDiscovery({
+ .device_discovered_cb =
+ [&latch, &discovered_device](BluetoothDevice& device) {
+ discovered_device = device;
+ NEARBY_LOG(INFO, "Discovered device=%p [impl=%p]", &device,
+ &device.GetImpl());
+ latch.CountDown();
+ },
+ }));
+ EXPECT_TRUE(latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(bt_server.TurnOffDiscoverability());
+ ASSERT_TRUE(discovered_device.IsValid());
+ BluetoothSocket socket_for_server;
+ CountDownLatch accept_latch(1);
+ EXPECT_TRUE(bt_server.StartAcceptingConnections(
+ std::string(kServiceName),
+ {
+ .accepted_cb =
+ [&socket_for_server, &accept_latch](BluetoothSocket socket) {
+ socket_for_server = std::move(socket);
+ accept_latch.CountDown();
+ },
+ }));
+ CancellationFlag flag(true);
+ BluetoothSocket socket_for_client =
+ bt_client.Connect(discovered_device, std::string(kServiceName), &flag);
+ // If FeatureFlag is disabled, Cancelled is false as no-op.
+ if (!feature_flags.enable_cancellation_flag) {
+ EXPECT_TRUE(accept_latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(bt_server.StopAcceptingConnections(std::string(kServiceName)));
+ EXPECT_TRUE(socket_for_server.IsValid());
+ EXPECT_TRUE(socket_for_client.IsValid());
+ EXPECT_TRUE(socket_for_server.GetRemoteDevice().IsValid());
+ EXPECT_TRUE(socket_for_client.GetRemoteDevice().IsValid());
+ } else {
+ EXPECT_FALSE(accept_latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(bt_server.StopAcceptingConnections(std::string(kServiceName)));
+ EXPECT_FALSE(socket_for_server.IsValid());
+ EXPECT_FALSE(socket_for_client.IsValid());
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(ParametrisedBluetoothClassicTest, BluetoothClassicTest,
+ ::testing::ValuesIn(kTestCases));
+
+TEST_F(BluetoothClassicTest, CanConstructValidObject) {
+ EXPECT_TRUE(bt_a_->IsMediumValid());
+ EXPECT_TRUE(bt_a_->IsAdapterValid());
+ EXPECT_TRUE(bt_a_->IsAvailable());
+ EXPECT_TRUE(bt_b_->IsMediumValid());
+ EXPECT_TRUE(bt_b_->IsAdapterValid());
+ EXPECT_TRUE(bt_b_->IsAvailable());
+ EXPECT_NE(&radio_a_->GetBluetoothAdapter(), &radio_b_->GetBluetoothAdapter());
+}
+
+TEST_F(BluetoothClassicTest, CanStartAdvertising) {
+ constexpr absl::string_view kDeviceName{"Simulated BT device #1"};
+ EXPECT_TRUE(bt_a_->TurnOnDiscoverability(std::string(kDeviceName)));
+ EXPECT_EQ(radio_a_->GetBluetoothAdapter().GetName(), kDeviceName);
+}
+
+TEST_F(BluetoothClassicTest, CanStopAdvertising) {
+ constexpr absl::string_view kDeviceName{"Simulated BT device #1"};
+ EXPECT_TRUE(bt_a_->TurnOnDiscoverability(std::string(kDeviceName)));
+ EXPECT_EQ(radio_a_->GetBluetoothAdapter().GetName(), kDeviceName);
+ EXPECT_TRUE(bt_a_->TurnOffDiscoverability());
+}
+
+TEST_F(BluetoothClassicTest, CanStartDiscovery) {
+ constexpr absl::string_view kDeviceName{"Simulated BT device #1"};
+ EXPECT_TRUE(bt_a_->TurnOnDiscoverability(std::string(kDeviceName)));
+ EXPECT_EQ(radio_a_->GetBluetoothAdapter().GetName(), kDeviceName);
+ CountDownLatch latch(1);
+ EXPECT_TRUE(bt_b_->StartDiscovery({
+ .device_discovered_cb =
+ [&latch](BluetoothDevice& device) { latch.CountDown(); },
+ }));
+ EXPECT_TRUE(latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(bt_a_->TurnOffDiscoverability());
+}
+
+TEST_F(BluetoothClassicTest, CanStopDiscovery) {
+ CountDownLatch latch(1);
+ EXPECT_TRUE(bt_a_->StartDiscovery({
+ .device_discovered_cb =
+ [&latch](BluetoothDevice& device) { latch.CountDown(); },
+ }));
+ EXPECT_FALSE(latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(bt_a_->StopDiscovery());
+}
+
+TEST_F(BluetoothClassicTest, CanStartAcceptingConnections) {
+ constexpr absl::string_view kDeviceName{"Simulated BT device #1"};
+ constexpr absl::string_view kServiceName{"service name"};
+
+ BluetoothRadio& radio_for_client = *radio_a_;
+ BluetoothRadio& radio_for_server = *radio_b_;
+ BluetoothClassic& bt_client = *bt_a_;
+ BluetoothClassic& bt_server = *bt_b_;
+
+ EXPECT_TRUE(radio_for_client.IsEnabled());
+ EXPECT_TRUE(radio_for_server.IsEnabled());
+
+ EXPECT_TRUE(bt_server.TurnOnDiscoverability(std::string(kDeviceName)));
+ EXPECT_EQ(radio_for_server.GetBluetoothAdapter().GetName(), kDeviceName);
+ CountDownLatch latch(1);
+ BluetoothDevice discovered_device;
+ EXPECT_TRUE(bt_client.StartDiscovery({
+ .device_discovered_cb =
+ [&latch, &discovered_device](BluetoothDevice& device) {
+ discovered_device = device;
+ NEARBY_LOG(INFO, "Discovered device=%p [impl=%p]", &device,
+ &device.GetImpl());
+ latch.CountDown();
+ },
+ }));
+ EXPECT_TRUE(latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(bt_server.TurnOffDiscoverability());
+ EXPECT_TRUE(discovered_device.IsValid());
+ EXPECT_TRUE(
+ bt_server.StartAcceptingConnections(std::string(kServiceName), {}));
+ // Allow StartAcceptingConnections do something, before stopping it.
+ // This is best effort, because no callbacks are invoked in this scenario.
+ SystemClock::Sleep(kWaitDuration);
+ EXPECT_TRUE(bt_server.StopAcceptingConnections(std::string(kServiceName)));
+}
+
+} // namespace
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/bluetooth_radio.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/bluetooth_radio.cc
new file mode 100644
index 00000000000..6fba7d0a61f
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/bluetooth_radio.cc
@@ -0,0 +1,120 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/bluetooth_radio.h"
+
+#include "internal/platform/exception.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/system_clock.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+constexpr absl::Duration BluetoothRadio::kPauseBetweenToggle;
+
+BluetoothRadio::BluetoothRadio() {
+ if (!IsAdapterValid()) {
+ NEARBY_LOG(ERROR, "Bluetooth adapter is not valid: BT is not supported");
+ }
+}
+
+BluetoothRadio::~BluetoothRadio() {
+ // We never enabled Bluetooth, nothing to do.
+ if (!ever_saved_state_.Get()) {
+ NEARBY_LOG(INFO, "BT adapter was not used. Not touching HW.");
+ return;
+ }
+
+ // Toggle Bluetooth regardless of our original state. Some devices/chips can
+ // start to freak out after some time (e.g. b/37775337), and this helps to
+ // ensure BT resets properly.
+ NEARBY_LOG(INFO, "Toggle BT adapter state before releasing adapter.");
+ Toggle();
+
+ NEARBY_LOG(INFO, "Bring BT adapter to original state");
+ if (!SetBluetoothState(originally_enabled_.Get())) {
+ NEARBY_LOG(INFO, "Failed to restore BT adapter original state.");
+ }
+}
+
+bool BluetoothRadio::Enable() {
+ if (!SaveOriginalState()) {
+ return false;
+ }
+
+ return SetBluetoothState(true);
+}
+
+bool BluetoothRadio::Disable() {
+ if (!SaveOriginalState()) {
+ return false;
+ }
+
+ return SetBluetoothState(false);
+}
+
+bool BluetoothRadio::IsEnabled() const {
+ return IsAdapterValid() && IsInDesiredState(true);
+}
+
+bool BluetoothRadio::Toggle() {
+ if (!SaveOriginalState()) {
+ return false;
+ }
+
+ if (!SetBluetoothState(false)) {
+ NEARBY_LOG(INFO, "BT Toggle: Failed to turn BT off.");
+ return false;
+ }
+
+ if (SystemClock::Sleep(kPauseBetweenToggle).Raised(Exception::kInterrupted)) {
+ NEARBY_LOG(INFO, "BT Toggle: interrupted before turing on.");
+ return false;
+ }
+
+ if (!SetBluetoothState(true)) {
+ NEARBY_LOG(INFO, "BT Toggle: Failed to turn BT on.");
+ return false;
+ }
+
+ return true;
+}
+
+bool BluetoothRadio::SetBluetoothState(bool enable) {
+ return bluetooth_adapter_.SetStatus(
+ enable ? BluetoothAdapter::Status::kEnabled
+ : BluetoothAdapter::Status::kDisabled);
+}
+
+bool BluetoothRadio::IsInDesiredState(bool should_be_enabled) const {
+ return bluetooth_adapter_.IsEnabled() == should_be_enabled;
+}
+
+bool BluetoothRadio::SaveOriginalState() {
+ if (!IsAdapterValid()) {
+ return false;
+ }
+
+ // If we haven't saved the original state of the radio, save it.
+ if (!ever_saved_state_.Set(true)) {
+ originally_enabled_.Set(bluetooth_adapter_.IsEnabled());
+ }
+
+ return true;
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/bluetooth_radio.h b/chromium/third_party/nearby/src/connections/implementation/mediums/bluetooth_radio.h
new file mode 100644
index 00000000000..386b412e5cf
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/bluetooth_radio.h
@@ -0,0 +1,90 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MEDIUMS_BLUETOOTH_RADIO_H_
+#define CORE_INTERNAL_MEDIUMS_BLUETOOTH_RADIO_H_
+
+#include <cstdint>
+
+#include "absl/time/clock.h"
+#include "internal/platform/atomic_boolean.h"
+#include "internal/platform/bluetooth_adapter.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Provides the operations that can be performed on the Bluetooth radio.
+class BluetoothRadio {
+ public:
+ BluetoothRadio();
+ BluetoothRadio(BluetoothRadio&&) = default;
+ BluetoothRadio& operator=(BluetoothRadio&&) = default;
+
+ // Reverts the Bluetooth radio to its original state.
+ ~BluetoothRadio();
+
+ // Enables Bluetooth.
+ //
+ // This must be called before attempting to invoke any other methods of
+ // this class.
+ //
+ // Returns true if enabled successfully.
+ bool Enable();
+
+ // Disables Bluetooth.
+ //
+ // Returns true if disabled successfully.
+ bool Disable();
+
+ // Returns true if the Bluetooth radio is currently enabled.
+ bool IsEnabled() const;
+
+ // Turn BT radio Off, delay for kPauseBetweenToggle and then turn it On.
+ // This will block calling thread for at least kPauseBetweenToggle duration.
+ bool Toggle();
+
+ // Returns result of BluetoothAdapter::IsValid() for private adapter instance.
+ bool IsAdapterValid() const { return bluetooth_adapter_.IsValid(); }
+
+ BluetoothAdapter& GetBluetoothAdapter() { return bluetooth_adapter_; }
+
+ private:
+ static constexpr absl::Duration kPauseBetweenToggle = absl::Seconds(3);
+
+ bool SetBluetoothState(bool enable);
+ bool IsInDesiredState(bool should_be_enabled) const;
+ // To be called in enable(), disable(), and toggle(). This will remember the
+ // original state of the radio before any radio state has been modified.
+ // Returns false if Bluetooth doesn't exist on the device and the state cannot
+ // be obtained.
+ bool SaveOriginalState();
+
+ // BluetoothAdapter::IsValid() will return false if BT is not supported.
+ BluetoothAdapter bluetooth_adapter_;
+
+ // The Bluetooth radio's original state, before we modified it. True if
+ // originally enabled, false if originally disabled.
+ // We restore the radio to its original state in the destructor.
+
+ AtomicBoolean originally_enabled_{false};
+ // false if we never modified the radio state, true otherwise.
+ AtomicBoolean ever_saved_state_{false};
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MEDIUMS_BLUETOOTH_RADIO_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/bluetooth_radio_test.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/bluetooth_radio_test.cc
new file mode 100644
index 00000000000..cb939e1c5b4
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/bluetooth_radio_test.cc
@@ -0,0 +1,60 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/bluetooth_radio.h"
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+
+TEST(BluetoothRadioTest, ConstructorDestructorWorks) {
+ BluetoothRadio radio;
+ EXPECT_TRUE(radio.IsAdapterValid());
+}
+
+TEST(BluetoothRadioTest, CanEnable) {
+ BluetoothRadio radio;
+ EXPECT_TRUE(radio.IsAdapterValid());
+ EXPECT_FALSE(radio.IsEnabled());
+ EXPECT_TRUE(radio.Enable());
+ EXPECT_TRUE(radio.IsEnabled());
+}
+
+TEST(BluetoothRadioTest, CanDisable) {
+ BluetoothRadio radio;
+ EXPECT_TRUE(radio.IsAdapterValid());
+ EXPECT_FALSE(radio.IsEnabled());
+ EXPECT_TRUE(radio.Enable());
+ EXPECT_TRUE(radio.IsEnabled());
+ EXPECT_TRUE(radio.Disable());
+ EXPECT_FALSE(radio.IsEnabled());
+}
+
+TEST(BluetoothRadioTest, CanToggle) {
+ BluetoothRadio radio;
+ EXPECT_TRUE(radio.IsAdapterValid());
+ EXPECT_FALSE(radio.IsEnabled());
+ EXPECT_TRUE(radio.Toggle());
+ EXPECT_TRUE(radio.IsEnabled());
+}
+
+} // namespace
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/lost_entity_tracker.h b/chromium/third_party/nearby/src/connections/implementation/mediums/lost_entity_tracker.h
new file mode 100644
index 00000000000..b0795c408a1
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/lost_entity_tracker.h
@@ -0,0 +1,94 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MEDIUMS_LOST_ENTITY_TRACKER_H_
+#define CORE_INTERNAL_MEDIUMS_LOST_ENTITY_TRACKER_H_
+
+#include "absl/container/flat_hash_set.h"
+#include "internal/platform/mutex.h"
+#include "internal/platform/mutex_lock.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+// Tracks "lost" entities based on a manual update/compute model. Used by
+// mediums that only report found devices. Lost entities are computed based off
+// of whether a specific entity was rediscovered since the last call to
+// ComputeLostEntities.
+//
+// Note: Entity must overload the < and == operators.
+template <typename Entity>
+class LostEntityTracker {
+ public:
+ using EntitySet = absl::flat_hash_set<Entity>;
+
+ LostEntityTracker();
+ ~LostEntityTracker();
+
+ // Records the given entity as being recently found, whether or not this is
+ // our first time discovering the entity.
+ void RecordFoundEntity(const Entity& entity) ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Computes and returns the set of entities considered lost since the last
+ // time this method was called.
+ EntitySet ComputeLostEntities() ABSL_LOCKS_EXCLUDED(mutex_);
+
+ private:
+ Mutex mutex_;
+ EntitySet current_entities_ ABSL_GUARDED_BY(mutex_);
+ EntitySet previously_found_entities_ ABSL_GUARDED_BY(mutex_);
+};
+
+template <typename Entity>
+LostEntityTracker<Entity>::LostEntityTracker()
+ : current_entities_{}, previously_found_entities_{} {}
+
+template <typename Entity>
+LostEntityTracker<Entity>::~LostEntityTracker() {
+ previously_found_entities_.clear();
+ current_entities_.clear();
+}
+
+template <typename Entity>
+void LostEntityTracker<Entity>::RecordFoundEntity(const Entity& entity) {
+ MutexLock lock(&mutex_);
+
+ current_entities_.insert(entity);
+}
+
+template <typename Entity>
+typename LostEntityTracker<Entity>::EntitySet
+LostEntityTracker<Entity>::ComputeLostEntities() {
+ MutexLock lock(&mutex_);
+
+ // The set of lost entities is the previously found set MINUS the currently
+ // found set.
+ for (const auto& item : current_entities_) {
+ previously_found_entities_.erase(item);
+ }
+ auto lost_entities = std::move(previously_found_entities_);
+ previously_found_entities_ = std::move(current_entities_);
+ current_entities_ = {};
+
+ return lost_entities;
+}
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MEDIUMS_LOST_ENTITY_TRACKER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/lost_entity_tracker_test.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/lost_entity_tracker_test.cc
new file mode 100644
index 00000000000..b2211ae0828
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/lost_entity_tracker_test.cc
@@ -0,0 +1,137 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/lost_entity_tracker.h"
+
+#include "gtest/gtest.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+namespace {
+
+struct TestEntity {
+ int id;
+
+ template <typename H>
+ friend H AbslHashValue(H h, const TestEntity& test_entity) {
+ return H::combine(std::move(h), test_entity.id);
+ }
+
+ bool operator==(const TestEntity& other) const { return id == other.id; }
+ bool operator<(const TestEntity& other) const { return id < other.id; }
+};
+
+TEST(LostEntityTrackerTest, NoEntitiesLost) {
+ LostEntityTracker<TestEntity> lost_entity_tracker;
+ TestEntity entity_1{1};
+ TestEntity entity_2{2};
+ TestEntity entity_3{3};
+
+ // Discover some entities.
+ lost_entity_tracker.RecordFoundEntity(entity_1);
+ lost_entity_tracker.RecordFoundEntity(entity_2);
+ lost_entity_tracker.RecordFoundEntity(entity_3);
+
+ // Make sure none are lost on the first round.
+ ASSERT_TRUE(lost_entity_tracker.ComputeLostEntities().empty());
+
+ // Rediscover the same entities.
+ lost_entity_tracker.RecordFoundEntity(entity_1);
+ lost_entity_tracker.RecordFoundEntity(entity_2);
+ lost_entity_tracker.RecordFoundEntity(entity_3);
+
+ // Make sure we still didn't lose any entities.
+ EXPECT_TRUE(lost_entity_tracker.ComputeLostEntities().empty());
+}
+
+TEST(LostEntityTrackerTest, AllEntitiesLost) {
+ LostEntityTracker<TestEntity> lost_entity_tracker;
+ TestEntity entity_1{1};
+ TestEntity entity_2{2};
+ TestEntity entity_3{3};
+
+ // Discover some entities.
+ lost_entity_tracker.RecordFoundEntity(entity_1);
+ lost_entity_tracker.RecordFoundEntity(entity_2);
+ lost_entity_tracker.RecordFoundEntity(entity_3);
+
+ // Make sure none are lost on the first round.
+ EXPECT_TRUE(lost_entity_tracker.ComputeLostEntities().empty());
+
+ // Go through a round without rediscovering any entities.
+ typename LostEntityTracker<TestEntity>::EntitySet lost_entities =
+ lost_entity_tracker.ComputeLostEntities();
+ EXPECT_TRUE(lost_entities.find(entity_1) != lost_entities.end());
+ EXPECT_TRUE(lost_entities.find(entity_2) != lost_entities.end());
+ EXPECT_TRUE(lost_entities.find(entity_3) != lost_entities.end());
+}
+
+TEST(LostEntityTrackerTest, SomeEntitiesLost) {
+ LostEntityTracker<TestEntity> lost_entity_tracker;
+ TestEntity entity_1{1};
+ TestEntity entity_2{2};
+ TestEntity entity_3{3};
+
+ // Discover some entities.
+ lost_entity_tracker.RecordFoundEntity(entity_1);
+ lost_entity_tracker.RecordFoundEntity(entity_2);
+
+ // Make sure none are lost on the first round.
+ EXPECT_TRUE(lost_entity_tracker.ComputeLostEntities().empty());
+
+ // Go through the next round only rediscovering one of our entities and
+ // discovering an additional entity as well. Then, verify that only one entity
+ // was lost after the check.
+ lost_entity_tracker.RecordFoundEntity(entity_1);
+ lost_entity_tracker.RecordFoundEntity(entity_3);
+ typename LostEntityTracker<TestEntity>::EntitySet lost_entities =
+ lost_entity_tracker.ComputeLostEntities();
+ EXPECT_TRUE(lost_entities.find(entity_1) == lost_entities.end());
+ EXPECT_TRUE(lost_entities.find(entity_2) != lost_entities.end());
+ EXPECT_TRUE(lost_entities.find(entity_3) == lost_entities.end());
+}
+
+TEST(LostEntityTrackerTest, SameEntityMultipleCopies) {
+ LostEntityTracker<TestEntity> lost_entity_tracker;
+ TestEntity entity_1{1};
+ TestEntity entity_1_copy{1};
+
+ // Discover an entity.
+ lost_entity_tracker.RecordFoundEntity(entity_1);
+
+ // Make sure none are lost on the first round.
+ EXPECT_TRUE(lost_entity_tracker.ComputeLostEntities().empty());
+
+ // Rediscover the same entity, but through a copy of it.
+ lost_entity_tracker.RecordFoundEntity(entity_1_copy);
+
+ // Make sure none are lost on the second round.
+ EXPECT_TRUE(lost_entity_tracker.ComputeLostEntities().empty());
+
+ // Go through a round without rediscovering any entities and verify that we
+ // lost an entity equivalent to both copies of it.
+ typename LostEntityTracker<TestEntity>::EntitySet lost_entities =
+ lost_entity_tracker.ComputeLostEntities();
+ EXPECT_EQ(lost_entities.size(), 1);
+ EXPECT_TRUE(lost_entities.find(entity_1) != lost_entities.end());
+ EXPECT_TRUE(lost_entities.find(entity_1_copy) != lost_entities.end());
+}
+
+} // namespace
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/mediums.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/mediums.cc
new file mode 100644
index 00000000000..e3313180e0a
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/mediums.cc
@@ -0,0 +1,33 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/mediums.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+BluetoothRadio& Mediums::GetBluetoothRadio() { return bluetooth_radio_; }
+
+BluetoothClassic& Mediums::GetBluetoothClassic() { return bluetooth_classic_; }
+
+Ble& Mediums::GetBle() { return ble_; }
+
+WifiLan& Mediums::GetWifiLan() { return wifi_lan_; }
+
+mediums::WebRtc& Mediums::GetWebRtc() { return webrtc_; }
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/mediums.h b/chromium/third_party/nearby/src/connections/implementation/mediums/mediums.h
new file mode 100644
index 00000000000..bea247b5758
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/mediums.h
@@ -0,0 +1,73 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MEDIUMS_MEDIUMS_H_
+#define CORE_INTERNAL_MEDIUMS_MEDIUMS_H_
+
+#include "connections/implementation/mediums/ble.h"
+#include "connections/implementation/mediums/bluetooth_classic.h"
+#include "connections/implementation/mediums/bluetooth_radio.h"
+#ifdef NO_WEBRTC
+#include "connections/implementation/mediums/webrtc_stub.h"
+#else
+#include "connections/implementation/mediums/webrtc.h"
+#endif
+#include "connections/implementation/mediums/wifi_lan.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Facilitates convenient and reliable usage of various wireless mediums.
+class Mediums {
+ public:
+ Mediums() = default;
+ ~Mediums() = default;
+
+ // Returns a handle to the Bluetooth radio.
+ BluetoothRadio& GetBluetoothRadio();
+
+ // Returns a handle to the Bluetooth Classic medium.
+ BluetoothClassic& GetBluetoothClassic();
+
+ // Returns a handle to the Ble medium.
+ Ble& GetBle();
+
+ // Returns a handle to the Wifi-Lan medium.
+ WifiLan& GetWifiLan();
+
+ // Returns a handle to the WebRtc medium.
+ mediums::WebRtc& GetWebRtc();
+
+ private:
+ // The order of declaration is critical for both construction and
+ // destruction.
+ //
+ // 1) Construction: The individual mediums have a dependency on the
+ // corresponding radio, so the radio must be initialized first.
+ //
+ // 2) Destruction: The individual mediums should be shut down before the
+ // corresponding radio.
+ BluetoothRadio bluetooth_radio_;
+ BluetoothClassic bluetooth_classic_{bluetooth_radio_};
+ Ble ble_{bluetooth_radio_};
+ WifiLan wifi_lan_;
+ mediums::WebRtc webrtc_;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MEDIUMS_MEDIUMS_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/utils.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/utils.cc
new file mode 100644
index 00000000000..8930ea20f36
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/utils.cc
@@ -0,0 +1,94 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/utils.h"
+
+#include <memory>
+#include <string>
+
+#include "internal/platform/prng.h"
+#include "internal/platform/crypto.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+namespace {
+constexpr absl::string_view kUpgradeServiceIdPostfix = "_UPGRADE";
+}
+
+ByteArray Utils::GenerateRandomBytes(size_t length) {
+ Prng rng;
+ std::string data;
+ data.reserve(length);
+
+ // Adds 4 random bytes per iteration.
+ while (length > 0) {
+ std::uint32_t val = rng.NextUint32();
+ for (int i = 0; i < 4; i++) {
+ data += val & 0xFF;
+ val >>= 8;
+ length--;
+
+ if (!length) break;
+ }
+ }
+
+ return ByteArray(data);
+}
+
+ByteArray Utils::Sha256Hash(const ByteArray& source, size_t length) {
+ return Utils::Sha256Hash(std::string(source), length);
+}
+
+ByteArray Utils::Sha256Hash(const std::string& source, size_t length) {
+ ByteArray full_hash(length);
+ full_hash.CopyAt(0, Crypto::Sha256(source));
+ return full_hash;
+}
+
+std::string Utils::WrapUpgradeServiceId(const std::string& service_id) {
+ if (service_id.empty()) {
+ return {};
+ }
+ return service_id + std::string(kUpgradeServiceIdPostfix);
+}
+
+std::string Utils::UnwrapUpgradeServiceId(
+ const std::string& upgrade_service_id) {
+ auto pos = upgrade_service_id.find(std::string(kUpgradeServiceIdPostfix));
+ if (pos != std::string::npos) {
+ return std::string(upgrade_service_id, 0, pos);
+ }
+ return upgrade_service_id;
+}
+
+LocationHint Utils::BuildLocationHint(const std::string& location) {
+ LocationHint location_hint;
+ location_hint.set_format(LocationStandard::UNKNOWN);
+
+ if (!location.empty()) {
+ location_hint.set_location(location);
+ if (location.at(0) == '+') {
+ location_hint.set_format(LocationStandard::E164_CALLING);
+ } else {
+ location_hint.set_format(LocationStandard::ISO_3166_1_ALPHA_2);
+ }
+ }
+ return location_hint;
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/utils.h b/chromium/third_party/nearby/src/connections/implementation/mediums/utils.h
new file mode 100644
index 00000000000..01b4496815f
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/utils.h
@@ -0,0 +1,42 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MEDIUMS_UTILS_H_
+#define CORE_INTERNAL_MEDIUMS_UTILS_H_
+
+#include <memory>
+#include <string>
+
+#include "connections/implementation/proto/offline_wire_formats.pb.h"
+#include "internal/platform/byte_array.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+class Utils {
+ public:
+ static ByteArray GenerateRandomBytes(size_t length);
+ static ByteArray Sha256Hash(const ByteArray& source, size_t length);
+ static ByteArray Sha256Hash(const std::string& source, size_t length);
+ static std::string WrapUpgradeServiceId(const std::string& service_id);
+ static std::string UnwrapUpgradeServiceId(const std::string& service_id);
+ static LocationHint BuildLocationHint(const std::string& location);
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MEDIUMS_UTILS_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/uuid.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/uuid.cc
new file mode 100644
index 00000000000..b1e58078ae1
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/uuid.cc
@@ -0,0 +1,87 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/uuid.h"
+
+#include <iomanip>
+#include <sstream>
+
+#include "internal/platform/crypto.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+std::ostream& write_hex(std::ostream& os, absl::string_view data) {
+ for (const auto b : data) {
+ os << std::setfill('0') << std::setw(2) << std::hex
+ << (static_cast<unsigned int>(b) & 0x0ff);
+ }
+ return os;
+}
+} // namespace
+
+Uuid::Uuid(absl::string_view data) : data_(Crypto::Md5(data)) {
+ // Based on the Java counterpart at
+ // http://androidxref.com/8.0.0_r4/xref/libcore/ojluni/src/main/java/java/util/UUID.java#162.
+ data_[6] &= 0x0f; // Clear version.
+ data_[6] |= 0x30; // Set to version 3.
+ data_[8] &= 0x3f; // Clear variant.
+ data_[8] |= 0x80; // Set to IETF variant.
+}
+
+Uuid::Uuid(std::uint64_t most_sig_bits, std::uint64_t least_sig_bits) {
+ // Base on the Java counterpart at
+ // http://androidxref.com/8.0.0_r4/xref/libcore/ojluni/src/main/java/java/util/UUID.java#104.
+ data_.reserve(sizeof(most_sig_bits) + sizeof(least_sig_bits));
+
+ data_[0] = static_cast<char>((most_sig_bits >> 56) & 0x0ff);
+ data_[1] = static_cast<char>((most_sig_bits >> 48) & 0x0ff);
+ data_[2] = static_cast<char>((most_sig_bits >> 40) & 0x0ff);
+ data_[3] = static_cast<char>((most_sig_bits >> 32) & 0x0ff);
+ data_[4] = static_cast<char>((most_sig_bits >> 24) & 0x0ff);
+ data_[5] = static_cast<char>((most_sig_bits >> 16) & 0x0ff);
+ data_[6] = static_cast<char>((most_sig_bits >> 8) & 0x0ff);
+ data_[7] = static_cast<char>((most_sig_bits >> 0) & 0x0ff);
+
+ data_[8] = static_cast<char>((least_sig_bits >> 56) & 0x0ff);
+ data_[9] = static_cast<char>((least_sig_bits >> 48) & 0x0ff);
+ data_[10] = static_cast<char>((least_sig_bits >> 40) & 0x0ff);
+ data_[11] = static_cast<char>((least_sig_bits >> 32) & 0x0ff);
+ data_[12] = static_cast<char>((least_sig_bits >> 24) & 0x0ff);
+ data_[13] = static_cast<char>((least_sig_bits >> 16) & 0x0ff);
+ data_[14] = static_cast<char>((least_sig_bits >> 8) & 0x0ff);
+ data_[15] = static_cast<char>((least_sig_bits >> 0) & 0x0ff);
+}
+
+Uuid::operator std::string() const {
+ // Based on the Java counterpart at
+ // http://androidxref.com/8.0.0_r4/xref/libcore/ojluni/src/main/java/java/util/UUID.java#375.
+ std::ostringstream md5_hex;
+ write_hex(md5_hex, absl::string_view(&data_[0], 4));
+ md5_hex << "-";
+ write_hex(md5_hex, absl::string_view(&data_[4], 2));
+ md5_hex << "-";
+ write_hex(md5_hex, absl::string_view(&data_[6], 2));
+ md5_hex << "-";
+ write_hex(md5_hex, absl::string_view(&data_[8], 2));
+ md5_hex << "-";
+ write_hex(md5_hex, absl::string_view(&data_[10], 6));
+
+ return md5_hex.str();
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/uuid.h b/chromium/third_party/nearby/src/connections/implementation/mediums/uuid.h
index fec9e071c17..fec9e071c17 100644
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/uuid.h
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/uuid.h
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/uuid_test.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/uuid_test.cc
new file mode 100644
index 00000000000..b31fd45196c
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/uuid_test.cc
@@ -0,0 +1,71 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/uuid.h"
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "internal/platform/crypto.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+
+constexpr absl::string_view kString{"some string"};
+constexpr std::uint64_t kNum1 = 0x123456789abcdef0;
+constexpr std::uint64_t kNum2 = 0x21436587a9cbed0f;
+
+TEST(UuidTest, CreateFromStringWithMd5) {
+ Uuid uuid(kString);
+ std::string uuid_str(uuid);
+ std::string uuid_data(uuid.data());
+ std::string md5_data(Crypto::Md5(kString));
+ NEARBY_LOG(INFO, "MD5-based UUID: '%s'", uuid_str.c_str());
+ uuid_data[6] = 0;
+ uuid_data[8] = 0;
+ md5_data[6] = 0;
+ md5_data[8] = 0;
+ EXPECT_EQ(md5_data, uuid_data);
+}
+
+TEST(UuidTest, CreateFromBinary) {
+ Uuid uuid(kNum1, kNum2);
+ std::string uuid_data(uuid.data());
+ std::string uuid_str(uuid);
+ NEARBY_LOG(INFO, "UUID: '%s'", uuid_str.c_str());
+ EXPECT_EQ(uuid_data[0], (kNum1 >> 56) & 0xFF);
+ EXPECT_EQ(uuid_data[1], (kNum1 >> 48) & 0xFF);
+ EXPECT_EQ(uuid_data[2], (kNum1 >> 40) & 0xFF);
+ EXPECT_EQ(uuid_data[3], (kNum1 >> 32) & 0xFF);
+ EXPECT_EQ(uuid_data[4], (kNum1 >> 24) & 0xFF);
+ EXPECT_EQ(uuid_data[5], (kNum1 >> 16) & 0xFF);
+ EXPECT_EQ(uuid_data[6], (kNum1 >> 8) & 0xFF);
+ EXPECT_EQ(uuid_data[7], (kNum1 >> 0) & 0xFF);
+ EXPECT_EQ(uuid_data[8], (kNum2 >> 56) & 0xFF);
+ EXPECT_EQ(uuid_data[9], (kNum2 >> 48) & 0xFF);
+ EXPECT_EQ(uuid_data[10], (kNum2 >> 40) & 0xFF);
+ EXPECT_EQ(uuid_data[11], (kNum2 >> 32) & 0xFF);
+ EXPECT_EQ(uuid_data[12], (kNum2 >> 24) & 0xFF);
+ EXPECT_EQ(uuid_data[13], (kNum2 >> 16) & 0xFF);
+ EXPECT_EQ(uuid_data[14], (kNum2 >> 8) & 0xFF);
+ EXPECT_EQ(uuid_data[15], (kNum2 >> 0) & 0xFF);
+}
+
+} // namespace
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc.cc
new file mode 100644
index 00000000000..8175afa42df
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc.cc
@@ -0,0 +1,744 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/webrtc.h"
+
+#include <functional>
+#include <memory>
+
+#include "absl/functional/bind_front.h"
+#include "absl/strings/str_cat.h"
+#include "absl/time/time.h"
+#include "connections/implementation/mediums/webrtc/session_description_wrapper.h"
+#include "connections/implementation/mediums/webrtc/signaling_frames.h"
+#include "connections/implementation/mediums/webrtc_socket.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/listeners.h"
+#include "internal/platform/cancelable_alarm.h"
+#include "internal/platform/future.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/mutex_lock.h"
+#include "proto/mediums/web_rtc_signaling_frames.pb.h"
+#include "webrtc/api/jsep.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+namespace {
+
+// The maximum amount of time to wait to connect to a data channel via WebRTC.
+constexpr absl::Duration kDataChannelTimeout = absl::Seconds(10);
+
+// Delay between restarting signaling messenger to receive messages.
+constexpr absl::Duration kRestartReceiveMessagesDuration = absl::Seconds(60);
+
+} // namespace
+
+WebRtc::WebRtc() = default;
+
+WebRtc::~WebRtc() {
+ // This ensures that all pending callbacks are run before we reset the medium
+ // and we are not accepting new runnables.
+ single_thread_executor_.Shutdown();
+
+ // Stop accepting all connections
+ absl::flat_hash_set<std::string> service_ids;
+ for (auto& item : accepting_connections_info_) {
+ service_ids.emplace(item.first);
+ }
+ for (const auto& service_id : service_ids) {
+ StopAcceptingConnections(service_id);
+ }
+}
+
+const std::string WebRtc::GetDefaultCountryCode() {
+ return medium_.GetDefaultCountryCode();
+}
+
+bool WebRtc::IsAvailable() { return medium_.IsValid(); }
+
+bool WebRtc::IsAcceptingConnections(const std::string& service_id) {
+ MutexLock lock(&mutex_);
+ return IsAcceptingConnectionsLocked(service_id);
+}
+
+bool WebRtc::IsAcceptingConnectionsLocked(const std::string& service_id) {
+ return accepting_connections_info_.contains(service_id);
+}
+
+bool WebRtc::StartAcceptingConnections(const std::string& service_id,
+ const WebrtcPeerId& self_peer_id,
+ const LocationHint& location_hint,
+ AcceptedConnectionCallback callback) {
+ MutexLock lock(&mutex_);
+ if (!IsAvailable()) {
+ NEARBY_LOG(WARNING,
+ "Cannot start accepting WebRTC connections because WebRTC is "
+ "not available.");
+ return false;
+ }
+
+ if (IsAcceptingConnectionsLocked(service_id)) {
+ NEARBY_LOG(WARNING,
+ "Cannot start accepting WebRTC connections because service %s "
+ "is already accepting WebRTC connections.",
+ service_id.c_str());
+ return false;
+ }
+
+ // We'll track our state here, so that we're separated from the other services
+ // who may be also using WebRTC.
+ AcceptingConnectionsInfo info = AcceptingConnectionsInfo();
+ info.self_peer_id = self_peer_id;
+ info.accepted_connection_callback = callback;
+
+ // Create a new SignalingMessenger so that we can communicate w/ Tachyon.
+ info.signaling_messenger =
+ medium_.GetSignalingMessenger(self_peer_id.GetId(), location_hint);
+ if (!info.signaling_messenger->IsValid()) {
+ return false;
+ }
+
+ // This registers ourselves w/ Tachyon, creating a room from the PeerId.
+ // This allows a remote device to message us over Tachyon.
+ if (!info.signaling_messenger->StartReceivingMessages(
+ absl::bind_front(&WebRtc::OnSignalingMessage, this, service_id),
+ absl::bind_front(&WebRtc::OnSignalingComplete, this, service_id))) {
+ info.signaling_messenger.reset();
+ return false;
+ }
+
+ // We'll automatically disconnect from Tachyon after 60sec. When this alarm
+ // fires, we'll recreate our room so we continue to receive messages.
+ info.restart_tachyon_receive_messages_alarm = CancelableAlarm(
+ "restart_receiving_messages_webrtc",
+ std::bind(&WebRtc::ProcessRestartTachyonReceiveMessages, this,
+ service_id),
+ kRestartReceiveMessagesDuration, &single_thread_executor_);
+
+ // Now that we're set up to receive messages, we'll save our state and return
+ // a successful result.
+ accepting_connections_info_.emplace(service_id, std::move(info));
+ NEARBY_LOG(INFO,
+ "Started listening for WebRTC connections as %s on service %s",
+ self_peer_id.GetId().c_str(), service_id.c_str());
+ return true;
+}
+
+void WebRtc::StopAcceptingConnections(const std::string& service_id) {
+ MutexLock lock(&mutex_);
+ if (!IsAcceptingConnectionsLocked(service_id)) {
+ NEARBY_LOG(WARNING,
+ "Cannot stop accepting WebRTC connections because service %s "
+ "is not accepting WebRTC connections.",
+ service_id.c_str());
+ return;
+ }
+
+ // Grab our info from the map.
+ auto& info = accepting_connections_info_.find(service_id)->second;
+
+ // Stop receiving messages from Tachyon.
+ info.signaling_messenger->StopReceivingMessages();
+ info.signaling_messenger.reset();
+
+ // Cancel the scheduled alarm.
+ if (info.restart_tachyon_receive_messages_alarm.IsValid()) {
+ info.restart_tachyon_receive_messages_alarm.Cancel();
+ info.restart_tachyon_receive_messages_alarm = CancelableAlarm();
+ }
+
+ // If we had any in-progress connections that haven't materialized into full
+ // DataChannels yet, it's time to shut them down since they can't reach us
+ // anymore.
+ absl::flat_hash_set<std::string> peer_ids;
+ for (auto& item : connection_flows_) {
+ peer_ids.emplace(item.first);
+ }
+ for (const auto& peer_id : peer_ids) {
+ const auto& entry = connection_flows_.find(peer_id);
+ // Skip outgoing connections in this step. Start/StopAcceptingConnections
+ // only deals with incoming connections.
+ if (requesting_connections_info_.contains(peer_id)) {
+ continue;
+ }
+
+ // Skip fully connected connections in this step. If the connection was
+ // formed while we were accepting connections, then it will stay alive until
+ // it's explicitly closed.
+ if (!entry->second->CloseIfNotConnected()) {
+ continue;
+ }
+
+ connection_flows_.erase(peer_id);
+ }
+
+ // Clean up our state. We're now no longer listening for connections.
+ accepting_connections_info_.erase(service_id);
+ NEARBY_LOG(INFO, "Stopped listening for WebRTC connections for service %s",
+ service_id.c_str());
+}
+
+WebRtcSocketWrapper WebRtc::Connect(const std::string& service_id,
+ const WebrtcPeerId& remote_peer_id,
+ const LocationHint& location_hint,
+ CancellationFlag* cancellation_flag) {
+ for (int attempts_count = 0; attempts_count < kConnectAttemptsLimit;
+ attempts_count++) {
+ auto wrapper_result = AttemptToConnect(service_id, remote_peer_id,
+ location_hint, cancellation_flag);
+ if (wrapper_result.IsValid()) {
+ return wrapper_result;
+ }
+ }
+ return WebRtcSocketWrapper();
+}
+
+WebRtcSocketWrapper WebRtc::AttemptToConnect(
+ const std::string& service_id, const WebrtcPeerId& remote_peer_id,
+ const LocationHint& location_hint, CancellationFlag* cancellation_flag) {
+ ConnectionRequestInfo info = ConnectionRequestInfo();
+ info.self_peer_id = WebrtcPeerId::FromRandom();
+ Future<WebRtcSocketWrapper> socket_future = info.socket_future;
+
+ {
+ MutexLock lock(&mutex_);
+ if (!IsAvailable()) {
+ NEARBY_LOG(
+ WARNING,
+ "Cannot connect to WebRTC peer %s because WebRTC is not available.",
+ remote_peer_id.GetId().c_str());
+ return WebRtcSocketWrapper();
+ }
+
+ if (cancellation_flag->Cancelled()) {
+ NEARBY_LOGS(INFO) << "Cannot connect with WebRtc due to cancel.";
+ return WebRtcSocketWrapper();
+ }
+
+ // Create a new ConnectionFlow for this connection attempt.
+ std::unique_ptr<ConnectionFlow> connection_flow =
+ CreateConnectionFlow(service_id, remote_peer_id);
+ if (!connection_flow) {
+ NEARBY_LOG(
+ INFO,
+ "Cannot connect to WebRTC peer %s because we failed to create a "
+ "ConnectionFlow.",
+ remote_peer_id.GetId().c_str());
+ return WebRtcSocketWrapper();
+ }
+
+ // Create a new SignalingMessenger so that we can communicate over Tachyon.
+ info.signaling_messenger =
+ medium_.GetSignalingMessenger(info.self_peer_id.GetId(), location_hint);
+ if (!info.signaling_messenger->IsValid()) {
+ NEARBY_LOG(
+ INFO,
+ "Cannot connect to WebRTC peer %s because we failed to create a "
+ "SignalingMessenger.",
+ remote_peer_id.GetId().c_str());
+ return WebRtcSocketWrapper();
+ }
+
+ // This registers ourselves w/ Tachyon, creating a room from the PeerId.
+ // This allows a remote device to message us over Tachyon.
+ auto signaling_complete_callback = [socket_future](bool success) mutable {
+ if (!success) {
+ socket_future.SetException({Exception::kFailed});
+ }
+ };
+ if (!info.signaling_messenger->StartReceivingMessages(
+ absl::bind_front(&WebRtc::OnSignalingMessage, this, service_id),
+ signaling_complete_callback)) {
+ NEARBY_LOG(INFO,
+ "Cannot connect to WebRTC peer %s because we failed to start "
+ "receiving messages over Tachyon.",
+ remote_peer_id.GetId().c_str());
+ info.signaling_messenger.reset();
+ return WebRtcSocketWrapper();
+ }
+
+ // Poke the remote device. This will cause them to send us an Offer.
+ if (!info.signaling_messenger->SendMessage(
+ remote_peer_id.GetId(),
+ webrtc_frames::EncodeReadyForSignalingPoke(info.self_peer_id))) {
+ NEARBY_LOG(INFO,
+ "Cannot connect to WebRTC peer %s because we failed to poke "
+ "the peer over Tachyon.",
+ remote_peer_id.GetId().c_str());
+ info.signaling_messenger.reset();
+ return WebRtcSocketWrapper();
+ }
+
+ // Create a new ConnectionRequest entry. This map will be used later to look
+ // up state as we negotiate the connection over Tachyon.
+ requesting_connections_info_.emplace(remote_peer_id.GetId(),
+ std::move(info));
+ connection_flows_.emplace(remote_peer_id.GetId(),
+ std::move(connection_flow));
+ }
+
+ // Wait for the connection to go through. Don't hold the mutex here so that
+ // we're not blocking necessary operations.
+ ExceptionOr<WebRtcSocketWrapper> socket_result =
+ socket_future.Get(kDataChannelTimeout);
+
+ {
+ MutexLock lock(&mutex_);
+
+ // Reclaim our info, since we had released ownership while talking to
+ // Tachyon.
+ auto& info =
+ requesting_connections_info_.find(remote_peer_id.GetId())->second;
+
+ // Verify that the connection went through.
+ if (!socket_result.ok()) {
+ NEARBY_LOG(INFO, "Failed to connect to WebRTC peer %s.",
+ remote_peer_id.GetId().c_str());
+ RemoveConnectionFlow(remote_peer_id);
+ info.signaling_messenger.reset();
+ requesting_connections_info_.erase(remote_peer_id.GetId());
+ return WebRtcSocketWrapper();
+ }
+
+ // Clean up our ConnectionRequest.
+ info.signaling_messenger.reset();
+ requesting_connections_info_.erase(remote_peer_id.GetId());
+
+ // Return the result.
+ return socket_result.GetResult();
+ }
+}
+
+void WebRtc::ProcessLocalIceCandidate(
+ const std::string& service_id, const WebrtcPeerId& remote_peer_id,
+ const ::location::nearby::mediums::IceCandidate ice_candidate) {
+ MutexLock lock(&mutex_);
+
+ // Check first if we have an outgoing request w/ this peer. As this request is
+ // tied to a specific peer, it takes precedence.
+ const auto& connection_request_entry =
+ requesting_connections_info_.find(remote_peer_id.GetId());
+ if (connection_request_entry != requesting_connections_info_.end()) {
+ // Pass the ice candidate to the remote side.
+ if (!connection_request_entry->second.signaling_messenger->SendMessage(
+ remote_peer_id.GetId(),
+ webrtc_frames::EncodeIceCandidates(
+ connection_request_entry->second.self_peer_id,
+ {ice_candidate}))) {
+ NEARBY_LOG(INFO, "Failed to send ice candidate to %s.",
+ remote_peer_id.GetId().c_str());
+ }
+
+ NEARBY_LOG(INFO, "Sent ice candidate to %s.",
+ remote_peer_id.GetId().c_str());
+ return;
+ }
+
+ // Check next if we're expecting incoming connection requests.
+ const auto& accepting_connection_entry =
+ accepting_connections_info_.find(service_id);
+ if (accepting_connection_entry != accepting_connections_info_.end()) {
+ // Pass the ice candidate to the remote side.
+ // TODO(xlythe) Consider not blocking here, since this can eat into the
+ // connection time
+ if (!accepting_connection_entry->second.signaling_messenger->SendMessage(
+ remote_peer_id.GetId(),
+ webrtc_frames::EncodeIceCandidates(
+ accepting_connection_entry->second.self_peer_id,
+ {ice_candidate}))) {
+ NEARBY_LOG(INFO, "Failed to send ice candidate to %s.",
+ remote_peer_id.GetId().c_str());
+ }
+
+ NEARBY_LOG(INFO, "Sent ice candidate to %s.",
+ remote_peer_id.GetId().c_str());
+ return;
+ }
+
+ NEARBY_LOG(INFO,
+ "Skipping restart listening for tachyon inbox messages since we "
+ "are not accepting connections for service %s.",
+ service_id.c_str());
+}
+
+void WebRtc::OnSignalingMessage(const std::string& service_id,
+ const ByteArray& message) {
+ OffloadFromThread("rtc-on-signaling-message", [this, service_id, message]() {
+ ProcessTachyonInboxMessage(service_id, message);
+ });
+}
+
+void WebRtc::OnSignalingComplete(const std::string& service_id, bool success) {
+ NEARBY_LOG(INFO, "Signaling completed with status: %d.", success);
+ if (success) {
+ return;
+ }
+
+ OffloadFromThread("rtc-on-signaling-complete", [this, service_id]() {
+ MutexLock lock(&mutex_);
+ const auto& info_entry = accepting_connections_info_.find(service_id);
+ if (info_entry == accepting_connections_info_.end()) {
+ return;
+ }
+
+ if (info_entry->second.restart_accept_connections_count <
+ kRestartAcceptConnectionsLimit) {
+ ++info_entry->second.restart_accept_connections_count;
+ } else {
+ return;
+ }
+
+ RestartTachyonReceiveMessages(service_id);
+ });
+}
+
+void WebRtc::ProcessTachyonInboxMessage(const std::string& service_id,
+ const ByteArray& message) {
+ MutexLock lock(&mutex_);
+
+ // Attempt to parse the incoming message as a WebRtcSignalingFrame.
+ location::nearby::mediums::WebRtcSignalingFrame frame;
+ if (!frame.ParseFromString(std::string(message))) {
+ NEARBY_LOG(WARNING, "Failed to parse signaling message.");
+ return;
+ }
+
+ // Ensure that the frame is valid (no missing fields).
+ if (!frame.has_sender_id()) {
+ NEARBY_LOG(WARNING, "Invalid WebRTC frame: Sender ID is missing.");
+ return;
+ }
+ WebrtcPeerId remote_peer_id = WebrtcPeerId(frame.sender_id().id());
+
+ // Depending on the message type, we'll respond as appropriate.
+ if (requesting_connections_info_.contains(remote_peer_id.GetId())) {
+ // This is from a peer we have an outgoing connection request with, so we'll
+ // only process the Answer path.
+ if (frame.has_offer()) {
+ ReceiveOffer(remote_peer_id,
+ SessionDescriptionWrapper(
+ webrtc_frames::DecodeOffer(frame).release()));
+ SendAnswer(remote_peer_id);
+ } else if (frame.has_ice_candidates()) {
+ ReceiveIceCandidates(remote_peer_id,
+ webrtc_frames::DecodeIceCandidates(frame));
+ } else {
+ NEARBY_LOG(INFO, "Received unknown WebRTC frame: ignoring.");
+ }
+ } else if (IsAcceptingConnectionsLocked(service_id)) {
+ // We don't have an outgoing connection request with this peer, but we are
+ // accepting incoming requests so we'll only process the Offer path.
+ if (frame.has_ready_for_signaling_poke()) {
+ SendOffer(service_id, remote_peer_id);
+ } else if (frame.has_answer()) {
+ ReceiveAnswer(remote_peer_id,
+ SessionDescriptionWrapper(
+ webrtc_frames::DecodeAnswer(frame).release()));
+ } else if (frame.has_ice_candidates()) {
+ ReceiveIceCandidates(remote_peer_id,
+ webrtc_frames::DecodeIceCandidates(frame));
+ } else {
+ NEARBY_LOG(INFO, "Received unknown WebRTC frame: ignoring.");
+ }
+ } else {
+ NEARBY_LOG(
+ INFO,
+ "Ignoring Tachyon message since we are not accepting connections.");
+ }
+}
+
+void WebRtc::SendOffer(const std::string& service_id,
+ const WebrtcPeerId& remote_peer_id) {
+ std::unique_ptr<ConnectionFlow> connection_flow =
+ CreateConnectionFlow(service_id, remote_peer_id);
+ if (!connection_flow) {
+ NEARBY_LOG(INFO,
+ "Unable to send offer. Failed to create a ConnectionFlow.");
+ return;
+ }
+
+ SessionDescriptionWrapper offer = connection_flow->CreateOffer();
+ if (!offer.IsValid()) {
+ NEARBY_LOG(INFO,
+ "Unable to send offer. Failed to create our offer locally.");
+ RemoveConnectionFlow(remote_peer_id);
+ return;
+ }
+
+ const webrtc::SessionDescriptionInterface& sdp = offer.GetSdp();
+ if (!connection_flow->SetLocalSessionDescription(offer)) {
+ NEARBY_LOG(INFO,
+ "Unable to send offer. Failed to register our offer locally.");
+ RemoveConnectionFlow(remote_peer_id);
+ return;
+ }
+
+ // Grab our info from the map.
+ auto& info = accepting_connections_info_.find(service_id)->second;
+
+ // Pass the offer to the remote side.
+ if (!info.signaling_messenger->SendMessage(
+ remote_peer_id.GetId(),
+ webrtc_frames::EncodeOffer(info.self_peer_id, sdp))) {
+ NEARBY_LOG(INFO,
+ "Unable to send offer. Failed to write the offer to the remote "
+ "peer %s.",
+ remote_peer_id.GetId().c_str());
+ RemoveConnectionFlow(remote_peer_id);
+ return;
+ }
+
+ // Store the ConnectionFlow so that other methods can use it later.
+ connection_flows_.emplace(remote_peer_id.GetId(), std::move(connection_flow));
+ NEARBY_LOG(INFO, "Sent offer to %s.", remote_peer_id.GetId().c_str());
+}
+
+void WebRtc::ReceiveOffer(const WebrtcPeerId& remote_peer_id,
+ SessionDescriptionWrapper offer) {
+ const auto& entry = connection_flows_.find(remote_peer_id.GetId());
+ if (entry == connection_flows_.end()) {
+ NEARBY_LOG(INFO,
+ "Unable to receive offer. Failed to create a ConnectionFlow.");
+ return;
+ }
+
+ if (!entry->second->OnOfferReceived(offer)) {
+ NEARBY_LOG(INFO, "Unable to receive offer. Failed to process the offer.");
+ RemoveConnectionFlow(remote_peer_id);
+ }
+}
+
+void WebRtc::SendAnswer(const WebrtcPeerId& remote_peer_id) {
+ const auto& entry = connection_flows_.find(remote_peer_id.GetId());
+ if (entry == connection_flows_.end()) {
+ NEARBY_LOG(INFO,
+ "Unable to send answer. Failed to create a ConnectionFlow.");
+ return;
+ }
+
+ SessionDescriptionWrapper answer = entry->second->CreateAnswer();
+ if (!answer.IsValid()) {
+ NEARBY_LOG(INFO,
+ "Unable to send answer. Failed to create our answer locally.");
+ RemoveConnectionFlow(remote_peer_id);
+ return;
+ }
+
+ const webrtc::SessionDescriptionInterface& sdp = answer.GetSdp();
+ if (!entry->second->SetLocalSessionDescription(answer)) {
+ NEARBY_LOG(INFO,
+ "Unable to send answer. Failed to register our answer locally.");
+ RemoveConnectionFlow(remote_peer_id);
+ return;
+ }
+
+ // Grab our info from the map.
+ const auto& connection_request_entry =
+ requesting_connections_info_.find(remote_peer_id.GetId());
+ if (connection_request_entry == requesting_connections_info_.end()) {
+ NEARBY_LOG(INFO,
+ "Unable to send answer. Failed to find an outgoing connection "
+ "request.");
+ RemoveConnectionFlow(remote_peer_id);
+ return;
+ }
+
+ // Pass the answer to the remote side.
+ if (!connection_request_entry->second.signaling_messenger->SendMessage(
+ remote_peer_id.GetId(),
+ webrtc_frames::EncodeAnswer(
+ connection_request_entry->second.self_peer_id, sdp))) {
+ NEARBY_LOG(
+ INFO,
+ "Unable to send answer. Failed to write the answer to the remote "
+ "peer %s.",
+ remote_peer_id.GetId().c_str());
+ RemoveConnectionFlow(remote_peer_id);
+ return;
+ }
+
+ NEARBY_LOG(INFO, "Sent answer to %s.", remote_peer_id.GetId().c_str());
+}
+
+void WebRtc::ReceiveAnswer(const WebrtcPeerId& remote_peer_id,
+ SessionDescriptionWrapper answer) {
+ const auto& entry = connection_flows_.find(remote_peer_id.GetId());
+ if (entry == connection_flows_.end()) {
+ NEARBY_LOG(INFO,
+ "Unable to receive answer. Failed to create a ConnectionFlow.");
+ return;
+ }
+
+ if (!entry->second->OnAnswerReceived(answer)) {
+ NEARBY_LOG(INFO, "Unable to receive answer. Failed to process the answer.");
+ RemoveConnectionFlow(remote_peer_id);
+ }
+}
+
+void WebRtc::ReceiveIceCandidates(
+ const WebrtcPeerId& remote_peer_id,
+ std::vector<std::unique_ptr<webrtc::IceCandidateInterface>>
+ ice_candidates) {
+ const auto& entry = connection_flows_.find(remote_peer_id.GetId());
+ if (entry == connection_flows_.end()) {
+ NEARBY_LOG(
+ INFO,
+ "Unable to receive ice candidates. Failed to create a ConnectionFlow.");
+ return;
+ }
+
+ entry->second->OnRemoteIceCandidatesReceived(std::move(ice_candidates));
+}
+
+void WebRtc::ProcessRestartTachyonReceiveMessages(
+ const std::string& service_id) {
+ MutexLock lock(&mutex_);
+ RestartTachyonReceiveMessages(service_id);
+}
+
+void WebRtc::RestartTachyonReceiveMessages(const std::string& service_id) {
+ if (!IsAcceptingConnectionsLocked(service_id)) {
+ NEARBY_LOG(INFO,
+ "Skipping restart listening for tachyon inbox messages since we "
+ "are not accepting connections for service %s.",
+ service_id.c_str());
+ return;
+ }
+
+ // Grab our info from the map.
+ auto& info = accepting_connections_info_.find(service_id)->second;
+
+ // Ensure we've disconnected from Tachyon.
+ info.signaling_messenger->StopReceivingMessages();
+
+ // Attempt to re-register.
+ if (!info.signaling_messenger->StartReceivingMessages(
+ absl::bind_front(&WebRtc::OnSignalingMessage, this, service_id),
+ absl::bind_front(&WebRtc::OnSignalingComplete, this, service_id))) {
+ NEARBY_LOG(WARNING,
+ "Failed to restart listening for tachyon inbox messages for "
+ "service %s since we failed to reach Tachyon.",
+ service_id.c_str());
+ return;
+ }
+
+ NEARBY_LOG(INFO,
+ "Successfully restarted listening for tachyon inbox messages on "
+ "service %s.",
+ service_id.c_str());
+}
+
+void WebRtc::ProcessDataChannelOpen(const std::string& service_id,
+ const WebrtcPeerId& remote_peer_id,
+ WebRtcSocketWrapper socket_wrapper) {
+ MutexLock lock(&mutex_);
+
+ // Notify the client of the newly formed socket.
+ const auto& connection_request_entry =
+ requesting_connections_info_.find(remote_peer_id.GetId());
+ if (connection_request_entry != requesting_connections_info_.end()) {
+ connection_request_entry->second.socket_future.Set(socket_wrapper);
+ return;
+ }
+
+ const auto& accepting_connection_entry =
+ accepting_connections_info_.find(service_id);
+ if (accepting_connection_entry != accepting_connections_info_.end()) {
+ accepting_connection_entry->second.accepted_connection_callback.accepted_cb(
+ socket_wrapper);
+ return;
+ }
+
+ // No one to handle the newly created DataChannel, so we'll just close it.
+ socket_wrapper.Close();
+ NEARBY_LOG(INFO,
+ "Ignoring new DataChannel because we "
+ "are not accepting connections for service %s.",
+ service_id.c_str());
+}
+
+void WebRtc::ProcessDataChannelClosed(const WebrtcPeerId& remote_peer_id) {
+ MutexLock lock(&mutex_);
+ NEARBY_LOG(INFO,
+ "Data channel has closed, removing connection flow for peer %s.",
+ remote_peer_id.GetId().c_str());
+
+ RemoveConnectionFlow(remote_peer_id);
+}
+
+std::unique_ptr<ConnectionFlow> WebRtc::CreateConnectionFlow(
+ const std::string& service_id, const WebrtcPeerId& remote_peer_id) {
+ RemoveConnectionFlow(remote_peer_id);
+
+ return ConnectionFlow::Create(
+ {.local_ice_candidate_found_cb =
+ {[this, service_id, remote_peer_id](
+ const webrtc::IceCandidateInterface* ice_candidate) {
+ // Note: We need to encode the ice candidate here, before we jump
+ // off the thread. Otherwise, it gets destroyed and we can't read
+ // it later.
+ ::location::nearby::mediums::IceCandidate encoded_ice_candidate =
+ webrtc_frames::EncodeIceCandidate(*ice_candidate);
+ OffloadFromThread(
+ "rtc-ice-candidates",
+ [this, service_id, remote_peer_id, encoded_ice_candidate]() {
+ ProcessLocalIceCandidate(service_id, remote_peer_id,
+ encoded_ice_candidate);
+ });
+ }}},
+ {
+ .data_channel_open_cb = {[this, service_id, remote_peer_id](
+ WebRtcSocketWrapper socket_wrapper) {
+ OffloadFromThread(
+ "rtc-channel-created",
+ [this, service_id, remote_peer_id, socket_wrapper]() {
+ ProcessDataChannelOpen(service_id, remote_peer_id,
+ socket_wrapper);
+ });
+ }},
+ .data_channel_closed_cb = {[this, remote_peer_id]() {
+ OffloadFromThread("rtc-channel-closed", [this, remote_peer_id]() {
+ ProcessDataChannelClosed(remote_peer_id);
+ });
+ }},
+ },
+ medium_);
+}
+
+void WebRtc::RemoveConnectionFlow(const WebrtcPeerId& remote_peer_id) {
+ if (!connection_flows_.erase(remote_peer_id.GetId())) {
+ return;
+ }
+
+ // If we had an outgoing connection request w/ this peer, report the failure
+ // to the future that's being waited on.
+ const auto& connection_request_entry =
+ requesting_connections_info_.find(remote_peer_id.GetId());
+ if (connection_request_entry != requesting_connections_info_.end()) {
+ connection_request_entry->second.socket_future.SetException(
+ {Exception::kFailed});
+ }
+}
+
+void WebRtc::OffloadFromThread(const std::string& name, Runnable runnable) {
+ single_thread_executor_.Execute(name, std::move(runnable));
+}
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc.h b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc.h
new file mode 100644
index 00000000000..7369128af2e
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc.h
@@ -0,0 +1,265 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MEDIUMS_WEBRTC_H_
+#define CORE_INTERNAL_MEDIUMS_WEBRTC_H_
+
+#include <cstddef>
+#include <functional>
+#include <memory>
+#include <string>
+
+#include "absl/container/flat_hash_map.h"
+#include "absl/container/flat_hash_set.h"
+#include "connections/implementation/proto/offline_wire_formats.pb.h"
+#include "connections/implementation/mediums/webrtc/connection_flow.h"
+#include "connections/implementation/mediums/webrtc/data_channel_listener.h"
+#include "connections/implementation/mediums/webrtc/local_ice_candidate_listener.h"
+#include "connections/implementation/mediums/webrtc/webrtc_socket_impl.h"
+#include "connections/implementation/mediums/webrtc_peer_id.h"
+#include "connections/implementation/mediums/webrtc_socket.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/cancellation_flag.h"
+#include "internal/platform/listeners.h"
+#include "internal/platform/runnable.h"
+#include "internal/platform/atomic_boolean.h"
+#include "internal/platform/cancelable_alarm.h"
+#include "internal/platform/future.h"
+#include "internal/platform/mutex.h"
+#include "internal/platform/scheduled_executor.h"
+#include "internal/platform/single_thread_executor.h"
+#include "internal/platform/webrtc.h"
+#include "proto/mediums/web_rtc_signaling_frames.pb.h"
+#include "webrtc/api/jsep.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+// Callback that is invoked when a new connection is accepted.
+struct AcceptedConnectionCallback {
+ std::function<void(WebRtcSocketWrapper socket)> accepted_cb =
+ DefaultCallback<WebRtcSocketWrapper>();
+};
+
+// Entry point for connecting a data channel between two devices via WebRtc.
+class WebRtc {
+ public:
+ WebRtc();
+ ~WebRtc();
+
+ // Gets the default two-letter country code associated with current locale.
+ // For example, en_US locale resolves to "US".
+ const std::string GetDefaultCountryCode();
+
+ // Returns if WebRtc is available as a medium for nearby to transport data.
+ // Runs on @MainThread.
+ bool IsAvailable();
+
+ // Returns if the device is accepting connection with specific service id.
+ // Runs on @MainThread.
+ bool IsAcceptingConnections(const std::string& service_id)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Prepares the device to accept incoming WebRtc connections. Returns a
+ // boolean value indicating if the device has started accepting connections.
+ // Runs on @MainThread.
+ bool StartAcceptingConnections(const std::string& service_id,
+ const WebrtcPeerId& self_peer_id,
+ const LocationHint& location_hint,
+ AcceptedConnectionCallback callback)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Try to stop (accepting) the specific connection with provided service id.
+ // Runs on @MainThread
+ void StopAcceptingConnections(const std::string& service_id)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Initiates a WebRtc connection with peer device identified by |peer_id|
+ // with internal retry for maximum attempts of kConnectAttemptsLimit.
+ // Runs on @MainThread.
+ WebRtcSocketWrapper Connect(const std::string& service_id,
+ const WebrtcPeerId& peer_id,
+ const LocationHint& location_hint,
+ CancellationFlag* cancellation_flag)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ private:
+ static constexpr int kConnectAttemptsLimit = 3;
+ static constexpr int kRestartAcceptConnectionsLimit = 3;
+
+ enum class Role {
+ kNone = 0,
+ kOfferer = 1,
+ kAnswerer = 2,
+ };
+
+ struct AcceptingConnectionsInfo {
+ // The self_peer_id is generated from the BT/WiFi advertisements and allows
+ // the scanner to message us over Tachyon.
+ WebrtcPeerId self_peer_id;
+
+ // The registered callback. When there's an incoming connection, this
+ // callback is notified.
+ AcceptedConnectionCallback accepted_connection_callback;
+
+ // Allows us to communicate with the Tachyon web server.
+ std::unique_ptr<WebRtcSignalingMessenger> signaling_messenger;
+
+ // Restarts the tachyon inbox receives messages streaming rpc if the
+ // streaming rpc times out. The streaming rpc times out after 60s while
+ // advertising. Non-null when listening for WebRTC connections as an
+ // offerer.
+ CancelableAlarm restart_tachyon_receive_messages_alarm;
+
+ // Tracks the number of times we've restarted receiving messages after a
+ // failure. We limit the number to prevent endless restarts if we are
+ // repeatedly unable to communicate with Tachyon.
+ int restart_accept_connections_count = 0;
+ };
+
+ struct ConnectionRequestInfo {
+ // The self_peer_id is randomly generated and allows the advertiser to
+ // message us over Tachyon.
+ WebrtcPeerId self_peer_id;
+
+ // Allows us to communicate with the Tachyon web server.
+ std::unique_ptr<WebRtcSignalingMessenger> signaling_messenger;
+
+ // The pending DataChannel future. Our client will be blocked on this while
+ // they wait for us to set up the channel over Tachyon.
+ Future<WebRtcSocketWrapper> socket_future;
+ };
+
+ // Attempt to initiates a WebRtc connection with peer device identified by
+ // |peer_id|.
+ // Runs on @MainThread.
+ WebRtcSocketWrapper AttemptToConnect(const std::string& service_id,
+ const WebrtcPeerId& peer_id,
+ const LocationHint& location_hint,
+ CancellationFlag* cancellation_flag)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns if the device is accepting connection with specific service id.
+ // Runs on @MainThread.
+ bool IsAcceptingConnectionsLocked(const std::string& service_id)
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Receives a message from the signaling messenger.
+ void OnSignalingMessage(const std::string& service_id,
+ const ByteArray& message);
+
+ // Decides whether to restart receiving messages.
+ void OnSignalingComplete(const std::string& service_id, bool success);
+
+ // Runs on |single_thread_executor_|.
+ void ProcessTachyonInboxMessage(const std::string& service_id,
+ const ByteArray& message)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Runs on |single_thread_executor_|.
+ void SendOffer(const std::string& service_id,
+ const WebrtcPeerId& remote_peer_id)
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Runs on |single_thread_executor_|.
+ void ReceiveOffer(const WebrtcPeerId& remote_peer_id,
+ SessionDescriptionWrapper offer)
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Runs on |single_thread_executor_|.
+ void SendAnswer(const WebrtcPeerId& remote_peer_id)
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Runs on |single_thread_executor_|.
+ void ReceiveAnswer(const WebrtcPeerId& remote_peer_id,
+ SessionDescriptionWrapper answer)
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Runs on |single_thread_executor_|.
+ void ReceiveIceCandidates(
+ const WebrtcPeerId& remote_peer_id,
+ std::vector<std::unique_ptr<webrtc::IceCandidateInterface>>
+ ice_candidates) ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Runs on |single_thread_executor_|.
+ std::unique_ptr<ConnectionFlow> CreateConnectionFlow(
+ const std::string& service_id, const WebrtcPeerId& remote_peer_id)
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Runs on |single_thread_executor_|.
+ std::unique_ptr<ConnectionFlow> GetConnectionFlow(
+ const WebrtcPeerId& remote_peer_id) ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Runs on |single_thread_executor_|.
+ void RemoveConnectionFlow(const WebrtcPeerId& remote_peer_id)
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Runs on |single_thread_executor_|.
+ void ProcessDataChannelOpen(const std::string& service_id,
+ const WebrtcPeerId& remote_peer_id,
+ WebRtcSocketWrapper socket_wrapper)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Runs on |single_thread_executor_|.
+ void ProcessDataChannelClosed(const WebrtcPeerId& remote_peer_id)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Runs on |single_thread_executor_|.
+ void ProcessLocalIceCandidate(
+ const std::string& service_id, const WebrtcPeerId& remote_peer_id,
+ const ::location::nearby::mediums::IceCandidate ice_candidate)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Runs on |single_thread_executor_|.
+ void ProcessRestartTachyonReceiveMessages(const std::string& service_id)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Runs on |single_thread_executor_|.
+ void RestartTachyonReceiveMessages(const std::string& service_id)
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ void OffloadFromThread(const std::string& name, Runnable runnable);
+
+ Mutex mutex_;
+
+ WebRtcMedium medium_;
+
+ // The single thread we throw the potentially blocking work on to.
+ ScheduledExecutor single_thread_executor_;
+
+ // A map of ServiceID -> State for all services that are listening for
+ // incoming connections.
+ absl::flat_hash_map<std::string, AcceptingConnectionsInfo>
+ accepting_connections_info_ ABSL_GUARDED_BY(mutex_);
+
+ // A map of a remote PeerId -> State for pending connection requests. As
+ // messages from Tachyon come in, this lets us look up the connection request
+ // info to handle the interaction.
+ absl::flat_hash_map<std::string, ConnectionRequestInfo>
+ requesting_connections_info_ ABSL_GUARDED_BY(mutex_);
+
+ // A map of a remote PeerId -> ConnectionFlow. For each connection, we create
+ // a unique ConnectionFlow.
+ absl::flat_hash_map<std::string, std::unique_ptr<ConnectionFlow>>
+ connection_flows_ ABSL_GUARDED_BY(mutex_);
+};
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MEDIUMS_WEBRTC_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/BUILD b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/BUILD
new file mode 100644
index 00000000000..1090a391ba0
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/BUILD
@@ -0,0 +1,98 @@
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+licenses(["notice"])
+
+cc_library(
+ name = "webrtc",
+ srcs = [
+ "connection_flow.cc",
+ "signaling_frames.cc",
+ ],
+ hdrs = [
+ "connection_flow.h",
+ "data_channel_listener.h",
+ "local_ice_candidate_listener.h",
+ "session_description_wrapper.h",
+ "signaling_frames.h",
+ ],
+ copts = ["-DCORE_ADAPTER_DLL"],
+ visibility = [
+ "//connections/implementation:__subpackages__",
+ ],
+ deps = [
+ ":data_types",
+ "//connections:core_types",
+ "//connections/implementation/mediums:utils",
+ "//internal/platform:base",
+ "//internal/platform:comm",
+ "//internal/platform:logging",
+ "//internal/platform:types",
+ "//proto/mediums:web_rtc_signaling_frames_cc_proto",
+ "//third_party/webrtc/files/stable/webrtc/api:libjingle_peerconnection_api",
+ "//third_party/webrtc/files/stable/webrtc/pc:peerconnection",
+ "@com_google_absl//absl/memory",
+ "@com_google_absl//absl/time",
+ ],
+)
+
+cc_library(
+ name = "data_types",
+ srcs = [
+ "webrtc_socket_impl.cc",
+ ],
+ hdrs = [
+ "webrtc_socket_impl.h",
+ ],
+ copts = ["-DCORE_ADAPTER_DLL"],
+ visibility = [
+ "//connections/implementation:__subpackages__",
+ ],
+ deps = [
+ "//connections:core_types",
+ "//internal/platform:base",
+ "//internal/platform:types",
+ "//third_party/webrtc/files/stable/webrtc/api:libjingle_peerconnection_api",
+ ],
+)
+
+cc_test(
+ name = "webrtc_test",
+ timeout = "short",
+ srcs = [
+ "connection_flow_test.cc",
+ "signaling_frames_test.cc",
+ "webrtc_socket_impl_test.cc",
+ ],
+ tags = [
+ "notsan", # NOTE(b/139734036): known data race in usrsctplib.
+ "requires-net:external",
+ ],
+ deps = [
+ ":data_types",
+ ":webrtc",
+ "//connections/implementation/mediums:utils",
+ "//internal/platform:base",
+ "//internal/platform:comm",
+ "//internal/platform:test_util",
+ "//internal/platform:types",
+ "//internal/platform/implementation/g3", # buildcleaner: keep
+ "//third_party/webrtc/files/stable/webrtc/api:libjingle_peerconnection_api",
+ "//third_party/webrtc/files/stable/webrtc/api:rtc_error",
+ "//third_party/webrtc/files/stable/webrtc/api:scoped_refptr",
+ "@com_github_protobuf_matchers//protobuf-matchers",
+ "@com_google_absl//absl/time",
+ "@com_google_googletest//:gtest_main",
+ "@com_google_protobuf//:protobuf",
+ ],
+)
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/connection_flow.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/connection_flow.cc
new file mode 100644
index 00000000000..e012ab2a1f1
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/connection_flow.cc
@@ -0,0 +1,556 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/webrtc/connection_flow.h"
+
+#include <iterator>
+#include <memory>
+
+#include "absl/memory/memory.h"
+#include "absl/time/time.h"
+#include "connections/implementation/mediums/webrtc/session_description_wrapper.h"
+#include "connections/implementation/mediums/webrtc/webrtc_socket_impl.h"
+#include "connections/implementation/mediums/webrtc_socket.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/mutex_lock.h"
+#include "internal/platform/webrtc.h"
+#include "webrtc/api/data_channel_interface.h"
+#include "webrtc/api/jsep.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+constexpr absl::Duration ConnectionFlow::kTimeout;
+constexpr absl::Duration ConnectionFlow::kPeerConnectionTimeout;
+
+// This is the same as the nearby data channel name.
+constexpr char kDataChannelName[] = "dataChannel";
+
+class CreateSessionDescriptionObserverImpl
+ : public webrtc::CreateSessionDescriptionObserver {
+ public:
+ CreateSessionDescriptionObserverImpl(
+ ConnectionFlow* connection_flow,
+ Future<SessionDescriptionWrapper> settable_future,
+ ConnectionFlow::State expected_entry_state,
+ ConnectionFlow::State exit_state)
+ : connection_flow_{connection_flow},
+ settable_future_{settable_future},
+ expected_entry_state_{expected_entry_state},
+ exit_state_{exit_state} {}
+
+ // webrtc::CreateSessionDescriptionObserver
+ void OnSuccess(webrtc::SessionDescriptionInterface* desc) override {
+ if (connection_flow_->TransitionState(expected_entry_state_, exit_state_)) {
+ settable_future_.Set(SessionDescriptionWrapper{desc});
+ } else {
+ settable_future_.SetException({Exception::kFailed});
+ }
+ }
+
+ void OnFailure(webrtc::RTCError error) override {
+ NEARBY_LOG(ERROR, "Error when creating session description: %s",
+ error.message());
+ settable_future_.SetException({Exception::kFailed});
+ }
+
+ private:
+ ConnectionFlow* connection_flow_;
+ Future<SessionDescriptionWrapper> settable_future_;
+ ConnectionFlow::State expected_entry_state_;
+ ConnectionFlow::State exit_state_;
+};
+
+class SetDescriptionObserverBase {
+ public:
+ ExceptionOr<bool> GetResult(absl::Duration timeout) {
+ return settable_future_.Get(timeout);
+ }
+
+ protected:
+ void OnSetDescriptionComplete(webrtc::RTCError error) {
+ // On success, |error.ok()| is true.
+ if (error.ok()) {
+ settable_future_.Set(true);
+ return;
+ }
+ settable_future_.SetException({Exception::kFailed});
+ }
+
+ private:
+ Future<bool> settable_future_;
+};
+
+class SetLocalDescriptionObserver
+ : public webrtc::SetLocalDescriptionObserverInterface,
+ public SetDescriptionObserverBase {
+ public:
+ void OnSetLocalDescriptionComplete(webrtc::RTCError error) override {
+ OnSetDescriptionComplete(error);
+ }
+};
+
+class SetRemoteDescriptionObserver
+ : public webrtc::SetRemoteDescriptionObserverInterface,
+ public SetDescriptionObserverBase {
+ public:
+ void OnSetRemoteDescriptionComplete(webrtc::RTCError error) override {
+ OnSetDescriptionComplete(error);
+ }
+};
+
+using PeerConnectionState =
+ webrtc::PeerConnectionInterface::PeerConnectionState;
+
+std::unique_ptr<ConnectionFlow> ConnectionFlow::Create(
+ LocalIceCandidateListener local_ice_candidate_listener,
+ DataChannelListener data_channel_listener, WebRtcMedium& webrtc_medium) {
+ auto connection_flow = absl::WrapUnique(
+ new ConnectionFlow(std::move(local_ice_candidate_listener),
+ std::move(data_channel_listener)));
+ if (connection_flow->InitPeerConnection(webrtc_medium)) {
+ return connection_flow;
+ }
+
+ return nullptr;
+}
+
+ConnectionFlow::ConnectionFlow(
+ LocalIceCandidateListener local_ice_candidate_listener,
+ DataChannelListener data_channel_listener)
+ : data_channel_listener_(std::move(data_channel_listener)),
+ local_ice_candidate_listener_(std::move(local_ice_candidate_listener)) {}
+
+ConnectionFlow::~ConnectionFlow() {
+ NEARBY_LOG(INFO, "~ConnectionFlow");
+ RunOnSignalingThread([this] { CloseOnSignalingThread(); });
+ shutdown_latch_.Await();
+ NEARBY_LOG(INFO, "~ConnectionFlow done");
+}
+
+SessionDescriptionWrapper ConnectionFlow::CreateOffer() {
+ CHECK(!IsRunningOnSignalingThread());
+ Future<SessionDescriptionWrapper> success_future;
+ if (!RunOnSignalingThread([this, success_future] {
+ CreateOfferOnSignalingThread(success_future);
+ })) {
+ NEARBY_LOG(ERROR, "Failed to create offer");
+ return SessionDescriptionWrapper();
+ }
+ ExceptionOr<SessionDescriptionWrapper> result = success_future.Get(kTimeout);
+ if (result.ok()) {
+ return std::move(result.result());
+ }
+ NEARBY_LOG(ERROR, "Failed to create offer: %d", result.exception());
+ return SessionDescriptionWrapper();
+}
+
+void ConnectionFlow::CreateOfferOnSignalingThread(
+ Future<SessionDescriptionWrapper> success_future) {
+ if (!TransitionState(State::kInitialized, State::kCreatingOffer)) {
+ success_future.SetException({Exception::kFailed});
+ return;
+ }
+ webrtc::DataChannelInit data_channel_init;
+ data_channel_init.reliable = true;
+ auto pc = GetPeerConnection();
+ CreateSocketFromDataChannel(
+ pc->CreateDataChannel(kDataChannelName, &data_channel_init));
+
+ webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options;
+ rtc::scoped_refptr<CreateSessionDescriptionObserverImpl> observer(
+ new rtc::RefCountedObject<CreateSessionDescriptionObserverImpl>(
+ this, success_future, State::kCreatingOffer,
+ State::kWaitingForAnswer));
+ pc->CreateOffer(observer, options);
+}
+
+SessionDescriptionWrapper ConnectionFlow::CreateAnswer() {
+ CHECK(!IsRunningOnSignalingThread());
+ Future<SessionDescriptionWrapper> success_future;
+ if (!RunOnSignalingThread([this, success_future] {
+ CreateAnswerOnSignalingThread(success_future);
+ })) {
+ NEARBY_LOG(ERROR, "Failed to create answer");
+ return SessionDescriptionWrapper();
+ }
+ ExceptionOr<SessionDescriptionWrapper> result = success_future.Get(kTimeout);
+ if (result.ok()) {
+ return std::move(result.result());
+ }
+ NEARBY_LOG(ERROR, "Failed to create answer: %d", result.exception());
+ return SessionDescriptionWrapper();
+}
+
+void ConnectionFlow::CreateAnswerOnSignalingThread(
+ Future<SessionDescriptionWrapper> success_future) {
+ if (!TransitionState(State::kReceivedOffer, State::kCreatingAnswer)) {
+ success_future.SetException({Exception::kFailed});
+ return;
+ }
+ webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options;
+ rtc::scoped_refptr<CreateSessionDescriptionObserverImpl> observer(
+ new rtc::RefCountedObject<CreateSessionDescriptionObserverImpl>(
+ this, success_future, State::kCreatingAnswer,
+ State::kWaitingToConnect));
+ auto pc = GetPeerConnection();
+ pc->CreateAnswer(observer, options);
+}
+
+bool ConnectionFlow::SetLocalSessionDescription(SessionDescriptionWrapper sdp) {
+ CHECK(!IsRunningOnSignalingThread());
+ if (!sdp.IsValid()) return false;
+
+ rtc::scoped_refptr<SetLocalDescriptionObserver> observer(
+ new rtc::RefCountedObject<SetLocalDescriptionObserver>());
+
+ if (!RunOnSignalingThread([this, observer, sdp = std::move(sdp)]() mutable {
+ if (state_ == State::kEnded) {
+ observer->OnSetLocalDescriptionComplete(
+ webrtc::RTCError(webrtc::RTCErrorType::INVALID_STATE));
+ return;
+ }
+ auto pc = GetPeerConnection();
+
+ pc->SetLocalDescription(
+ std::unique_ptr<webrtc::SessionDescriptionInterface>(sdp.Release()),
+ observer);
+ })) {
+ return false;
+ }
+
+ ExceptionOr<bool> result = observer->GetResult(kTimeout);
+ bool success = result.ok() && result.result();
+ if (!success) {
+ NEARBY_LOG(ERROR, "Failed to set local session description: %d",
+ result.exception());
+ }
+ return success;
+}
+
+bool ConnectionFlow::SetRemoteSessionDescription(SessionDescriptionWrapper sdp,
+ State expected_entry_state,
+ State exit_state) {
+ if (!sdp.IsValid()) return false;
+
+ rtc::scoped_refptr<SetRemoteDescriptionObserver> observer(
+ new rtc::RefCountedObject<SetRemoteDescriptionObserver>());
+
+ if (!RunOnSignalingThread([this, observer, sdp = std::move(sdp),
+ expected_entry_state, exit_state]() mutable {
+ if (!TransitionState(expected_entry_state, exit_state)) {
+ observer->OnSetRemoteDescriptionComplete(
+ webrtc::RTCError(webrtc::RTCErrorType::INVALID_STATE));
+ return;
+ }
+ auto pc = GetPeerConnection();
+
+ pc->SetRemoteDescription(
+ std::unique_ptr<webrtc::SessionDescriptionInterface>(sdp.Release()),
+ observer);
+ })) {
+ return false;
+ }
+
+ ExceptionOr<bool> result = observer->GetResult(kTimeout);
+ bool success = result.ok() && result.result();
+ if (!success) {
+ NEARBY_LOG(ERROR, "Failed to set remote description: %d",
+ result.exception());
+ }
+ return success;
+}
+
+bool ConnectionFlow::OnOfferReceived(SessionDescriptionWrapper offer) {
+ CHECK(!IsRunningOnSignalingThread());
+ return SetRemoteSessionDescription(std::move(offer), State::kInitialized,
+ State::kReceivedOffer);
+}
+
+bool ConnectionFlow::OnAnswerReceived(SessionDescriptionWrapper answer) {
+ CHECK(!IsRunningOnSignalingThread());
+ return SetRemoteSessionDescription(
+ std::move(answer), State::kWaitingForAnswer, State::kWaitingToConnect);
+}
+
+bool ConnectionFlow::OnRemoteIceCandidatesReceived(
+ std::vector<std::unique_ptr<webrtc::IceCandidateInterface>>
+ ice_candidates) {
+ CHECK(!IsRunningOnSignalingThread());
+ // We can't call RunOnSignalingThread because C++ wants to copy ice_candidates
+ // if we try. unique_ptr is not CopyConstructible and compilation fails.
+ auto pc = GetPeerConnection();
+
+ if (!pc) {
+ return false;
+ }
+ pc->signaling_thread()->PostTask(
+ [this, can_run_tasks = std::weak_ptr<void>(can_run_tasks_),
+ candidates = std::move(ice_candidates)]() mutable {
+ // don't run the task if the weak_ptr is no longer valid.
+ if (!can_run_tasks.lock()) {
+ return;
+ }
+ AddIceCandidatesOnSignalingThread(std::move(candidates));
+ });
+ return true;
+}
+
+void ConnectionFlow::AddIceCandidatesOnSignalingThread(
+ std::vector<std::unique_ptr<webrtc::IceCandidateInterface>>
+ ice_candidates) {
+ CHECK(IsRunningOnSignalingThread());
+ if (state_ == State::kEnded) {
+ NEARBY_LOG(WARNING,
+ "You cannot add ice candidates to a disconnected session.");
+ return;
+ }
+ if (state_ != State::kWaitingToConnect && state_ != State::kConnected) {
+ cached_remote_ice_candidates_.insert(
+ cached_remote_ice_candidates_.end(),
+ std::make_move_iterator(ice_candidates.begin()),
+ std::make_move_iterator(ice_candidates.end()));
+ return;
+ }
+ auto pc = GetPeerConnection();
+ for (auto&& ice_candidate : ice_candidates) {
+ if (!pc->AddIceCandidate(ice_candidate.get())) {
+ NEARBY_LOG(WARNING, "Unable to add remote ice candidate.");
+ }
+ }
+}
+
+bool ConnectionFlow::CloseIfNotConnected() {
+ CHECK(!IsRunningOnSignalingThread());
+ Future<bool> closed;
+ if (RunOnSignalingThread([this, closed]() mutable {
+ if (state_ == State::kConnected) {
+ closed.Set(false);
+ } else {
+ CloseOnSignalingThread();
+ closed.Set(true);
+ }
+ })) {
+ auto result = closed.Get();
+ return result.ok() && result.result();
+ }
+ return true;
+}
+
+bool ConnectionFlow::InitPeerConnection(WebRtcMedium& webrtc_medium) {
+ Future<bool> success_future;
+ // CreatePeerConnection callback may be invoked after ConnectionFlow lifetime
+ // has ended, in case of a timeout. Future is captured by value, and is safe
+ // to access, but it is not safe to access ConnectionFlow member variables
+ // unless the Future::Set() returns true.
+ webrtc_medium.CreatePeerConnection(
+ this,
+ [this, success_future](rtc::scoped_refptr<webrtc::PeerConnectionInterface>
+ peer_connection) mutable {
+ if (!peer_connection) {
+ success_future.Set(false);
+ return;
+ }
+
+ // If this fails, means we have already assigned something to
+ // success_future; it is either:
+ // 1) this is the 2nd call of this callback (and this is a bug), or
+ // 2) Get(timeout) has set the future value as exception already.
+ if (success_future.IsSet()) return;
+ MutexLock lock(&mutex_);
+ peer_connection_ = peer_connection;
+ signaling_thread_for_dcheck_only_ =
+ peer_connection_->signaling_thread();
+ success_future.Set(true);
+ });
+
+ ExceptionOr<bool> result = success_future.Get(kPeerConnectionTimeout);
+ bool success = result.ok() && result.result();
+ if (!success) {
+ shutdown_latch_.CountDown();
+ NEARBY_LOG(ERROR, "Failed to create peer connection: %d",
+ result.exception());
+ }
+ return success;
+}
+
+void ConnectionFlow::OnSignalingStable() {
+ if (state_ != State::kWaitingToConnect && state_ != State::kConnected) return;
+ auto pc = GetPeerConnection();
+ for (auto&& ice_candidate : cached_remote_ice_candidates_) {
+ if (!pc->AddIceCandidate(ice_candidate.get())) {
+ NEARBY_LOG(WARNING, "Unable to add remote ice candidate.");
+ }
+ }
+ cached_remote_ice_candidates_.clear();
+}
+
+void ConnectionFlow::CreateSocketFromDataChannel(
+ rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel) {
+ NEARBY_LOG(INFO, "Creating data channel socket");
+ auto socket =
+ std::make_unique<WebRtcSocket>("WebRtcSocket", std::move(data_channel));
+ socket->SetSocketListener({
+ .socket_ready_cb = {[this](WebRtcSocket* socket) {
+ CHECK(IsRunningOnSignalingThread());
+ if (!TransitionState(State::kWaitingToConnect, State::kConnected)) {
+ NEARBY_LOG(ERROR,
+ "Data channel socket is open but connection flow was not "
+ "in the required state");
+ socket->Close();
+ return;
+ }
+ // Pass socket wrapper by copy on purpose
+ data_channel_listener_.data_channel_open_cb(socket_wrapper_);
+ }},
+ .socket_closed_cb = [callback =
+ data_channel_listener_.data_channel_closed_cb](
+ WebRtcSocket*) { callback(); },
+ });
+ socket_wrapper_ = WebRtcSocketWrapper(std::move(socket));
+}
+
+void ConnectionFlow::OnIceCandidate(
+ const webrtc::IceCandidateInterface* candidate) {
+ CHECK(IsRunningOnSignalingThread());
+ local_ice_candidate_listener_.local_ice_candidate_found_cb(candidate);
+}
+
+void ConnectionFlow::OnSignalingChange(
+ webrtc::PeerConnectionInterface::SignalingState new_state) {
+ NEARBY_LOG(INFO, "OnSignalingChange: %d", new_state);
+ CHECK(IsRunningOnSignalingThread());
+ if (new_state == webrtc::PeerConnectionInterface::SignalingState::kStable) {
+ OnSignalingStable();
+ }
+}
+
+void ConnectionFlow::OnDataChannel(
+ rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel) {
+ NEARBY_LOG(INFO, "OnDataChannel");
+ CHECK(IsRunningOnSignalingThread());
+ CreateSocketFromDataChannel(std::move(data_channel));
+}
+
+void ConnectionFlow::OnIceGatheringChange(
+ webrtc::PeerConnectionInterface::IceGatheringState new_state) {
+ NEARBY_LOG(INFO, "OnIceGatheringChange: %d", new_state);
+ CHECK(IsRunningOnSignalingThread());
+}
+
+void ConnectionFlow::OnConnectionChange(
+ webrtc::PeerConnectionInterface::PeerConnectionState new_state) {
+ NEARBY_LOG(INFO, "OnConnectionChange: %d", new_state);
+ CHECK(IsRunningOnSignalingThread());
+ if (new_state == PeerConnectionState::kClosed ||
+ new_state == PeerConnectionState::kFailed ||
+ new_state == PeerConnectionState::kDisconnected) {
+ NEARBY_LOG(INFO, "Closing due to peer connection state change: %d",
+ new_state);
+ CloseOnSignalingThread();
+ }
+}
+
+void ConnectionFlow::OnRenegotiationNeeded() {
+ NEARBY_LOG(INFO, "OnRenegotiationNeeded");
+ CHECK(IsRunningOnSignalingThread());
+}
+
+bool ConnectionFlow::TransitionState(State current_state, State new_state) {
+ CHECK(IsRunningOnSignalingThread());
+ if (current_state != state_) {
+ NEARBY_LOG(
+ WARNING,
+ "Invalid state transition to %d: current state is %d but expected %d.",
+ new_state, state_, current_state);
+ return false;
+ }
+ NEARBY_LOG(INFO, "Transition: %d -> %d", state_, new_state);
+ state_ = new_state;
+ return true;
+}
+
+bool ConnectionFlow::CloseOnSignalingThread() {
+ if (state_ == State::kEnded) {
+ return false;
+ }
+ state_ = State::kEnded;
+ // This prevents other tasks from queuing on the signaling thread for this
+ // object.
+ auto pc = GetAndResetPeerConnection();
+
+ NEARBY_LOG(INFO, "Closing WebRTC peer connection.");
+ // NOTE: Closing the peer conection will close the data channel and thus the
+ // socket implicitly.
+ if (pc) pc->Close();
+ NEARBY_LOG(INFO, "Closed WebRTC peer connection.");
+ // Prevent any already queued tasks from running on the signaling thread
+ can_run_tasks_.reset();
+ // If anyone was waiting for shutdown to be done let them know.
+ shutdown_latch_.CountDown();
+ return true;
+}
+
+bool ConnectionFlow::RunOnSignalingThread(Runnable&& runnable) {
+ CHECK(!IsRunningOnSignalingThread());
+ auto pc = GetPeerConnection();
+ if (!pc) {
+ NEARBY_LOG(WARNING,
+ "Peer connection not available. Cannot schedule tasks.");
+ return false;
+ }
+ // We are off signaling thread, so we can't use peer connection's methods
+ // but we can access the signaling thread handle.
+ pc->signaling_thread()->PostTask(
+ [can_run_tasks = std::weak_ptr<void>(can_run_tasks_),
+ task = std::move(runnable)] {
+ // don't run the task if the weak_ptr is no longer valid.
+ // shared_ptr |can_run_tasks_| is destroyed on the same thread
+ // (signaling thread). This guarantees that if the weak_ptr is valid
+ // when this task starts, it will stay valid until the task ends.
+ if (!can_run_tasks.lock()) {
+ NEARBY_LOG(INFO, "Peer connection already closed. Cannot run tasks.");
+ return;
+ }
+ task();
+ });
+ return true;
+}
+
+bool ConnectionFlow::IsRunningOnSignalingThread() {
+ return signaling_thread_for_dcheck_only_ != nullptr &&
+ signaling_thread_for_dcheck_only_ == rtc::Thread::Current();
+}
+
+rtc::scoped_refptr<webrtc::PeerConnectionInterface>
+ConnectionFlow::GetPeerConnection() {
+ // We must use a mutex to ensure that peer connection is
+ // fully initialized.
+ // We increase the peer_connection_'s refcount to keep it
+ // alive while we use it.
+ MutexLock lock(&mutex_);
+ return peer_connection_;
+}
+
+rtc::scoped_refptr<webrtc::PeerConnectionInterface>
+ConnectionFlow::GetAndResetPeerConnection() {
+ MutexLock lock(&mutex_);
+ return std::move(peer_connection_);
+}
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/connection_flow.h b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/connection_flow.h
new file mode 100644
index 00000000000..d042d102337
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/connection_flow.h
@@ -0,0 +1,233 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MEDIUMS_WEBRTC_CONNECTION_FLOW_H_
+#define CORE_INTERNAL_MEDIUMS_WEBRTC_CONNECTION_FLOW_H_
+
+#include <memory>
+
+#include "connections/implementation/mediums/webrtc/data_channel_listener.h"
+#include "connections/implementation/mediums/webrtc/local_ice_candidate_listener.h"
+#include "connections/implementation/mediums/webrtc/session_description_wrapper.h"
+#include "connections/implementation/mediums/webrtc_socket.h"
+#include "internal/platform/runnable.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/single_thread_executor.h"
+#include "internal/platform/webrtc.h"
+#include "webrtc/api/data_channel_interface.h"
+#include "webrtc/api/peer_connection_interface.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+/**
+ * Flow for an offerer:
+ *
+ * <ul>
+ * <li>INITIALIZED: After construction.
+ * <li>CREATING_OFFER: After CreateOffer(). Local ice candidate collection
+ * begins.
+ * <li>WAITING_FOR_ANSWER: Until the remote peer sends their answer.
+ * <li>WAITING_TO_CONNECT: Until the data channel actually connects. Remote
+ * ice candidates should be added with OnRemoteIceCandidatesReceived as they are
+ * gathered.
+ * <li>CONNECTED: We successfully connected to the remote data
+ * channel.
+ * <li>ENDED: The final state that can occur from any of the previous
+ * states if we disconnect at any point in the flow.
+ * </ul>
+ *
+ * <p>Flow for an answerer:
+ *
+ * <ul>
+ * <li>INITIALIZED: After construction.
+ * <li>RECEIVED_OFFER: After onOfferReceived().
+ * <li>CREATING_ANSWER: After CreateAnswer(). Local ice candidate collection
+ * begins.
+ * <li>WAITING_TO_CONNECT: Until the data channel actually connects.
+ * Remote ice candidates should be added with OnRemoteIceCandidatesReceived as
+ * they are gathered.
+ * <li>CONNECTED: We successfully connected to the remote
+ * data channel.
+ * <li>ENDED: The final state that can occur from any of the
+ * previous states if we disconnect at any point in the flow.
+ * </ul>
+ */
+class ConnectionFlow : public webrtc::PeerConnectionObserver {
+ public:
+ enum class State {
+ kInitialized,
+ kCreatingOffer,
+ kWaitingForAnswer,
+ kReceivedOffer,
+ kCreatingAnswer,
+ kWaitingToConnect,
+ kConnected,
+ kEnded,
+ };
+
+ // This method blocks on the creation of the peer connection object.
+ // Can be called on any thread but never called on signaling thread.
+ static std::unique_ptr<ConnectionFlow> Create(
+ LocalIceCandidateListener local_ice_candidate_listener,
+ DataChannelListener data_channel_listener, WebRtcMedium& webrtc_medium);
+ ~ConnectionFlow() override;
+
+ // Create the offer that will be sent to the remote. Mirrors the behaviour of
+ // PeerConnectionInterface::CreateOffer.
+ // Can be called on any thread but never called on signaling thread.
+ SessionDescriptionWrapper CreateOffer() ABSL_LOCKS_EXCLUDED(mutex_);
+ // Create the answer that will be sent to the remote. Mirrors the behaviour of
+ // PeerConnectionInterface::CreateAnswer.
+ // Can be called on any thread but never called on signaling thread.
+ SessionDescriptionWrapper CreateAnswer() ABSL_LOCKS_EXCLUDED(mutex_);
+ // Set the local session description. |sdp| was created via CreateOffer()
+ // or CreateAnswer().
+ // Can be called on any thread but never called on signaling thread.
+ bool SetLocalSessionDescription(SessionDescriptionWrapper sdp)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ // Invoked when an offer was received from a remote; this will set the remote
+ // session description on the peer connection. Returns true if the offer was
+ // successfully set as remote session description.
+ // Can be called on any thread but never called on signaling thread.
+ bool OnOfferReceived(SessionDescriptionWrapper offer)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ // Invoked when an answer was received from a remote; this will set the remote
+ // session description on the peer connection. Returns true if the offer was
+ // successfully set as remote session description.
+ // Can be called on any thread but never called on signaling thread.
+ bool OnAnswerReceived(SessionDescriptionWrapper answer)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ // Invoked when an ice candidate was received from a remote; this will add the
+ // ice candidate to the peer connection if ready or cache it otherwise.
+ // Can be called on any thread but never called on signaling thread.
+ bool OnRemoteIceCandidatesReceived(
+ std::vector<std::unique_ptr<webrtc::IceCandidateInterface>>
+ ice_candidates) ABSL_LOCKS_EXCLUDED(mutex_);
+ // Close the peer connection and data channel if not connected.
+ // Can be called on any thread but never called on signaling thread.
+ bool CloseIfNotConnected() ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // webrtc::PeerConnectionObserver:
+ // All methods called only on signaling thread.
+ void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override;
+ void OnSignalingChange(
+ webrtc::PeerConnectionInterface::SignalingState new_state) override;
+ void OnDataChannel(
+ rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel) override;
+ void OnIceGatheringChange(
+ webrtc::PeerConnectionInterface::IceGatheringState new_state) override;
+ void OnConnectionChange(
+ webrtc::PeerConnectionInterface::PeerConnectionState new_state) override;
+ void OnRenegotiationNeeded() override;
+
+ // Public because it's used in tests too.
+ rtc::scoped_refptr<webrtc::PeerConnectionInterface> GetPeerConnection();
+
+ private:
+ ConnectionFlow(LocalIceCandidateListener local_ice_candidate_listener,
+ DataChannelListener data_channel_listener);
+
+ // Resets peer connection reference. Returns old value.
+ rtc::scoped_refptr<webrtc::PeerConnectionInterface>
+ GetAndResetPeerConnection();
+ void CreateOfferOnSignalingThread(
+ Future<SessionDescriptionWrapper> success_future);
+ void CreateAnswerOnSignalingThread(
+ Future<SessionDescriptionWrapper> success_future);
+ void AddIceCandidatesOnSignalingThread(
+ std::vector<std::unique_ptr<webrtc::IceCandidateInterface>>
+ ice_candidates);
+ // Invoked when the peer connection indicates that signaling is stable.
+ void OnSignalingStable() ABSL_LOCKS_EXCLUDED(mutex_);
+
+ void CreateSocketFromDataChannel(
+ rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel);
+
+ // TODO(bfranz): Consider whether this needs to be configurable per platform
+ static constexpr absl::Duration kTimeout = absl::Milliseconds(250);
+ static constexpr absl::Duration kPeerConnectionTimeout =
+ absl::Milliseconds(2500);
+
+ bool InitPeerConnection(WebRtcMedium& webrtc_medium);
+
+ bool TransitionState(State current_state, State new_state);
+
+ bool SetRemoteSessionDescription(SessionDescriptionWrapper sdp,
+ State expected_entry_state,
+ State exit_state);
+
+ bool CloseOnSignalingThread() ABSL_LOCKS_EXCLUDED(mutex_);
+
+ bool RunOnSignalingThread(Runnable&& runnable);
+ bool IsRunningOnSignalingThread();
+
+ Mutex mutex_;
+ // Used to prevent the destructor from returning while the signaling thread is
+ // still running CloseOnSignalingThread()
+ CountDownLatch shutdown_latch_{1};
+
+ // State is used on signaling thread only.
+ State state_ = State::kInitialized;
+ // Used to communicate data channel events back to the caller of Create()
+ DataChannelListener data_channel_listener_;
+
+ LocalIceCandidateListener local_ice_candidate_listener_;
+ // Peer connection can be used only on signaling thread. The only exception
+ // is accessing the signaling thread handle. Tasks posted on the
+ // signaling thread may outlive both |peer_connection_| and |this| objects.
+ // A mutex is required to access peer connection reference because peer
+ // connection object and the reference can be initialized on different
+ // threads - the reference could be initialized before peer connection's
+ // constructor has finished.
+ // |peer_connection_| is actually implemented by PeerConnectionProxy, which
+ // runs the real PeerConnection's methods on the correct thread (signaling or
+ // worker). If a proxy method is called on the correct thread, then the real
+ // method is called directly. Otherwise, a task is posted on the correct
+ // thread and the current thread is blocked until that task finishes. We
+ // choose to explicitly use |peer_connection_| on the signaling thread,
+ // because it allows us to do state management on the signaling thread too,
+ // simplifies locking, and we don't have to block the current thread for every
+ // peer connection call.
+ rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_
+ ABSL_GUARDED_BY(mutex_);
+
+ // Used to hold a reference to the WebRtcSocket while the data channel is
+ // connecting.
+ WebRtcSocketWrapper socket_wrapper_;
+
+ std::vector<std::unique_ptr<webrtc::IceCandidateInterface>>
+ cached_remote_ice_candidates_;
+ // This pointer is only for DCHECK() assertions.
+ // It allows us to check if we are running on signaling thread even
+ // after destroying |peer_connection_|.
+ const void* signaling_thread_for_dcheck_only_ = nullptr;
+ // This shared_ptr is reset on the signaling thread when ConnectionFlow is
+ // closed. This prevents us from running tasks on the signaling thread when
+ // peer connection is closed. The value stored in |can_run_tasks_| is not
+ // used. We are using std::shared_ptr instead of rtc::WeakPtrFactory because
+ // the former is thread-safe.
+ std::shared_ptr<void> can_run_tasks_ = std::make_shared<int>();
+
+ friend class CreateSessionDescriptionObserverImpl;
+};
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MEDIUMS_WEBRTC_CONNECTION_FLOW_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/connection_flow_test.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/connection_flow_test.cc
new file mode 100644
index 00000000000..340be2283b6
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/connection_flow_test.cc
@@ -0,0 +1,408 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/webrtc/connection_flow.h"
+
+#include <memory>
+#include <vector>
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "absl/time/time.h"
+#include "connections/implementation/mediums/webrtc/session_description_wrapper.h"
+#include "connections/implementation/mediums/webrtc_socket.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/medium_environment.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/webrtc.h"
+#include "webrtc/api/data_channel_interface.h"
+#include "webrtc/api/jsep.h"
+#include "webrtc/api/rtc_error.h"
+#include "webrtc/api/scoped_refptr.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+namespace {
+
+class ConnectionFlowTest : public ::testing::Test {
+ protected:
+ ConnectionFlowTest() {
+ MediumEnvironment::Instance().Stop();
+ MediumEnvironment::Instance().Start({.webrtc_enabled = true});
+ }
+};
+
+std::unique_ptr<webrtc::IceCandidateInterface> CopyCandidate(
+ const webrtc::IceCandidateInterface* candidate) {
+ return webrtc::CreateIceCandidate(candidate->sdp_mid(),
+ candidate->sdp_mline_index(),
+ candidate->candidate());
+}
+
+// TODO(bfranz) - Add test that deterministically sends answerer_ice_candidates
+// before answer is sent.
+TEST_F(ConnectionFlowTest, SuccessfulOfferAnswerFlow) {
+ WebRtcMedium webrtc_medium_offerer, webrtc_medium_answerer;
+
+ Future<ByteArray> message_received_future;
+
+ Future<WebRtcSocketWrapper> offerer_socket_future, answerer_socket_future;
+
+ std::unique_ptr<ConnectionFlow> offerer, answerer;
+
+ // Send Ice Candidates immediately when you retrieve them
+ offerer = ConnectionFlow::Create(
+ {.local_ice_candidate_found_cb =
+ [&answerer](const webrtc::IceCandidateInterface* candidate) {
+ std::vector<std::unique_ptr<webrtc::IceCandidateInterface>> vec;
+ vec.push_back(CopyCandidate(candidate));
+ // The callback might be alive while the objects in test are
+ // destroyed.
+ if (answerer)
+ answerer->OnRemoteIceCandidatesReceived(std::move(vec));
+ }},
+ {.data_channel_open_cb =
+ [&offerer_socket_future](WebRtcSocketWrapper socket) {
+ offerer_socket_future.Set(std::move(socket));
+ }},
+ webrtc_medium_offerer);
+ ASSERT_NE(offerer, nullptr);
+ answerer = ConnectionFlow::Create(
+ {.local_ice_candidate_found_cb =
+ [&offerer](const webrtc::IceCandidateInterface* candidate) {
+ std::vector<std::unique_ptr<webrtc::IceCandidateInterface>> vec;
+ vec.push_back(CopyCandidate(candidate));
+ // The callback might be alive while the objects in test are
+ // destroyed.
+ if (offerer)
+ offerer->OnRemoteIceCandidatesReceived(std::move(vec));
+ }},
+ {.data_channel_open_cb =
+ [&answerer_socket_future](WebRtcSocketWrapper socket) {
+ answerer_socket_future.Set(std::move(socket));
+ }},
+ webrtc_medium_answerer);
+ ASSERT_NE(answerer, nullptr);
+
+ // Create and send offer
+ SessionDescriptionWrapper offer = offerer->CreateOffer();
+ ASSERT_TRUE(offer.IsValid());
+ EXPECT_EQ(offer.GetType(), webrtc::SdpType::kOffer);
+ EXPECT_TRUE(answerer->OnOfferReceived(offer));
+ EXPECT_TRUE(offerer->SetLocalSessionDescription(std::move(offer)));
+
+ // Create and send answer
+ SessionDescriptionWrapper answer = answerer->CreateAnswer();
+ ASSERT_TRUE(answer.IsValid());
+ EXPECT_EQ(answer.GetType(), webrtc::SdpType::kAnswer);
+ EXPECT_TRUE(offerer->OnAnswerReceived(answer));
+ EXPECT_TRUE(answerer->SetLocalSessionDescription(std::move(answer)));
+
+ // Retrieve Data Channels
+ ExceptionOr<WebRtcSocketWrapper> offerer_socket =
+ offerer_socket_future.Get(absl::Seconds(1));
+ EXPECT_TRUE(offerer_socket.ok());
+ ExceptionOr<WebRtcSocketWrapper> answerer_socket =
+ answerer_socket_future.Get(absl::Seconds(1));
+ EXPECT_TRUE(answerer_socket.ok());
+
+ // Send message on data channel
+ const char message[] = "Test";
+ offerer_socket.result().GetImpl().GetOutputStream().Write(
+ ByteArray(message, 4));
+ ExceptionOr<ByteArray> received_message =
+ answerer_socket.result().GetImpl().GetInputStream().Read(4);
+ EXPECT_TRUE(received_message.ok());
+ EXPECT_EQ(received_message.result(), ByteArray{message});
+}
+
+TEST_F(ConnectionFlowTest, CreateAnswerBeforeOfferReceived) {
+ WebRtcMedium webrtc_medium;
+
+ std::unique_ptr<ConnectionFlow> answerer = ConnectionFlow::Create(
+ LocalIceCandidateListener(), DataChannelListener(), webrtc_medium);
+ ASSERT_NE(answerer, nullptr);
+
+ SessionDescriptionWrapper answer = answerer->CreateAnswer();
+ EXPECT_FALSE(answer.IsValid());
+}
+
+TEST_F(ConnectionFlowTest, SetAnswerBeforeOffer) {
+ WebRtcMedium webrtc_medium_offerer, webrtc_medium_answerer;
+
+ std::unique_ptr<ConnectionFlow> offerer =
+ ConnectionFlow::Create(LocalIceCandidateListener(), DataChannelListener(),
+ webrtc_medium_offerer);
+ ASSERT_NE(offerer, nullptr);
+ std::unique_ptr<ConnectionFlow> answerer =
+ ConnectionFlow::Create(LocalIceCandidateListener(), DataChannelListener(),
+ webrtc_medium_answerer);
+ ASSERT_NE(answerer, nullptr);
+
+ SessionDescriptionWrapper offer = offerer->CreateOffer();
+ ASSERT_TRUE(offer.IsValid());
+ EXPECT_EQ(offer.GetType(), webrtc::SdpType::kOffer);
+ // Did not set offer as local session description
+ EXPECT_TRUE(answerer->OnOfferReceived(offer));
+
+ SessionDescriptionWrapper answer = answerer->CreateAnswer();
+ ASSERT_TRUE(answer.IsValid());
+ EXPECT_EQ(answer.GetType(), webrtc::SdpType::kAnswer);
+ EXPECT_FALSE(offerer->OnAnswerReceived(answer));
+}
+
+TEST_F(ConnectionFlowTest, CannotCreateOfferAfterClose) {
+ WebRtcMedium webrtc_medium;
+
+ std::unique_ptr<ConnectionFlow> offerer = ConnectionFlow::Create(
+ LocalIceCandidateListener(), DataChannelListener(), webrtc_medium);
+ ASSERT_NE(offerer, nullptr);
+
+ EXPECT_TRUE(offerer->CloseIfNotConnected());
+
+ EXPECT_FALSE(offerer->CreateOffer().IsValid());
+}
+
+TEST_F(ConnectionFlowTest, CannotSetSessionDescriptionAfterClose) {
+ WebRtcMedium webrtc_medium;
+
+ std::unique_ptr<ConnectionFlow> offerer = ConnectionFlow::Create(
+ LocalIceCandidateListener(), DataChannelListener(), webrtc_medium);
+ ASSERT_NE(offerer, nullptr);
+
+ SessionDescriptionWrapper offer = offerer->CreateOffer();
+ ASSERT_TRUE(offer.IsValid());
+ EXPECT_EQ(offer.GetType(), webrtc::SdpType::kOffer);
+
+ EXPECT_TRUE(offerer->CloseIfNotConnected());
+
+ EXPECT_FALSE(offerer->SetLocalSessionDescription(offer));
+}
+
+TEST_F(ConnectionFlowTest, CannotReceiveOfferAfterClose) {
+ WebRtcMedium webrtc_medium_offerer, webrtc_medium_answerer;
+
+ std::unique_ptr<ConnectionFlow> offerer =
+ ConnectionFlow::Create(LocalIceCandidateListener(), DataChannelListener(),
+ webrtc_medium_offerer);
+ ASSERT_NE(offerer, nullptr);
+ std::unique_ptr<ConnectionFlow> answerer =
+ ConnectionFlow::Create(LocalIceCandidateListener(), DataChannelListener(),
+ webrtc_medium_answerer);
+ ASSERT_NE(answerer, nullptr);
+
+ EXPECT_TRUE(answerer->CloseIfNotConnected());
+
+ SessionDescriptionWrapper offer = offerer->CreateOffer();
+ ASSERT_TRUE(offer.IsValid());
+ EXPECT_EQ(offer.GetType(), webrtc::SdpType::kOffer);
+
+ EXPECT_FALSE(answerer->OnOfferReceived(offer));
+}
+
+TEST_F(ConnectionFlowTest, NullPeerConnection) {
+ MediumEnvironment::Instance().SetUseValidPeerConnection(
+ /*use_valid_peer_connection=*/false);
+
+ WebRtcMedium medium;
+ std::unique_ptr<ConnectionFlow> answerer = ConnectionFlow::Create(
+ LocalIceCandidateListener(), DataChannelListener(), medium);
+ EXPECT_EQ(answerer, nullptr);
+}
+
+TEST_F(ConnectionFlowTest, PeerConnectionTimeout) {
+ MediumEnvironment::Instance().SetUseValidPeerConnection(
+ /*use_valid_peer_connection=*/true);
+ WebRtcMedium medium1;
+ std::unique_ptr<ConnectionFlow> flow1 = ConnectionFlow::Create(
+ LocalIceCandidateListener(), DataChannelListener(), medium1);
+ EXPECT_NE(flow1, nullptr);
+
+ // Attempt to trigger the 2.5s peer connection timeout.
+ MediumEnvironment::Instance().SetPeerConnectionLatency(absl::Seconds(5));
+ WebRtcMedium medium2;
+ std::unique_ptr<ConnectionFlow> flow2 = ConnectionFlow::Create(
+ LocalIceCandidateListener(), DataChannelListener(), medium2);
+ EXPECT_EQ(flow2, nullptr);
+}
+
+TEST_F(ConnectionFlowTest, TerminateAnswerer) {
+ WebRtcMedium webrtc_medium_offerer, webrtc_medium_answerer;
+
+ Future<ByteArray> message_received_future;
+
+ Future<WebRtcSocketWrapper> offerer_socket_future, answerer_socket_future;
+
+ std::unique_ptr<ConnectionFlow> offerer, answerer;
+
+ // Send Ice Candidates immediately when you retrieve them
+ offerer = ConnectionFlow::Create(
+ {.local_ice_candidate_found_cb =
+ [&answerer](const webrtc::IceCandidateInterface* candidate) {
+ std::vector<std::unique_ptr<webrtc::IceCandidateInterface>> vec;
+ vec.push_back(CopyCandidate(candidate));
+ // The callback might be alive while the objects in test are
+ // destroyed.
+ if (answerer)
+ answerer->OnRemoteIceCandidatesReceived(std::move(vec));
+ }},
+ {.data_channel_open_cb =
+ [&offerer_socket_future](WebRtcSocketWrapper socket) {
+ offerer_socket_future.Set(std::move(socket));
+ }},
+ webrtc_medium_offerer);
+ ASSERT_NE(offerer, nullptr);
+ answerer = ConnectionFlow::Create(
+ {.local_ice_candidate_found_cb =
+ [&offerer](const webrtc::IceCandidateInterface* candidate) {
+ std::vector<std::unique_ptr<webrtc::IceCandidateInterface>> vec;
+ vec.push_back(CopyCandidate(candidate));
+ // The callback might be alive while the objects in test are
+ // destroyed.
+ if (offerer)
+ offerer->OnRemoteIceCandidatesReceived(std::move(vec));
+ }},
+ {.data_channel_open_cb =
+ [&answerer_socket_future](WebRtcSocketWrapper wrapper) {
+ answerer_socket_future.Set(std::move(wrapper));
+ }},
+ webrtc_medium_answerer);
+ ASSERT_NE(answerer, nullptr);
+
+ // Create and send offer
+ SessionDescriptionWrapper offer = offerer->CreateOffer();
+ ASSERT_TRUE(offer.IsValid());
+ EXPECT_EQ(offer.GetType(), webrtc::SdpType::kOffer);
+ EXPECT_TRUE(answerer->OnOfferReceived(offer));
+ EXPECT_TRUE(offerer->SetLocalSessionDescription(std::move(offer)));
+
+ // Create and send answer
+ SessionDescriptionWrapper answer = answerer->CreateAnswer();
+ ASSERT_TRUE(answer.IsValid());
+ EXPECT_EQ(answer.GetType(), webrtc::SdpType::kAnswer);
+ EXPECT_TRUE(offerer->OnAnswerReceived(answer));
+ EXPECT_TRUE(answerer->SetLocalSessionDescription(std::move(answer)));
+
+ // Retrieve Data Channels
+ ExceptionOr<WebRtcSocketWrapper> offerer_socket =
+ offerer_socket_future.Get(absl::Seconds(1));
+ EXPECT_TRUE(offerer_socket.ok());
+ ExceptionOr<WebRtcSocketWrapper> answerer_socket =
+ answerer_socket_future.Get(absl::Seconds(1));
+ EXPECT_TRUE(offerer_socket.ok());
+
+ CountDownLatch latch(1);
+ auto pc = answerer->GetPeerConnection();
+ pc->signaling_thread()->PostTask([pc, latch]() mutable {
+ pc->Close();
+ latch.CountDown();
+ });
+ latch.Await();
+
+ // Send message on data channel
+ std::string message = "Test";
+ offerer_socket.result().GetOutputStream().Write(ByteArray{message});
+ ExceptionOr<ByteArray> received_message =
+ answerer_socket.result().GetInputStream().Read(4);
+ EXPECT_FALSE(received_message.ok());
+}
+
+TEST_F(ConnectionFlowTest, TerminateOfferer) {
+ WebRtcMedium webrtc_medium_offerer, webrtc_medium_answerer;
+
+ Future<ByteArray> message_received_future;
+
+ Future<WebRtcSocketWrapper> offerer_socket_future, answerer_socket_future;
+
+ std::unique_ptr<ConnectionFlow> offerer, answerer;
+
+ // Send Ice Candidates immediately when you retrieve them
+ offerer = ConnectionFlow::Create(
+ {.local_ice_candidate_found_cb =
+ [&answerer](const webrtc::IceCandidateInterface* candidate) {
+ std::vector<std::unique_ptr<webrtc::IceCandidateInterface>> vec;
+ vec.push_back(CopyCandidate(candidate));
+ // The callback might be alive while the objects in test are
+ // destroyed.
+ if (answerer)
+ answerer->OnRemoteIceCandidatesReceived(std::move(vec));
+ }},
+ {.data_channel_open_cb =
+ [&offerer_socket_future](WebRtcSocketWrapper socket) {
+ offerer_socket_future.Set(std::move(socket));
+ }},
+ webrtc_medium_offerer);
+ ASSERT_NE(offerer, nullptr);
+ answerer = ConnectionFlow::Create(
+ {.local_ice_candidate_found_cb =
+ [&offerer](const webrtc::IceCandidateInterface* candidate) {
+ std::vector<std::unique_ptr<webrtc::IceCandidateInterface>> vec;
+ vec.push_back(CopyCandidate(candidate));
+ // The callback might be alive while the objects in test are
+ // destroyed.
+ if (offerer)
+ offerer->OnRemoteIceCandidatesReceived(std::move(vec));
+ }},
+ {.data_channel_open_cb =
+ [&answerer_socket_future](WebRtcSocketWrapper wrapper) {
+ answerer_socket_future.Set(std::move(wrapper));
+ }},
+ webrtc_medium_answerer);
+ ASSERT_NE(answerer, nullptr);
+
+ // Create and send offer
+ SessionDescriptionWrapper offer = offerer->CreateOffer();
+ ASSERT_TRUE(offer.IsValid());
+ EXPECT_EQ(offer.GetType(), webrtc::SdpType::kOffer);
+ EXPECT_TRUE(answerer->OnOfferReceived(offer));
+ EXPECT_TRUE(offerer->SetLocalSessionDescription(std::move(offer)));
+
+ // Create and send answer
+ SessionDescriptionWrapper answer = answerer->CreateAnswer();
+ ASSERT_TRUE(answer.IsValid());
+ EXPECT_EQ(answer.GetType(), webrtc::SdpType::kAnswer);
+ EXPECT_TRUE(offerer->OnAnswerReceived(answer));
+ EXPECT_TRUE(answerer->SetLocalSessionDescription(std::move(answer)));
+
+ // Retrieve Data Channels
+ ExceptionOr<WebRtcSocketWrapper> offerer_socket =
+ offerer_socket_future.Get(absl::Seconds(1));
+ EXPECT_TRUE(offerer_socket.ok());
+ ExceptionOr<WebRtcSocketWrapper> answerer_socket =
+ answerer_socket_future.Get(absl::Seconds(1));
+ EXPECT_TRUE(offerer_socket.ok());
+
+ CountDownLatch latch(1);
+ auto pc = offerer->GetPeerConnection();
+ pc->signaling_thread()->PostTask([pc, latch]() mutable {
+ pc->Close();
+ latch.CountDown();
+ });
+ latch.Await();
+
+ // Send message on data channel
+ std::string message = "Test";
+ offerer_socket.result().GetOutputStream().Write(ByteArray{message});
+ ExceptionOr<ByteArray> received_message =
+ answerer_socket.result().GetInputStream().Read(4);
+ EXPECT_FALSE(received_message.ok());
+}
+} // namespace
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/data_channel_listener.h b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/data_channel_listener.h
new file mode 100644
index 00000000000..7464e747dce
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/data_channel_listener.h
@@ -0,0 +1,43 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MEDIUMS_WEBRTC_DATA_CHANNEL_LISTENER_H_
+#define CORE_INTERNAL_MEDIUMS_WEBRTC_DATA_CHANNEL_LISTENER_H_
+
+#include "connections/implementation/mediums/webrtc_socket.h"
+#include "connections/listeners.h"
+#include "internal/platform/byte_array.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+// Callbacks from the data channel.
+struct DataChannelListener {
+ // Called when the data channel is open and the socket wraper is ready to
+ // read and write.
+ std::function<void(WebRtcSocketWrapper)> data_channel_open_cb =
+ DefaultCallback<WebRtcSocketWrapper>();
+
+ // Called when the data channel is closed.
+ std::function<void()> data_channel_closed_cb = DefaultCallback<>();
+};
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MEDIUMS_WEBRTC_DATA_CHANNEL_LISTENER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/local_ice_candidate_listener.h b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/local_ice_candidate_listener.h
new file mode 100644
index 00000000000..34fefc1e024
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/local_ice_candidate_listener.h
@@ -0,0 +1,39 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MEDIUMS_WEBRTC_LOCAL_ICE_CANDIDATE_LISTENER_H_
+#define CORE_INTERNAL_MEDIUMS_WEBRTC_LOCAL_ICE_CANDIDATE_LISTENER_H_
+
+#include "connections/listeners.h"
+#include "webrtc/api/peer_connection_interface.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+// Callbacks from local ice candidate collection.
+struct LocalIceCandidateListener {
+ // Called when a new local ice candidate has been found.
+ std::function<void(const webrtc::IceCandidateInterface*)>
+ local_ice_candidate_found_cb = location::nearby::DefaultCallback<
+ const webrtc::IceCandidateInterface*>();
+};
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MEDIUMS_WEBRTC_LOCAL_ICE_CANDIDATE_LISTENER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/session_description_wrapper.h b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/session_description_wrapper.h
index dd594917348..dd594917348 100644
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/session_description_wrapper.h
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/session_description_wrapper.h
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/signaling_frames.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/signaling_frames.cc
new file mode 100644
index 00000000000..c3498eea2a8
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/signaling_frames.cc
@@ -0,0 +1,134 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/webrtc/signaling_frames.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+namespace webrtc_frames {
+using WebRtcSignalingFrame = location::nearby::mediums::WebRtcSignalingFrame;
+
+namespace {
+
+ByteArray FrameToByteArray(const WebRtcSignalingFrame& signaling_frame) {
+ std::string message;
+ signaling_frame.SerializeToString(&message);
+ return ByteArray(message.c_str(), message.size());
+}
+
+void SetSenderId(const WebrtcPeerId& sender_id, WebRtcSignalingFrame& frame) {
+ frame.mutable_sender_id()->set_id(sender_id.GetId());
+}
+
+std::unique_ptr<webrtc::IceCandidateInterface> DecodeIceCandidate(
+ location::nearby::mediums::IceCandidate ice_candidate_proto) {
+ webrtc::SdpParseError error;
+ return std::unique_ptr<webrtc::IceCandidateInterface>(
+ webrtc::CreateIceCandidate(ice_candidate_proto.sdp_mid(),
+ ice_candidate_proto.sdp_m_line_index(),
+ ice_candidate_proto.sdp(), &error));
+}
+
+} // namespace
+
+ByteArray EncodeReadyForSignalingPoke(const WebrtcPeerId& sender_id) {
+ WebRtcSignalingFrame signaling_frame;
+ signaling_frame.set_type(WebRtcSignalingFrame::READY_FOR_SIGNALING_POKE_TYPE);
+ SetSenderId(sender_id, signaling_frame);
+ signaling_frame.set_allocated_ready_for_signaling_poke(
+ new location::nearby::mediums::ReadyForSignalingPoke());
+ return FrameToByteArray(std::move(signaling_frame));
+}
+
+ByteArray EncodeOffer(const WebrtcPeerId& sender_id,
+ const webrtc::SessionDescriptionInterface& offer) {
+ WebRtcSignalingFrame signaling_frame;
+ signaling_frame.set_type(WebRtcSignalingFrame::OFFER_TYPE);
+ SetSenderId(sender_id, signaling_frame);
+ std::string offer_str;
+ offer.ToString(&offer_str);
+ signaling_frame.mutable_offer()
+ ->mutable_session_description()
+ ->set_description(offer_str);
+ return FrameToByteArray(std::move(signaling_frame));
+}
+
+ByteArray EncodeAnswer(const WebrtcPeerId& sender_id,
+ const webrtc::SessionDescriptionInterface& answer) {
+ WebRtcSignalingFrame signaling_frame;
+ signaling_frame.set_type(WebRtcSignalingFrame::ANSWER_TYPE);
+ SetSenderId(sender_id, signaling_frame);
+ std::string answer_str;
+ answer.ToString(&answer_str);
+ signaling_frame.mutable_answer()
+ ->mutable_session_description()
+ ->set_description(answer_str);
+ return FrameToByteArray(std::move(signaling_frame));
+}
+
+ByteArray EncodeIceCandidates(
+ const WebrtcPeerId& sender_id,
+ const std::vector<location::nearby::mediums::IceCandidate>&
+ ice_candidates) {
+ WebRtcSignalingFrame signaling_frame;
+ signaling_frame.set_type(WebRtcSignalingFrame::ICE_CANDIDATES_TYPE);
+ SetSenderId(sender_id, signaling_frame);
+ for (const auto& ice_candidate : ice_candidates) {
+ *signaling_frame.mutable_ice_candidates()->add_ice_candidates() =
+ ice_candidate;
+ }
+ return FrameToByteArray(std::move(signaling_frame));
+}
+
+std::unique_ptr<webrtc::SessionDescriptionInterface> DecodeOffer(
+ const WebRtcSignalingFrame& frame) {
+ return webrtc::CreateSessionDescription(
+ webrtc::SdpType::kOffer,
+ frame.offer().session_description().description());
+}
+
+std::unique_ptr<webrtc::SessionDescriptionInterface> DecodeAnswer(
+ const WebRtcSignalingFrame& frame) {
+ return webrtc::CreateSessionDescription(
+ webrtc::SdpType::kAnswer,
+ frame.answer().session_description().description());
+}
+
+std::vector<std::unique_ptr<webrtc::IceCandidateInterface>> DecodeIceCandidates(
+ const WebRtcSignalingFrame& frame) {
+ std::vector<std::unique_ptr<webrtc::IceCandidateInterface>> ice_candidates;
+ for (const auto& candidate : frame.ice_candidates().ice_candidates()) {
+ ice_candidates.push_back(DecodeIceCandidate(candidate));
+ }
+ return ice_candidates;
+}
+
+location::nearby::mediums::IceCandidate EncodeIceCandidate(
+ const webrtc::IceCandidateInterface& ice_candidate) {
+ std::string sdp;
+ ice_candidate.ToString(&sdp);
+ location::nearby::mediums::IceCandidate ice_candidate_proto;
+ ice_candidate_proto.set_sdp(sdp);
+ ice_candidate_proto.set_sdp_mid(ice_candidate.sdp_mid());
+ ice_candidate_proto.set_sdp_m_line_index(ice_candidate.sdp_mline_index());
+ return ice_candidate_proto;
+}
+
+} // namespace webrtc_frames
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/signaling_frames.h b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/signaling_frames.h
new file mode 100644
index 00000000000..89999b8a829
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/signaling_frames.h
@@ -0,0 +1,58 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MEDIUMS_WEBRTC_SIGNALING_FRAMES_H_
+#define CORE_INTERNAL_MEDIUMS_WEBRTC_SIGNALING_FRAMES_H_
+
+#include <vector>
+
+#include "connections/implementation/mediums/webrtc_peer_id.h"
+#include "internal/platform/byte_array.h"
+#include "proto/mediums/web_rtc_signaling_frames.pb.h"
+#include "webrtc/api/peer_connection_interface.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+namespace webrtc_frames {
+
+ByteArray EncodeReadyForSignalingPoke(const WebrtcPeerId& sender_id);
+
+ByteArray EncodeOffer(const WebrtcPeerId& sender_id,
+ const webrtc::SessionDescriptionInterface& offer);
+ByteArray EncodeAnswer(const WebrtcPeerId& sender_id,
+ const webrtc::SessionDescriptionInterface& answer);
+
+ByteArray EncodeIceCandidates(
+ const WebrtcPeerId& sender_id,
+ const std::vector<location::nearby::mediums::IceCandidate>& ice_candidates);
+location::nearby::mediums::IceCandidate EncodeIceCandidate(
+ const webrtc::IceCandidateInterface& ice_candidate);
+
+std::unique_ptr<webrtc::SessionDescriptionInterface> DecodeOffer(
+ const location::nearby::mediums::WebRtcSignalingFrame& frame);
+std::unique_ptr<webrtc::SessionDescriptionInterface> DecodeAnswer(
+ const location::nearby::mediums::WebRtcSignalingFrame& frame);
+
+std::vector<std::unique_ptr<webrtc::IceCandidateInterface>> DecodeIceCandidates(
+ const location::nearby::mediums::WebRtcSignalingFrame& frame);
+
+} // namespace webrtc_frames
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MEDIUMS_WEBRTC_SIGNALING_FRAMES_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/signaling_frames_test.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/signaling_frames_test.cc
new file mode 100644
index 00000000000..8c74d457e3a
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/signaling_frames_test.cc
@@ -0,0 +1,197 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/webrtc/signaling_frames.h"
+
+#include <memory>
+
+#include "google/protobuf/text_format.h"
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "connections/implementation/mediums/webrtc_peer_id.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+namespace webrtc_frames {
+
+namespace {
+
+const char kSampleSdp[] =
+ "v=0\r\no=- 7859371131 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 "
+ "0\r\na=msid-semantic: WMS\r\n";
+
+const char kIceCandidateSdp1[] =
+ "a=candidate:1 1 UDP 2130706431 10.0.1.1 8998 typ host";
+const char kIceCandidateSdp2[] =
+ "a=candidate:2 1 UDP 1694498815 192.0.2.3 45664 typ srflx raddr";
+
+const char kIceSdpMid[] = "data";
+const int kIceSdpMLineIndex = 0;
+
+const char kOfferProto[] = R"(
+ sender_id { id: "abc" }
+ type: OFFER_TYPE
+ offer {
+ session_description {
+ description: "v=0\r\no=- 7859371131 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=msid-semantic: WMS\r\n"
+ }
+ }
+ )";
+
+const char kAnswerProto[] = R"(
+ sender_id { id: "abc" }
+ type: ANSWER_TYPE
+ answer {
+ session_description {
+ description: "v=0\r\no=- 7859371131 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=msid-semantic: WMS\r\n"
+ }
+ }
+ )";
+
+const char kIceCandidatesProto[] = R"(
+ sender_id { id: "abc" }
+ type: ICE_CANDIDATES_TYPE
+ ice_candidates {
+ ice_candidates {
+ sdp: "candidate:1 1 udp 2130706431 10.0.1.1 8998 typ host generation 0"
+ sdp_mid: "data"
+ sdp_m_line_index: 0
+ }
+ ice_candidates {
+ sdp: "candidate:2 1 udp 1694498815 192.0.2.3 45664 typ srflx generation 0"
+ sdp_mid: "data"
+ sdp_m_line_index: 0
+ }
+ }
+ )";
+} // namespace
+
+TEST(SignalingFramesTest, SignalingPoke) {
+ WebrtcPeerId sender_id("abc");
+ ByteArray encoded_poke = EncodeReadyForSignalingPoke(sender_id);
+
+ location::nearby::mediums::WebRtcSignalingFrame frame;
+ frame.ParseFromString(std::string(encoded_poke.data(), encoded_poke.size()));
+
+ EXPECT_THAT(frame, protobuf_matchers::EqualsProto(R"pb(
+ sender_id { id: "abc" }
+ type: READY_FOR_SIGNALING_POKE_TYPE
+ ready_for_signaling_poke {}
+ )pb"));
+}
+
+TEST(SignalingFramesTest, EncodeValidOffer) {
+ WebrtcPeerId sender_id("abc");
+ std::unique_ptr<webrtc::SessionDescriptionInterface> offer =
+ webrtc::CreateSessionDescription(webrtc::SdpType::kOffer, kSampleSdp);
+ ByteArray encoded_offer = EncodeOffer(sender_id, *offer);
+
+ location::nearby::mediums::WebRtcSignalingFrame frame;
+ frame.ParseFromString(
+ std::string(encoded_offer.data(), encoded_offer.size()));
+
+ EXPECT_THAT(frame, protobuf_matchers::EqualsProto(kOfferProto));
+}
+
+TEST(SignaingFramesTest, DecodeValidOffer) {
+ location::nearby::mediums::WebRtcSignalingFrame frame;
+ proto2::TextFormat::ParseFromString(kOfferProto, &frame);
+ std::unique_ptr<webrtc::SessionDescriptionInterface> decoded_offer =
+ DecodeOffer(frame);
+
+ EXPECT_EQ(webrtc::SdpType::kOffer, decoded_offer->GetType());
+ std::string description;
+ decoded_offer->ToString(&description);
+ EXPECT_EQ(kSampleSdp, description);
+}
+
+TEST(SignalingFramesTest, EncodeValidAnswer) {
+ WebrtcPeerId sender_id("abc");
+ std::unique_ptr<webrtc::SessionDescriptionInterface> answer(
+ webrtc::CreateSessionDescription(webrtc::SdpType::kAnswer, kSampleSdp));
+ ByteArray encoded_answer = EncodeAnswer(sender_id, *answer);
+
+ location::nearby::mediums::WebRtcSignalingFrame frame;
+ frame.ParseFromString(
+ std::string(encoded_answer.data(), encoded_answer.size()));
+
+ EXPECT_THAT(frame, protobuf_matchers::EqualsProto(kAnswerProto));
+}
+
+TEST(SignalingFramesTest, DecodeValidAnswer) {
+ location::nearby::mediums::WebRtcSignalingFrame frame;
+ proto2::TextFormat::ParseFromString(kAnswerProto, &frame);
+ std::unique_ptr<webrtc::SessionDescriptionInterface> decoded_answer =
+ DecodeAnswer(frame);
+
+ EXPECT_EQ(webrtc::SdpType::kAnswer, decoded_answer->GetType());
+ std::string description;
+ decoded_answer->ToString(&description);
+ EXPECT_EQ(kSampleSdp, description);
+}
+
+TEST(SignalingFramesTest, EncodeValidIceCandidates) {
+ WebrtcPeerId sender_id("abc");
+ webrtc::SdpParseError error;
+
+ std::vector<std::unique_ptr<webrtc::IceCandidateInterface>> ice_candidates;
+ ice_candidates.emplace_back(webrtc::CreateIceCandidate(
+ kIceSdpMid, kIceSdpMLineIndex, kIceCandidateSdp1, &error));
+ ice_candidates.emplace_back(webrtc::CreateIceCandidate(
+ kIceSdpMid, kIceSdpMLineIndex, kIceCandidateSdp2, &error));
+ std::vector<location::nearby::mediums::IceCandidate> encoded_candidates_vec;
+ for (const auto& ice_candidate : ice_candidates) {
+ encoded_candidates_vec.push_back(EncodeIceCandidate(*ice_candidate));
+ }
+ ByteArray encoded_candidates =
+ EncodeIceCandidates(sender_id, encoded_candidates_vec);
+
+ location::nearby::mediums::WebRtcSignalingFrame frame;
+ frame.ParseFromString(
+ std::string(encoded_candidates.data(), encoded_candidates.size()));
+
+ EXPECT_THAT(frame, protobuf_matchers::EqualsProto(kIceCandidatesProto));
+}
+
+TEST(SignalingFramesTest, DecodeValidIceCandidates) {
+ webrtc::SdpParseError error;
+ std::vector<std::unique_ptr<webrtc::IceCandidateInterface>> ice_candidates;
+ ice_candidates.emplace_back(webrtc::CreateIceCandidate(
+ kIceSdpMid, kIceSdpMLineIndex, kIceCandidateSdp1, &error));
+ ice_candidates.emplace_back(webrtc::CreateIceCandidate(
+ kIceSdpMid, kIceSdpMLineIndex, kIceCandidateSdp2, &error));
+
+ location::nearby::mediums::WebRtcSignalingFrame frame;
+ proto2::TextFormat::ParseFromString(kIceCandidatesProto, &frame);
+ std::vector<std::unique_ptr<webrtc::IceCandidateInterface>>
+ decoded_candidates = DecodeIceCandidates(frame);
+
+ ASSERT_EQ(2u, decoded_candidates.size());
+ for (int i = 0; i < static_cast<int>(decoded_candidates.size()); i++) {
+ EXPECT_TRUE(ice_candidates[i]->candidate().IsEquivalent(
+ decoded_candidates[i]->candidate()));
+ EXPECT_EQ(ice_candidates[i]->sdp_mid(), decoded_candidates[i]->sdp_mid());
+ EXPECT_EQ(ice_candidates[i]->sdp_mline_index(),
+ decoded_candidates[i]->sdp_mline_index());
+ }
+}
+
+} // namespace webrtc_frames
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/webrtc_socket_impl.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/webrtc_socket_impl.cc
new file mode 100644
index 00000000000..e5d86e788d6
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/webrtc_socket_impl.cc
@@ -0,0 +1,190 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/webrtc/webrtc_socket_impl.h"
+
+#include "internal/platform/logging.h"
+#include "internal/platform/mutex_lock.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+// OutputStreamImpl
+Exception WebRtcSocket::OutputStreamImpl::Write(const ByteArray& data) {
+ if (data.size() > kMaxDataSize) {
+ NEARBY_LOG(WARNING, "Sending data larger than 1MB");
+ return {Exception::kIo};
+ }
+
+ socket_->BlockUntilSufficientSpaceInBuffer(data.size());
+
+ if (socket_->IsClosed()) {
+ NEARBY_LOG(WARNING, "Tried sending message while socket is closed");
+ return {Exception::kIo};
+ }
+
+ if (!socket_->SendMessage(data)) {
+ NEARBY_LOG(INFO, "Unable to write data to socket.");
+ return {Exception::kIo};
+ }
+ return {Exception::kSuccess};
+}
+
+Exception WebRtcSocket::OutputStreamImpl::Flush() {
+ // Java implementation is empty.
+ return {Exception::kSuccess};
+}
+
+Exception WebRtcSocket::OutputStreamImpl::Close() {
+ socket_->Close();
+ return {Exception::kSuccess};
+}
+
+// WebRtcSocket
+WebRtcSocket::WebRtcSocket(
+ const std::string& name,
+ rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel)
+ : name_(name), data_channel_(std::move(data_channel)) {
+ NEARBY_LOGS(INFO) << "WebRtcSocket::WebRtcSocket(" << name_
+ << ") this: " << this;
+ data_channel_->RegisterObserver(this);
+}
+
+WebRtcSocket::~WebRtcSocket() {
+ NEARBY_LOGS(INFO) << "WebRtcSocket::~WebRtcSocket(" << name_
+ << ") this: " << this;
+ Close();
+ NEARBY_LOGS(INFO) << "WebRtcSocket::~WebRtcSocket(" << name_
+ << ") this: " << this << " done";
+}
+
+InputStream& WebRtcSocket::GetInputStream() { return pipe_.GetInputStream(); }
+
+OutputStream& WebRtcSocket::GetOutputStream() { return output_stream_; }
+
+void WebRtcSocket::Close() {
+ NEARBY_LOGS(INFO) << "WebRtcSocket::Close(" << name_ << ") this: " << this;
+ if (closed_.Set(true)) return;
+
+ ClosePipe();
+ // NOTE: This call blocks and triggers a state change on the siginaling thread
+ // to 'closing' but does not block until 'closed' is sent so the data channel
+ // is not fully closed when this call is done.
+ data_channel_->Close();
+ NEARBY_LOGS(INFO) << "WebRtcSocket::Close(" << name_ << ") this: " << this
+ << " done";
+}
+
+void WebRtcSocket::OnStateChange() {
+ // Running on the signaling thread right now.
+ NEARBY_LOGS(ERROR)
+ << "WebRtcSocket::OnStateChange() webrtc data channel state: "
+ << webrtc::DataChannelInterface::DataStateString(data_channel_->state());
+ switch (data_channel_->state()) {
+ case webrtc::DataChannelInterface::DataState::kConnecting:
+ break;
+ case webrtc::DataChannelInterface::DataState::kOpen:
+ // We implicitly depend on the |socket_listener_| to offload from
+ // the signaling thread so it does not get blocked.
+ socket_listener_.socket_ready_cb(this);
+ break;
+ case webrtc::DataChannelInterface::DataState::kClosing:
+ break;
+ case webrtc::DataChannelInterface::DataState::kClosed:
+ NEARBY_LOG(
+ ERROR,
+ "WebRtcSocket::OnStateChange() unregistering data channel observer.");
+ data_channel_->UnregisterObserver();
+ // This will trigger a destruction of the owning connection flow
+ // We implicitly depend on the |socket_listener_| to offload from
+ // the signaling thread so it does not get blocked.
+ socket_listener_.socket_closed_cb(this);
+
+ if (!closed_.Set(true)) {
+ OffloadFromSignalingThread([this] { ClosePipe(); });
+ }
+ break;
+ }
+}
+void WebRtcSocket::OnMessage(const webrtc::DataBuffer& buffer) {
+ // This is a data channel callback on the signaling thread, lets off load so
+ // we don't block signaling.
+ OffloadFromSignalingThread(
+ [this, buffer = ByteArray(buffer.data.data<char>(), buffer.size())] {
+ if (!pipe_.GetOutputStream().Write(buffer).Ok()) {
+ Close();
+ return;
+ }
+
+ if (!pipe_.GetOutputStream().Flush().Ok()) {
+ Close();
+ }
+ });
+}
+
+void WebRtcSocket::OnBufferedAmountChange(uint64_t sent_data_size) {
+ // This is a data channel callback on the signaling thread, lets off load so
+ // we don't block signaling.
+ OffloadFromSignalingThread([this] { WakeUpWriter(); });
+}
+
+bool WebRtcSocket::SendMessage(const ByteArray& data) {
+ return data_channel_->Send(
+ webrtc::DataBuffer(std::string(data.data(), data.size())));
+}
+
+bool WebRtcSocket::IsClosed() { return closed_.Get(); }
+
+void WebRtcSocket::ClosePipe() {
+ NEARBY_LOGS(INFO) << "WebRtcSocket::ClosePipe(" << name_
+ << ") this: " << this;
+ // This is thread-safe to close these sockets even if a read or write is in
+ // process on another thread, Close will wait for the exclusive mutex before
+ // setting state.
+ pipe_.GetInputStream().Close();
+ pipe_.GetOutputStream().Close();
+ WakeUpWriter();
+ NEARBY_LOGS(INFO) << "WebRtcSocket::ClosePipe(" << name_ << ") this: " << this
+ << " done";
+}
+
+// Must not be called on signalling thread.
+void WebRtcSocket::WakeUpWriter() {
+ MutexLock lock(&backpressure_mutex_);
+ buffer_variable_.Notify();
+}
+
+void WebRtcSocket::SetSocketListener(SocketListener&& listener) {
+ socket_listener_ = std::move(listener);
+}
+
+void WebRtcSocket::BlockUntilSufficientSpaceInBuffer(int length) {
+ MutexLock lock(&backpressure_mutex_);
+ while (!IsClosed() &&
+ (data_channel_->buffered_amount() + length > kMaxDataSize)) {
+ // TODO(himanshujaju): Add wait with timeout.
+ buffer_variable_.Wait();
+ }
+}
+
+void WebRtcSocket::OffloadFromSignalingThread(Runnable runnable) {
+ single_thread_executor_.Execute(std::move(runnable));
+}
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/webrtc_socket_impl.h b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/webrtc_socket_impl.h
new file mode 100644
index 00000000000..19c9efbe87f
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/webrtc_socket_impl.h
@@ -0,0 +1,123 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MEDIUMS_WEBRTC_WEBRTC_SOCKET_IMPL_H_
+#define CORE_INTERNAL_MEDIUMS_WEBRTC_WEBRTC_SOCKET_IMPL_H_
+
+#include <memory>
+
+#include "connections/listeners.h"
+#include "internal/platform/input_stream.h"
+#include "internal/platform/output_stream.h"
+#include "internal/platform/socket.h"
+#include "internal/platform/atomic_boolean.h"
+#include "internal/platform/condition_variable.h"
+#include "internal/platform/mutex.h"
+#include "internal/platform/pipe.h"
+#include "internal/platform/single_thread_executor.h"
+#include "webrtc/api/data_channel_interface.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+// Maximum data size: 1 MB
+constexpr int kMaxDataSize = 1 * 1024 * 1024;
+
+// Defines the Socket implementation specific to WebRTC, which uses the WebRTC
+// data channel to send and receive messages.
+//
+// Messages are buffered here to prevent the data channel from overflowing,
+// which could lead to data loss.
+class WebRtcSocket : public Socket, public webrtc::DataChannelObserver {
+ public:
+ WebRtcSocket(const std::string& name,
+ rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel);
+ ~WebRtcSocket() override;
+
+ WebRtcSocket(const WebRtcSocket& other) = delete;
+ WebRtcSocket& operator=(const WebRtcSocket& other) = delete;
+
+ // Overrides for location::nearby::Socket:
+ InputStream& GetInputStream() override;
+ OutputStream& GetOutputStream() override;
+ void Close() override;
+
+ // webrtc::DataChannelObserver:
+ void OnStateChange() override;
+ void OnMessage(const webrtc::DataBuffer& buffer) override;
+ void OnBufferedAmountChange(uint64_t sent_data_size) override;
+
+ // Listener class the gets called when the socket is ready or closed
+ struct SocketListener {
+ std::function<void(WebRtcSocket*)> socket_ready_cb =
+ DefaultCallback<WebRtcSocket*>();
+ std::function<void(WebRtcSocket*)> socket_closed_cb =
+ DefaultCallback<WebRtcSocket*>();
+ };
+
+ void SetSocketListener(SocketListener&& listener);
+
+ private:
+ class OutputStreamImpl : public OutputStream {
+ public:
+ explicit OutputStreamImpl(WebRtcSocket* const socket) : socket_(socket) {}
+ ~OutputStreamImpl() override = default;
+
+ OutputStreamImpl(const OutputStreamImpl& other) = delete;
+ OutputStreamImpl& operator=(const OutputStreamImpl& other) = delete;
+
+ // OutputStream:
+ Exception Write(const ByteArray& data) override;
+ Exception Flush() override;
+ Exception Close() override;
+
+ private:
+ // |this| OutputStreamImpl is owned by |socket_|.
+ WebRtcSocket* const socket_;
+ };
+
+ void WakeUpWriter();
+ bool IsClosed();
+ void ClosePipe();
+ bool SendMessage(const ByteArray& data);
+ void BlockUntilSufficientSpaceInBuffer(int length);
+ void OffloadFromSignalingThread(Runnable runnable);
+
+ std::string name_;
+ rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel_;
+
+ Pipe pipe_;
+
+ OutputStreamImpl output_stream_{this};
+
+ AtomicBoolean closed_{false};
+
+ SocketListener socket_listener_;
+
+ mutable Mutex backpressure_mutex_;
+ ConditionVariable buffer_variable_{&backpressure_mutex_};
+
+ // This should be destroyed first to ensure any remaining tasks flushed on
+ // shutdown get run while the other members are still alive.
+ SingleThreadExecutor single_thread_executor_;
+};
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MEDIUMS_WEBRTC_WEBRTC_SOCKET_IMPL_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/webrtc_socket_impl_test.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/webrtc_socket_impl_test.cc
new file mode 100644
index 00000000000..fdb8137f629
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc/webrtc_socket_impl_test.cc
@@ -0,0 +1,235 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/webrtc/webrtc_socket_impl.h"
+
+#include <memory>
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "internal/platform/byte_array.h"
+#include "webrtc/api/data_channel_interface.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+namespace {
+
+// using TestPlatform = platform::ImplementationPlatform;
+
+const char kSocketName[] = "TestSocket";
+
+class MockDataChannel
+ : public rtc::RefCountedObject<webrtc::DataChannelInterface> {
+ public:
+ MOCK_METHOD(void, RegisterObserver, (webrtc::DataChannelObserver*));
+ MOCK_METHOD(void, UnregisterObserver, ());
+
+ MOCK_METHOD(std::string, label, (), (const));
+
+ MOCK_METHOD(bool, reliable, (), (const));
+ MOCK_METHOD(int, id, (), (const));
+ MOCK_METHOD(DataState, state, (), (const));
+ MOCK_METHOD(uint32_t, messages_sent, (), (const));
+ MOCK_METHOD(uint64_t, bytes_sent, (), (const));
+ MOCK_METHOD(uint32_t, messages_received, (), (const));
+ MOCK_METHOD(uint64_t, bytes_received, (), (const));
+
+ MOCK_METHOD(uint64_t, buffered_amount, (), (const));
+
+ MOCK_METHOD(void, Close, ());
+
+ MOCK_METHOD(bool, Send, (const webrtc::DataBuffer&));
+};
+
+} // namespace
+
+TEST(WebRtcSocketTest, ReadFromSocket) {
+ const char* message = "message";
+ rtc::scoped_refptr<MockDataChannel> mock_data_channel(new MockDataChannel());
+ WebRtcSocket webrtc_socket(kSocketName, mock_data_channel);
+
+ webrtc_socket.OnMessage(webrtc::DataBuffer{message});
+ ExceptionOr<ByteArray> result = webrtc_socket.GetInputStream().Read(7);
+ EXPECT_TRUE(result.ok());
+ EXPECT_EQ(result.result(), ByteArray{message});
+}
+
+TEST(WebRtcSocketTest, ReadMultipleMessages) {
+ rtc::scoped_refptr<MockDataChannel> mock_data_channel(new MockDataChannel());
+ WebRtcSocket webrtc_socket(kSocketName, mock_data_channel);
+
+ webrtc_socket.OnMessage(webrtc::DataBuffer{"Me"});
+ webrtc_socket.OnMessage(webrtc::DataBuffer{"ssa"});
+ webrtc_socket.OnMessage(webrtc::DataBuffer{"ge"});
+
+ ExceptionOr<ByteArray> result;
+
+ // This behaviour is different from the Java code
+ result = webrtc_socket.GetInputStream().Read(7);
+ EXPECT_TRUE(result.ok());
+ EXPECT_EQ(result.result(), ByteArray{"Me"});
+
+ result = webrtc_socket.GetInputStream().Read(7);
+ EXPECT_TRUE(result.ok());
+ EXPECT_EQ(result.result(), ByteArray{"ssa"});
+
+ result = webrtc_socket.GetInputStream().Read(7);
+ EXPECT_TRUE(result.ok());
+ EXPECT_EQ(result.result(), ByteArray{"ge"});
+}
+
+TEST(WebRtcSocketTest, WriteToSocket) {
+ const ByteArray kMessage{"Message"};
+ rtc::scoped_refptr<MockDataChannel> mock_data_channel(new MockDataChannel());
+ WebRtcSocket webrtc_socket(kSocketName, mock_data_channel);
+
+ EXPECT_CALL(*mock_data_channel, Send(testing::_))
+ .WillRepeatedly(testing::Return(true));
+ EXPECT_TRUE(webrtc_socket.GetOutputStream().Write(kMessage).Ok());
+}
+
+TEST(WebRtcSocketTest, SendDataBiggerThanMax) {
+ const ByteArray kMessage{kMaxDataSize + 1};
+ rtc::scoped_refptr<MockDataChannel> mock_data_channel(new MockDataChannel());
+ WebRtcSocket webrtc_socket(kSocketName, mock_data_channel);
+
+ EXPECT_CALL(*mock_data_channel, Send(testing::_)).Times(0);
+ EXPECT_EQ(webrtc_socket.GetOutputStream().Write(kMessage),
+ Exception{Exception::kIo});
+}
+
+TEST(WebRtcSocketTest, WriteToDataChannelFails) {
+ ByteArray kMessage{"Message"};
+ rtc::scoped_refptr<MockDataChannel> mock_data_channel(new MockDataChannel());
+ WebRtcSocket webrtc_socket(kSocketName, mock_data_channel);
+
+ ON_CALL(*mock_data_channel, Send(testing::_))
+ .WillByDefault(testing::Return(false));
+ EXPECT_EQ(webrtc_socket.GetOutputStream().Write(kMessage),
+ Exception{Exception::kIo});
+}
+
+TEST(WebRtcSocketTest, Close) {
+ rtc::scoped_refptr<MockDataChannel> mock_data_channel(new MockDataChannel());
+ WebRtcSocket webrtc_socket(kSocketName, mock_data_channel);
+
+ EXPECT_CALL(*mock_data_channel, Close());
+
+ int socket_closed_cb_called = 0;
+
+ webrtc_socket.SetSocketListener(
+ {.socket_closed_cb = [&](WebRtcSocket* socket) {
+ socket_closed_cb_called++;
+ }});
+ webrtc_socket.Close();
+
+ // We have to fake the close event to get the callback to run.
+ ON_CALL(*mock_data_channel, state())
+ .WillByDefault(
+ testing::Return(webrtc::DataChannelInterface::DataState::kClosed));
+
+ webrtc_socket.OnStateChange();
+
+ EXPECT_EQ(socket_closed_cb_called, 1);
+}
+
+TEST(WebRtcSocketTest, WriteOnClosedChannel) {
+ ByteArray kMessage{"Message"};
+ rtc::scoped_refptr<MockDataChannel> mock_data_channel(new MockDataChannel());
+ WebRtcSocket webrtc_socket(kSocketName, mock_data_channel);
+ webrtc_socket.Close();
+
+ EXPECT_CALL(*mock_data_channel, Send(testing::_)).Times(0);
+ EXPECT_EQ(webrtc_socket.GetOutputStream().Write(kMessage),
+ Exception{Exception::kIo});
+}
+
+TEST(WebRtcSocketTest, ReadFromClosedChannel) {
+ ByteArray kMessage{"Message"};
+ rtc::scoped_refptr<MockDataChannel> mock_data_channel(new MockDataChannel());
+ WebRtcSocket webrtc_socket(kSocketName, mock_data_channel);
+ ON_CALL(*mock_data_channel, Send(testing::_))
+ .WillByDefault(testing::Return(true));
+
+ webrtc_socket.GetOutputStream().Write(kMessage);
+ webrtc_socket.Close();
+
+ EXPECT_EQ(webrtc_socket.GetInputStream().Read(7).exception(), Exception::kIo);
+}
+
+TEST(WebRtcSocketTest, DataChannelCloseEventCleansUp) {
+ rtc::scoped_refptr<MockDataChannel> mock_data_channel(new MockDataChannel());
+ WebRtcSocket webrtc_socket(kSocketName, mock_data_channel);
+
+ ON_CALL(*mock_data_channel, state())
+ .WillByDefault(
+ testing::Return(webrtc::DataChannelInterface::DataState::kClosed));
+
+ webrtc_socket.OnStateChange();
+
+ EXPECT_EQ(webrtc_socket.GetInputStream().Read(7).exception(), Exception::kIo);
+
+ // Calling Close again should be safe even if the channel is already shut
+ // down.
+ webrtc_socket.Close();
+}
+
+TEST(WebRtcSocketTest, OpenStateTriggersCallback) {
+ rtc::scoped_refptr<MockDataChannel> mock_data_channel(new MockDataChannel());
+ WebRtcSocket webrtc_socket(kSocketName, mock_data_channel);
+
+ int socket_ready_cb_called = 0;
+
+ webrtc_socket.SetSocketListener(
+ {.socket_ready_cb = [&](WebRtcSocket* socket) {
+ socket_ready_cb_called++;
+ }});
+
+ ON_CALL(*mock_data_channel, state())
+ .WillByDefault(
+ testing::Return(webrtc::DataChannelInterface::DataState::kOpen));
+
+ webrtc_socket.OnStateChange();
+
+ EXPECT_EQ(socket_ready_cb_called, 1);
+}
+
+TEST(WebRtcSocketTest, CloseStateTriggersCallback) {
+ rtc::scoped_refptr<MockDataChannel> mock_data_channel(new MockDataChannel());
+ WebRtcSocket webrtc_socket(kSocketName, mock_data_channel);
+
+ int socket_closed_cb_called = 0;
+
+ webrtc_socket.SetSocketListener(
+ {.socket_closed_cb = [&](WebRtcSocket* socket) {
+ socket_closed_cb_called++;
+ }});
+
+ ON_CALL(*mock_data_channel, state())
+ .WillByDefault(
+ testing::Return(webrtc::DataChannelInterface::DataState::kClosed));
+
+ webrtc_socket.OnStateChange();
+
+ EXPECT_EQ(socket_closed_cb_called, 1);
+}
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_peer_id.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_peer_id.cc
new file mode 100644
index 00000000000..c74978b8256
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_peer_id.cc
@@ -0,0 +1,54 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/webrtc_peer_id.h"
+
+#include <sstream>
+
+#include "absl/strings/ascii.h"
+#include "absl/strings/escaping.h"
+#include "connections/implementation/mediums/utils.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+namespace {
+constexpr int kPeerIdLength = 64;
+
+std::string BytesToStringUppercase(const ByteArray& bytes) {
+ std::string hex_string(
+ absl::BytesToHexString(std::string(bytes.data(), bytes.size())));
+ absl::AsciiStrToUpper(&hex_string);
+ return hex_string;
+}
+} // namespace
+
+WebrtcPeerId WebrtcPeerId::FromRandom() {
+ return FromSeed(Utils::GenerateRandomBytes(kPeerIdLength));
+}
+
+WebrtcPeerId WebrtcPeerId::FromSeed(const ByteArray& seed) {
+ ByteArray full_hash(Utils::Sha256Hash(seed, kPeerIdLength));
+ ByteArray hashed_seed(full_hash.data(), kPeerIdLength / 2);
+ return WebrtcPeerId(BytesToStringUppercase(hashed_seed));
+}
+
+bool WebrtcPeerId::IsValid() const { return !id_.empty(); }
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_peer_id.h b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_peer_id.h
new file mode 100644
index 00000000000..77ac1cc8d8f
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_peer_id.h
@@ -0,0 +1,52 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MEDIUMS_WEBRTC_PEER_ID_H_
+#define CORE_INTERNAL_MEDIUMS_WEBRTC_PEER_ID_H_
+
+#include <memory>
+#include <string>
+
+#include "internal/platform/byte_array.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+// WebrtcPeerId is used as an identifier to exchange SDP messages to establish
+// WebRTC p2p connection. An empty WebrtcPeerId is considered to be invalid.
+class WebrtcPeerId {
+ public:
+ WebrtcPeerId() = default;
+ explicit WebrtcPeerId(const std::string& id) : id_(id) {}
+ ~WebrtcPeerId() = default;
+
+ static WebrtcPeerId FromRandom();
+ static WebrtcPeerId FromSeed(const ByteArray& seed);
+
+ bool IsValid() const;
+
+ const std::string& GetId() const { return id_; }
+
+ private:
+ std::string id_;
+};
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MEDIUMS_WEBRTC_PEER_ID_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_peer_id_test.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_peer_id_test.cc
new file mode 100644
index 00000000000..69345ada3f9
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_peer_id_test.cc
@@ -0,0 +1,57 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/webrtc_peer_id.h"
+
+#include <memory>
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/crypto.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+TEST(WebrtcPeerIdTest, GenerateRandomPeerId) {
+ WebrtcPeerId peer_id = WebrtcPeerId::FromRandom();
+ EXPECT_EQ(64, peer_id.GetId().size());
+}
+
+TEST(WebrtcPeerIdTest, GenerateFromSeed) {
+ // Values calculated by running actual SHA-256 hash on |seed|.
+ std::string seed = "seed";
+ std::string expected_peer_id =
+ "19B25856E1C150CA834CFFC8B59B23ADBD0EC0389E58EB22B3B64768098D002B";
+
+ ByteArray seed_bytes(seed);
+ WebrtcPeerId peer_id = WebrtcPeerId::FromSeed(seed_bytes);
+
+ EXPECT_EQ(64, peer_id.GetId().size());
+ EXPECT_EQ(expected_peer_id, peer_id.GetId());
+}
+
+TEST(WebrtcPeerIdTest, GetId) {
+ const std::string id = "this_is_a_test";
+ WebrtcPeerId peer_id(id);
+ EXPECT_EQ(id, peer_id.GetId());
+}
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_socket.h b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_socket.h
new file mode 100644
index 00000000000..86b0b618923
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_socket.h
@@ -0,0 +1,55 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MEDIUMS_WEBRTC_SOCKET_H_
+#define CORE_INTERNAL_MEDIUMS_WEBRTC_SOCKET_H_
+
+#include <memory>
+
+#include "connections/implementation/mediums/webrtc/webrtc_socket_impl.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+class WebRtcSocketWrapper final {
+ public:
+ WebRtcSocketWrapper() = default;
+ WebRtcSocketWrapper(const WebRtcSocketWrapper&) = default;
+ WebRtcSocketWrapper& operator=(const WebRtcSocketWrapper&) = default;
+ explicit WebRtcSocketWrapper(std::unique_ptr<WebRtcSocket> socket)
+ : impl_(socket.release()) {}
+ ~WebRtcSocketWrapper() = default;
+
+ InputStream& GetInputStream() { return impl_->GetInputStream(); }
+
+ OutputStream& GetOutputStream() { return impl_->GetOutputStream(); }
+
+ void Close() { return impl_->Close(); }
+
+ bool IsValid() const { return impl_ != nullptr; }
+
+ WebRtcSocket& GetImpl() { return *impl_; }
+
+ private:
+ std::shared_ptr<WebRtcSocket> impl_;
+};
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MEDIUMS_WEBRTC_WEBRTC_SOCKET_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_socket_stub.h b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_socket_stub.h
new file mode 100644
index 00000000000..7270a57f558
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_socket_stub.h
@@ -0,0 +1,69 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MEDIUMS_WEBRTC_SOCKET_STUB_H_
+#define CORE_INTERNAL_MEDIUMS_WEBRTC_SOCKET_STUB_H_
+
+#include <memory>
+
+#include "internal/platform/input_stream.h"
+#include "internal/platform/output_stream.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+class FakeInputStream : public InputStream {
+ public:
+ ExceptionOr<ByteArray> Read(std::int64_t size) {
+ return {Exception::kSuccess};
+ }
+ Exception Close() { return {Exception::kSuccess}; }
+};
+
+class FakeOutputStream : public OutputStream {
+ public:
+ Exception Write(const ByteArray& data) override {
+ return {Exception::kSuccess};
+ }
+ Exception Flush() override { return {Exception::kSuccess}; }
+ Exception Close() override { return {Exception::kSuccess}; }
+};
+
+class WebRtcSocketWrapper final {
+ public:
+ WebRtcSocketWrapper() = default;
+ WebRtcSocketWrapper(const WebRtcSocketWrapper&) = default;
+ WebRtcSocketWrapper& operator=(const WebRtcSocketWrapper&) = default;
+ ~WebRtcSocketWrapper() = default;
+
+ InputStream& GetInputStream() { return fake_input_stream_; }
+
+ OutputStream& GetOutputStream() { return fake_output_stream_; }
+
+ void Close() {}
+
+ bool IsValid() const { return false; }
+
+ private:
+ FakeInputStream fake_input_stream_;
+ FakeOutputStream fake_output_stream_;
+};
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MEDIUMS_WEBRTC_SOCKET_STUB_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_stub.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_stub.cc
new file mode 100644
index 00000000000..25cf72fca4c
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_stub.cc
@@ -0,0 +1,61 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/webrtc_stub.h"
+
+#include <functional>
+#include <memory>
+
+#include "connections/implementation/mediums/webrtc_socket_stub.h"
+#include "internal/platform/listeners.h"
+#include "internal/platform/cancelable_alarm.h"
+#include "internal/platform/future.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+WebRtc::WebRtc() = default;
+
+WebRtc::~WebRtc() {}
+
+const std::string WebRtc::GetDefaultCountryCode() { return "US"; }
+
+bool WebRtc::IsAvailable() { return false; }
+
+bool WebRtc::IsAcceptingConnections(const std::string& service_id) {
+ return false;
+}
+
+bool WebRtc::StartAcceptingConnections(const std::string& service_id,
+ const WebrtcPeerId& self_peer_id,
+ const LocationHint& location_hint,
+ AcceptedConnectionCallback callback) {
+ return false;
+}
+
+void WebRtc::StopAcceptingConnections(const std::string& service_id) {}
+
+WebRtcSocketWrapper WebRtc::Connect(const std::string& service_id,
+ const WebrtcPeerId& remote_peer_id,
+ const LocationHint& location_hint,
+ CancellationFlag* cancellation_flag) {
+ return WebRtcSocketWrapper();
+}
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_stub.h b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_stub.h
new file mode 100644
index 00000000000..6e62983b9c5
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_stub.h
@@ -0,0 +1,82 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MEDIUMS_WEBRTC_STUB_H_
+#define CORE_INTERNAL_MEDIUMS_WEBRTC_STUB_H_
+
+#include <cstddef>
+#include <functional>
+#include <memory>
+#include <string>
+
+#include "connections/implementation/proto/offline_wire_formats.pb.h"
+#include "connections/implementation/mediums/webrtc_peer_id.h"
+#include "connections/implementation/mediums/webrtc_socket_stub.h"
+#include "internal/platform/cancellation_flag.h"
+#include "internal/platform/listeners.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+// Callback that is invoked when a new connection is accepted.
+struct AcceptedConnectionCallback {
+ std::function<void(WebRtcSocketWrapper socket)> accepted_cb =
+ DefaultCallback<WebRtcSocketWrapper>();
+};
+// Entry point for connecting a data channel between two devices via WebRtc.
+class WebRtc {
+ public:
+ WebRtc();
+ ~WebRtc();
+
+ // Gets the default two-letter country code associated with current locale.
+ // For example, en_US locale resolves to "US".
+ const std::string GetDefaultCountryCode();
+
+ // Returns if WebRtc is available as a medium for nearby to transport data.
+ // Runs on @MainThread.
+ bool IsAvailable();
+
+ // Returns if the device is accepting connection with specific service id.
+ // Runs on @MainThread.
+ bool IsAcceptingConnections(const std::string& service_id);
+
+ // Prepares the device to accept incoming WebRtc connections. Returns a
+ // boolean value indicating if the device has started accepting connections.
+ // Runs on @MainThread.
+ bool StartAcceptingConnections(const std::string& service_id,
+ const WebrtcPeerId& self_peer_id,
+ const LocationHint& location_hint,
+ AcceptedConnectionCallback callback);
+
+ // Try to stop (accepting) the specific connection with provided service id.
+ // Runs on @MainThread
+ void StopAcceptingConnections(const std::string& service_id);
+
+ // Initiates a WebRtc connection with peer device identified by |peer_id|
+ // with internal retry for maximum attempts of kConnectAttemptsLimit.
+ // Runs on @MainThread.
+ WebRtcSocketWrapper Connect(const std::string& service_id,
+ const WebrtcPeerId& peer_id,
+ const LocationHint& location_hint,
+ CancellationFlag* cancellation_flag);
+};
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MEDIUMS_WEBRTC_STUB_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_test.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_test.cc
new file mode 100644
index 00000000000..373e444edd8
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/webrtc_test.cc
@@ -0,0 +1,406 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/webrtc.h"
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "connections/implementation/mediums/webrtc_socket.h"
+#include "internal/platform/listeners.h"
+#include "internal/platform/medium_environment.h"
+#include "internal/platform/mutex_lock.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace mediums {
+
+namespace {
+
+using FeatureFlags = FeatureFlags::Flags;
+
+constexpr FeatureFlags kTestCases[] = {
+ FeatureFlags{
+ .enable_cancellation_flag = true,
+ },
+ FeatureFlags{
+ .enable_cancellation_flag = false,
+ },
+};
+
+class WebRtcTest : public ::testing::TestWithParam<FeatureFlags> {
+ protected:
+ using MockAcceptedCallback =
+ testing::MockFunction<void(WebRtcSocketWrapper socket)>;
+
+ WebRtcTest() { env_.Stop(); }
+
+ MediumEnvironment& env_{MediumEnvironment::Instance()};
+};
+
+// Tests the flow when the two devices exchange SDP messages and connect to each
+// other but the signaling channel is closed before sending the data.
+TEST_P(WebRtcTest, ConnectBothDevices_ShutdownSignaling_SendData) {
+ env_.Start({.webrtc_enabled = true});
+ FeatureFlags feature_flags = GetParam();
+ env_.SetFeatureFlags(feature_flags);
+ WebRtc receiver, sender;
+ WebRtcSocketWrapper receiver_socket, sender_socket;
+ const WebrtcPeerId self_id("self_id");
+ const std::string service_id("NearbySharing");
+ LocationHint location_hint;
+ Future<bool> connected;
+ ByteArray message("message xyz");
+
+ receiver.StartAcceptingConnections(
+ service_id, self_id, location_hint,
+ {[&receiver_socket, connected](WebRtcSocketWrapper wrapper) mutable {
+ receiver_socket = wrapper;
+ connected.Set(receiver_socket.IsValid());
+ }});
+
+ CancellationFlag flag;
+ sender_socket = sender.Connect(service_id, self_id, location_hint, &flag);
+ EXPECT_TRUE(sender_socket.IsValid());
+
+ ExceptionOr<bool> devices_connected = connected.Get();
+ ASSERT_TRUE(devices_connected.ok());
+ EXPECT_TRUE(devices_connected.result());
+
+ // Only shuts down signaling channel.
+ receiver.StopAcceptingConnections(service_id);
+
+ sender_socket.GetOutputStream().Write(message);
+ ExceptionOr<ByteArray> received_msg =
+ receiver_socket.GetInputStream().Read(/*size=*/32);
+ ASSERT_TRUE(received_msg.ok());
+ EXPECT_EQ(message, received_msg.result());
+ env_.Stop();
+}
+
+TEST_P(WebRtcTest, CanCancelConnect) {
+ env_.Start({.webrtc_enabled = true});
+ FeatureFlags feature_flags = GetParam();
+ env_.SetFeatureFlags(feature_flags);
+ WebRtc receiver, sender;
+ WebRtcSocketWrapper receiver_socket, sender_socket;
+ const WebrtcPeerId self_id("self_id");
+ const std::string service_id("NearbySharing");
+ LocationHint location_hint;
+ Future<bool> connected;
+ ByteArray message("message");
+
+ receiver.StartAcceptingConnections(
+ service_id, self_id, location_hint,
+ {[&receiver_socket, connected](WebRtcSocketWrapper wrapper) mutable {
+ receiver_socket = wrapper;
+ connected.Set(receiver_socket.IsValid());
+ }});
+
+ CancellationFlag flag(true);
+ sender_socket = sender.Connect(service_id, self_id, location_hint, &flag);
+ // If FeatureFlag is disabled, Cancelled is false as no-op.
+ if (!feature_flags.enable_cancellation_flag) {
+ EXPECT_TRUE(sender_socket.IsValid());
+
+ ExceptionOr<bool> devices_connected = connected.Get();
+ ASSERT_TRUE(devices_connected.ok());
+ EXPECT_TRUE(devices_connected.result());
+
+ sender_socket.GetOutputStream().Write(message);
+ ExceptionOr<ByteArray> received_msg =
+ receiver_socket.GetInputStream().Read(/*size=*/32);
+ ASSERT_TRUE(received_msg.ok());
+ EXPECT_EQ(message, received_msg.result());
+
+ receiver_socket.Close();
+ } else {
+ EXPECT_FALSE(sender_socket.IsValid());
+ }
+ env_.Stop();
+}
+
+INSTANTIATE_TEST_SUITE_P(ParametrisedWebRtcTest, WebRtcTest,
+ ::testing::ValuesIn(kTestCases));
+
+// Basic test to check that device is accepting connections when initialized.
+TEST_F(WebRtcTest, NotAcceptingConnections) {
+ env_.Start({.webrtc_enabled = true});
+ WebRtc webrtc;
+ ASSERT_TRUE(webrtc.IsAvailable());
+ EXPECT_FALSE(webrtc.IsAcceptingConnections(std::string{}));
+ env_.Stop();
+}
+
+// Tests the flow when the device tries to accept connections twice. In this
+// case, only the first call is successful and subsequent calls fail.
+TEST_F(WebRtcTest, StartAcceptingConnectionTwice) {
+ env_.Start({.webrtc_enabled = true});
+ testing::StrictMock<MockAcceptedCallback> mock_accepted_callback_;
+ WebRtc webrtc;
+ WebrtcPeerId self_id("peer_id");
+ const std::string service_id("NearbySharing");
+ LocationHint location_hint{};
+
+ ASSERT_TRUE(webrtc.IsAvailable());
+ ASSERT_TRUE(webrtc.StartAcceptingConnections(
+ service_id, self_id, location_hint,
+ {mock_accepted_callback_.AsStdFunction()}));
+ EXPECT_FALSE(webrtc.StartAcceptingConnections(
+ service_id, self_id, location_hint,
+ {mock_accepted_callback_.AsStdFunction()}));
+ EXPECT_TRUE(webrtc.IsAcceptingConnections(service_id));
+ EXPECT_FALSE(webrtc.IsAcceptingConnections(std::string{}));
+ env_.Stop();
+}
+
+// Tests the flow when the device tries to connect but there is no peer
+// accepting connections at the given peer ID.
+TEST_F(WebRtcTest, Connect_NoPeer) {
+ env_.Start({.webrtc_enabled = true});
+ WebRtc webrtc;
+ WebrtcPeerId peer_id("peer_id");
+ const std::string service_id("NearbySharing");
+ LocationHint location_hint;
+
+ ASSERT_TRUE(webrtc.IsAvailable());
+ CancellationFlag flag;
+ WebRtcSocketWrapper wrapper_1 =
+ webrtc.Connect(service_id, peer_id, location_hint, &flag);
+ EXPECT_FALSE(wrapper_1.IsValid());
+
+ EXPECT_TRUE(webrtc.StartAcceptingConnections(
+ service_id, peer_id, location_hint, AcceptedConnectionCallback()));
+ env_.Stop();
+}
+
+// Tests the flow when the device calls Connect() after calling
+// StartAcceptingConnections() without StopAcceptingConnections().
+TEST_F(WebRtcTest, StartAcceptingConnection_ThenConnect) {
+ env_.Start({.webrtc_enabled = true});
+ testing::StrictMock<MockAcceptedCallback> mock_accepted_callback_;
+ WebRtc webrtc;
+ WebrtcPeerId self_id("peer_id");
+ const std::string service_id("NearbySharing");
+ LocationHint location_hint;
+
+ ASSERT_TRUE(webrtc.IsAvailable());
+ ASSERT_TRUE(webrtc.StartAcceptingConnections(
+ service_id, self_id, location_hint,
+ {mock_accepted_callback_.AsStdFunction()}));
+ CancellationFlag flag;
+ WebRtcSocketWrapper wrapper = webrtc.Connect(
+ service_id, WebrtcPeerId("random_peer_id"), location_hint, &flag);
+ EXPECT_TRUE(webrtc.IsAcceptingConnections(service_id));
+ EXPECT_FALSE(wrapper.IsValid());
+ EXPECT_FALSE(webrtc.StartAcceptingConnections(
+ service_id, self_id, location_hint,
+ {mock_accepted_callback_.AsStdFunction()}));
+ env_.Stop();
+}
+
+// Tests the flow when the device calls StartAcceptingConnections but the medium
+// is closed before a peer device can connect to it.
+TEST_F(WebRtcTest, StartAndStopAcceptingConnections) {
+ env_.Start({.webrtc_enabled = true});
+ testing::StrictMock<MockAcceptedCallback> mock_accepted_callback_;
+ WebRtc webrtc;
+ WebrtcPeerId self_id("peer_id");
+ const std::string service_id("NearbySharing");
+ LocationHint location_hint;
+
+ ASSERT_TRUE(webrtc.IsAvailable());
+ ASSERT_TRUE(webrtc.StartAcceptingConnections(
+ service_id, self_id, location_hint,
+ {mock_accepted_callback_.AsStdFunction()}));
+ EXPECT_TRUE(webrtc.IsAcceptingConnections(service_id));
+ webrtc.StopAcceptingConnections(service_id);
+ EXPECT_FALSE(webrtc.IsAcceptingConnections(service_id));
+ env_.Stop();
+}
+
+// Tests the flow when the device tries to connect to two different peers
+// without disconnecting in between.
+TEST_F(WebRtcTest, ConnectTwice) {
+ env_.Start({.webrtc_enabled = true});
+ WebRtc receiver, sender, device_c;
+ WebRtcSocketWrapper receiver_socket, sender_socket;
+ const WebrtcPeerId self_id("self_id"), other_id("other_id");
+ const std::string service_id("NearbySharing");
+ LocationHint location_hint;
+ Future<bool> connected;
+ ByteArray message("message xyz");
+
+ receiver.StartAcceptingConnections(
+ service_id, self_id, location_hint,
+ {[&receiver_socket, connected](WebRtcSocketWrapper wrapper) mutable {
+ receiver_socket = wrapper;
+ connected.Set(receiver_socket.IsValid());
+ }});
+
+ device_c.StartAcceptingConnections(service_id, other_id, location_hint,
+ {[](WebRtcSocketWrapper wrapper) {}});
+
+ CancellationFlag flag;
+ sender_socket = sender.Connect(service_id, self_id, location_hint, &flag);
+ EXPECT_TRUE(sender_socket.IsValid());
+
+ ExceptionOr<bool> devices_connected = connected.Get();
+ ASSERT_TRUE(devices_connected.ok());
+ EXPECT_TRUE(devices_connected.result());
+
+ WebRtcSocketWrapper socket =
+ sender.Connect(service_id, other_id, location_hint, &flag);
+ EXPECT_TRUE(socket.IsValid());
+ socket.Close();
+
+ EXPECT_TRUE(receiver_socket.IsValid());
+ EXPECT_TRUE(sender_socket.IsValid());
+
+ sender_socket.GetOutputStream().Write(message);
+ ExceptionOr<ByteArray> received_msg =
+ receiver_socket.GetInputStream().Read(/*size=*/32);
+ ASSERT_TRUE(received_msg.ok());
+ EXPECT_EQ(message, received_msg.result());
+
+ receiver_socket.Close();
+ env_.Stop();
+}
+
+// Tests the flow when the two devices exchange SDP messages and connect to each
+// other but disconnect before being able to send/receive the actual data.
+TEST_F(WebRtcTest, ConnectBothDevicesAndAbort) {
+ env_.Start({.webrtc_enabled = true});
+ WebRtc receiver, sender;
+ WebRtcSocketWrapper receiver_socket, sender_socket;
+ const WebrtcPeerId self_id("self_id");
+ const std::string service_id("NearbySharing");
+ LocationHint location_hint;
+ Future<bool> connected;
+ ByteArray message("message xyz");
+
+ receiver.StartAcceptingConnections(
+ service_id, self_id, location_hint,
+ {[&receiver_socket, connected](WebRtcSocketWrapper wrapper) mutable {
+ receiver_socket = wrapper;
+ connected.Set(receiver_socket.IsValid());
+ }});
+
+ CancellationFlag flag;
+ sender_socket = sender.Connect(service_id, self_id, location_hint, &flag);
+ EXPECT_TRUE(sender_socket.IsValid());
+
+ ExceptionOr<bool> devices_connected = connected.Get();
+ ASSERT_TRUE(devices_connected.ok());
+ EXPECT_TRUE(devices_connected.result());
+
+ receiver_socket.Close();
+ env_.Stop();
+}
+
+// Tests the flow when the two devices exchange SDP messages and connect to each
+// other and the actual data is exchanged successfully between the devices.
+TEST_F(WebRtcTest, ConnectBothDevicesAndSendData) {
+ env_.Start({.webrtc_enabled = true});
+ WebRtc receiver, sender;
+ WebRtcSocketWrapper receiver_socket, sender_socket;
+ const WebrtcPeerId self_id("self_id");
+ const std::string service_id("NearbySharing");
+ LocationHint location_hint;
+ Future<bool> connected;
+ ByteArray message("message");
+
+ receiver.StartAcceptingConnections(
+ service_id, self_id, location_hint,
+ {[&receiver_socket, connected](WebRtcSocketWrapper wrapper) mutable {
+ receiver_socket = wrapper;
+ connected.Set(receiver_socket.IsValid());
+ }});
+
+ CancellationFlag flag;
+ sender_socket = sender.Connect(service_id, self_id, location_hint, &flag);
+ EXPECT_TRUE(sender_socket.IsValid());
+
+ ExceptionOr<bool> devices_connected = connected.Get();
+ ASSERT_TRUE(devices_connected.ok());
+ EXPECT_TRUE(devices_connected.result());
+
+ sender_socket.GetOutputStream().Write(message);
+ ExceptionOr<ByteArray> received_msg =
+ receiver_socket.GetInputStream().Read(/*size=*/32);
+ ASSERT_TRUE(received_msg.ok());
+ EXPECT_EQ(message, received_msg.result());
+
+ receiver_socket.Close();
+ env_.Stop();
+}
+
+TEST_F(WebRtcTest, Connect_NullPeerConnection) {
+ env_.Start({.webrtc_enabled = true});
+ testing::StrictMock<MockAcceptedCallback> mock_accepted_callback_;
+ env_.SetUseValidPeerConnection(
+ /*use_valid_peer_connection=*/false);
+
+ WebRtc webrtc;
+ const std::string service_id("NearbySharing");
+ WebrtcPeerId self_id("peer_id");
+ LocationHint location_hint;
+
+ ASSERT_TRUE(webrtc.IsAvailable());
+ CancellationFlag flag;
+ WebRtcSocketWrapper wrapper = webrtc.Connect(
+ service_id, WebrtcPeerId("random_peer_id"), location_hint, &flag);
+ EXPECT_FALSE(wrapper.IsValid());
+ env_.Stop();
+}
+
+// Tests the flow when the device calls StartAcceptingConnections and the
+// receive messages stream fails.
+TEST_F(WebRtcTest, ContinueAcceptingConnectionsOnComplete) {
+ env_.Start({.webrtc_enabled = true});
+ testing::StrictMock<MockAcceptedCallback> mock_accepted_callback_;
+ WebRtc webrtc;
+ WebrtcPeerId self_id("peer_id");
+ const std::string service_id("NearbySharing");
+ LocationHint location_hint;
+
+ ASSERT_TRUE(webrtc.IsAvailable());
+ ASSERT_TRUE(webrtc.StartAcceptingConnections(
+ service_id, self_id, location_hint,
+ {mock_accepted_callback_.AsStdFunction()}));
+ EXPECT_TRUE(webrtc.IsAcceptingConnections(service_id));
+
+ // Simulate a failure in receiving messages stream, WebRtc should restart
+ // accepting connections.
+ env_.SendWebRtcSignalingComplete(self_id.GetId(),
+ /*success=*/false);
+ EXPECT_TRUE(webrtc.IsAcceptingConnections(service_id));
+
+ // And a "success" message should not cause accepting connections to stop.
+ env_.SendWebRtcSignalingComplete(self_id.GetId(),
+ /*success=*/true);
+ EXPECT_TRUE(webrtc.IsAcceptingConnections(service_id));
+
+ webrtc.StopAcceptingConnections(service_id);
+ EXPECT_FALSE(webrtc.IsAcceptingConnections(service_id));
+ env_.Stop();
+}
+
+} // namespace
+
+} // namespace mediums
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/wifi_lan.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/wifi_lan.cc
new file mode 100644
index 00000000000..99b715a7c3b
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/wifi_lan.cc
@@ -0,0 +1,429 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/wifi_lan.h"
+
+#include <memory>
+#include <string>
+#include <utility>
+
+#include "absl/strings/str_format.h"
+#include "connections/implementation/mediums/utils.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/mutex_lock.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+WifiLan::~WifiLan() {
+ // Destructor is not taking locks, but methods it is calling are.
+ while (!discovering_info_.service_ids.empty()) {
+ StopDiscovery(*discovering_info_.service_ids.begin());
+ }
+ while (!server_sockets_.empty()) {
+ StopAcceptingConnections(server_sockets_.begin()->first);
+ }
+ while (!advertising_info_.nsd_service_infos.empty()) {
+ StopAdvertising(advertising_info_.nsd_service_infos.begin()->first);
+ }
+
+ // All the AcceptLoopRunnable objects in here should already have gotten an
+ // opportunity to shut themselves down cleanly in the calls to
+ // StopAcceptingConnections() above.
+ accept_loops_runner_.Shutdown();
+}
+
+bool WifiLan::IsAvailable() const {
+ MutexLock lock(&mutex_);
+
+ return IsAvailableLocked();
+}
+
+bool WifiLan::IsAvailableLocked() const { return medium_.IsValid(); }
+
+bool WifiLan::StartAdvertising(const std::string& service_id,
+ NsdServiceInfo& nsd_service_info) {
+ MutexLock lock(&mutex_);
+
+ if (!IsAvailableLocked()) {
+ NEARBY_LOGS(INFO)
+ << "Can't turn on WifiLan advertising. WifiLan is not available.";
+ return false;
+ }
+
+ if (!nsd_service_info.IsValid()) {
+ NEARBY_LOGS(INFO)
+ << "Refusing to turn on WifiLan advertising. nsd_service_info is not "
+ "valid.";
+ return false;
+ }
+
+ if (IsAdvertisingLocked(service_id)) {
+ NEARBY_LOGS(INFO)
+ << "Failed to WifiLan advertise because we're already advertising.";
+ return false;
+ }
+
+ if (!IsAcceptingConnectionsLocked(service_id)) {
+ NEARBY_LOGS(INFO)
+ << "Failed to turn on WifiLan advertising with nsd_service_info="
+ << &nsd_service_info
+ << ", service_name=" << nsd_service_info.GetServiceName()
+ << ", service_id=" << service_id
+ << ". Should accept connections before advertising.";
+ return false;
+ }
+
+ nsd_service_info.SetServiceType(GenerateServiceType(service_id));
+ const auto& it = server_sockets_.find(service_id);
+ if (it != server_sockets_.end()) {
+ nsd_service_info.SetIPAddress(it->second.GetIPAddress());
+ nsd_service_info.SetPort(it->second.GetPort());
+ }
+ if (!medium_.StartAdvertising(nsd_service_info)) {
+ NEARBY_LOGS(INFO)
+ << "Failed to turn on WifiLan advertising with nsd_service_info="
+ << &nsd_service_info
+ << ", service_name=" << nsd_service_info.GetServiceName()
+ << ", service_id=" << service_id;
+ return false;
+ }
+
+ NEARBY_LOGS(INFO) << "Turned on WifiLan advertising with nsd_service_info="
+ << &nsd_service_info
+ << ", service_name=" << nsd_service_info.GetServiceName()
+ << ", service_id=" << service_id;
+ advertising_info_.Add(service_id, std::move(nsd_service_info));
+ return true;
+}
+
+bool WifiLan::StopAdvertising(const std::string& service_id) {
+ MutexLock lock(&mutex_);
+
+ if (!IsAdvertisingLocked(service_id)) {
+ NEARBY_LOGS(INFO)
+ << "Can't turn off WifiLan advertising; it is already off";
+ return false;
+ }
+
+ NEARBY_LOGS(INFO) << "Turned off WifiLan advertising with service_id="
+ << service_id;
+ bool ret =
+ medium_.StopAdvertising(*advertising_info_.GetServiceInfo(service_id));
+ // Reset our bundle of advertising state to mark that we're no longer
+ // advertising for specific service_id.
+ advertising_info_.Remove(service_id);
+ return ret;
+}
+
+bool WifiLan::IsAdvertising(const std::string& service_id) {
+ MutexLock lock(&mutex_);
+
+ return IsAdvertisingLocked(service_id);
+}
+
+bool WifiLan::IsAdvertisingLocked(const std::string& service_id) {
+ return advertising_info_.Existed(service_id);
+}
+
+bool WifiLan::StartDiscovery(const std::string& service_id,
+ DiscoveredServiceCallback callback) {
+ MutexLock lock(&mutex_);
+
+ if (service_id.empty()) {
+ NEARBY_LOGS(INFO)
+ << "Refusing to start WifiLan discovering with empty service_id.";
+ return false;
+ }
+
+ if (!IsAvailableLocked()) {
+ NEARBY_LOGS(INFO)
+ << "Can't discover WifiLan services because WifiLan isn't available.";
+ return false;
+ }
+
+ if (IsDiscoveringLocked(service_id)) {
+ NEARBY_LOGS(INFO)
+ << "Refusing to start discovery of WifiLan services because another "
+ "discovery is already in-progress.";
+ return false;
+ }
+
+ std::string service_type = GenerateServiceType(service_id);
+ bool ret = medium_.StartDiscovery(service_id, service_type, callback);
+ if (!ret) {
+ NEARBY_LOGS(INFO) << "Failed to start discovery of WifiLan services.";
+ return false;
+ }
+
+ NEARBY_LOGS(INFO) << "Turned on WifiLan discovering with service_id="
+ << service_id;
+ // Mark the fact that we're currently performing a WifiLan discovering.
+ discovering_info_.Add(service_id);
+ return true;
+}
+
+bool WifiLan::StopDiscovery(const std::string& service_id) {
+ MutexLock lock(&mutex_);
+
+ if (!IsDiscoveringLocked(service_id)) {
+ NEARBY_LOGS(INFO)
+ << "Can't turn off WifiLan discovering because we never started "
+ "discovering.";
+ return false;
+ }
+
+ std::string service_type = GenerateServiceType(service_id);
+ NEARBY_LOGS(INFO) << "Turned off WifiLan discovering with service_id="
+ << service_id << ", service_type=" << service_type;
+ bool ret = medium_.StopDiscovery(service_type);
+ discovering_info_.Remove(service_id);
+ return ret;
+}
+
+bool WifiLan::IsDiscovering(const std::string& service_id) {
+ MutexLock lock(&mutex_);
+ return IsDiscoveringLocked(service_id);
+}
+
+bool WifiLan::IsDiscoveringLocked(const std::string& service_id) {
+ return discovering_info_.Existed(service_id);
+}
+
+bool WifiLan::StartAcceptingConnections(const std::string& service_id,
+ AcceptedConnectionCallback callback) {
+ MutexLock lock(&mutex_);
+
+ if (service_id.empty()) {
+ NEARBY_LOGS(INFO) << "Refusing to start accepting WifiLan connections; "
+ "service_id is empty.";
+ return false;
+ }
+
+ if (!IsAvailableLocked()) {
+ NEARBY_LOGS(INFO)
+ << "Can't start accepting WifiLan connections [service_id="
+ << service_id << "]; WifiLan not available.";
+ return false;
+ }
+
+ if (IsAcceptingConnectionsLocked(service_id)) {
+ NEARBY_LOGS(INFO)
+ << "Refusing to start accepting WifiLan connections [service="
+ << service_id
+ << "]; WifiLan server is already in-progress with the same name.";
+ return false;
+ }
+
+ auto port_range = medium_.GetDynamicPortRange();
+ // Generate an exact port here on server socket; if platform doesn't provide
+ // range of port then assign 0 to let platform decide it.
+ int port = 0;
+ if (port_range.has_value() &&
+ (port_range->first > 0 && port_range->first <= 65535 &&
+ port_range->second > 0 && port_range->second <= 65535 &&
+ port_range->first <= port_range->second)) {
+ port = GeneratePort(service_id, port_range.value());
+ }
+ WifiLanServerSocket server_socket = medium_.ListenForService(port);
+ if (!server_socket.IsValid()) {
+ NEARBY_LOGS(INFO)
+ << "Failed to start accepting WifiLan connections for service_id="
+ << service_id;
+ return false;
+ }
+
+ // Mark the fact that there's an in-progress WifiLan server accepting
+ // connections.
+ auto owned_server_socket =
+ server_sockets_.insert({service_id, std::move(server_socket)})
+ .first->second;
+
+ // Start the accept loop on a dedicated thread - this stays alive and
+ // listening for new incoming connections until StopAcceptingConnections() is
+ // invoked.
+ accept_loops_runner_.Execute(
+ "wifi-lan-accept",
+ [callback = std::move(callback),
+ server_socket = std::move(owned_server_socket)]() mutable {
+ while (true) {
+ WifiLanSocket client_socket = server_socket.Accept();
+ if (!client_socket.IsValid()) {
+ server_socket.Close();
+ break;
+ }
+ callback.accepted_cb(std::move(client_socket));
+ }
+ });
+
+ return true;
+}
+
+bool WifiLan::StopAcceptingConnections(const std::string& service_id) {
+ MutexLock lock(&mutex_);
+
+ if (service_id.empty()) {
+ NEARBY_LOGS(INFO) << "Unable to stop accepting WifiLan connections because "
+ "the service_id is empty.";
+ return false;
+ }
+
+ const auto& it = server_sockets_.find(service_id);
+ if (it == server_sockets_.end()) {
+ NEARBY_LOGS(INFO) << "Can't stop accepting WifiLan connections for "
+ << service_id << " because it was never started.";
+ return false;
+ }
+
+ // Closing the WifiLanServerSocket will kick off the suicide of the thread
+ // in accept_loops_thread_pool_ that blocks on WifiLanServerSocket.accept().
+ // That may take some time to complete, but there's no particular reason to
+ // wait around for it.
+ auto item = server_sockets_.extract(it);
+
+ // Store a handle to the WifiLanServerSocket, so we can use it after
+ // removing the entry from server_sockets_; making it scoped
+ // is a bonus that takes care of deallocation before we leave this method.
+ WifiLanServerSocket& listening_socket = item.mapped();
+
+ // Regardless of whether or not we fail to close the existing
+ // WifiLanServerSocket, remove it from server_sockets_ so that it
+ // frees up this service for another round.
+
+ // Finally, close the WifiLanServerSocket.
+ if (!listening_socket.Close().Ok()) {
+ NEARBY_LOGS(INFO) << "Failed to close WifiLan server socket for service_id="
+ << service_id;
+ return false;
+ }
+
+ return true;
+}
+
+bool WifiLan::IsAcceptingConnections(const std::string& service_id) {
+ MutexLock lock(&mutex_);
+ return IsAcceptingConnectionsLocked(service_id);
+}
+
+bool WifiLan::IsAcceptingConnectionsLocked(const std::string& service_id) {
+ return server_sockets_.find(service_id) != server_sockets_.end();
+}
+
+WifiLanSocket WifiLan::Connect(const std::string& service_id,
+ const NsdServiceInfo& service_info,
+ CancellationFlag* cancellation_flag) {
+ MutexLock lock(&mutex_);
+ // Socket to return. To allow for NRVO to work, it has to be a single object.
+ WifiLanSocket socket;
+
+ if (service_id.empty()) {
+ NEARBY_LOGS(INFO) << "Refusing to create client WifiLan socket because "
+ "service_id is empty.";
+ return socket;
+ }
+
+ if (!IsAvailableLocked()) {
+ NEARBY_LOGS(INFO) << "Can't create client WifiLan socket [service_id="
+ << service_id << "]; WifiLan isn't available.";
+ return socket;
+ }
+
+ if (cancellation_flag->Cancelled()) {
+ NEARBY_LOGS(INFO) << "Can't create client WifiLan socket due to cancel.";
+ return socket;
+ }
+
+ socket = medium_.ConnectToService(service_info, cancellation_flag);
+ if (!socket.IsValid()) {
+ NEARBY_LOGS(INFO) << "Failed to Connect via WifiLan [service_id="
+ << service_id << "]";
+ }
+
+ return socket;
+}
+
+WifiLanSocket WifiLan::Connect(const std::string& service_id,
+ const std::string& ip_address, int port,
+ CancellationFlag* cancellation_flag) {
+ MutexLock lock(&mutex_);
+ // Socket to return. To allow for NRVO to work, it has to be a single object.
+ WifiLanSocket socket;
+
+ if (service_id.empty()) {
+ NEARBY_LOGS(INFO) << "Refusing to create client WifiLan socket because "
+ "service_id is empty.";
+ return socket;
+ }
+
+ if (!IsAvailableLocked()) {
+ NEARBY_LOGS(INFO) << "Can't create client WifiLan socket [service_id="
+ << service_id << "]; WifiLan isn't available.";
+ return socket;
+ }
+
+ if (cancellation_flag->Cancelled()) {
+ NEARBY_LOGS(INFO) << "Can't create client WifiLan socket due to cancel.";
+ return socket;
+ }
+
+ socket = medium_.ConnectToService(ip_address, port, cancellation_flag);
+ if (!socket.IsValid()) {
+ NEARBY_LOGS(INFO) << "Failed to Connect via WifiLan [service_id="
+ << service_id << "]";
+ }
+
+ return socket;
+}
+
+std::pair<std::string, int> WifiLan::GetCredentials(
+ const std::string& service_id) {
+ MutexLock lock(&mutex_);
+ const auto& it = server_sockets_.find(service_id);
+ if (it == server_sockets_.end()) {
+ return std::pair<std::string, int>();
+ }
+ return std::pair<std::string, int>(it->second.GetIPAddress(),
+ it->second.GetPort());
+}
+
+std::string WifiLan::GenerateServiceType(const std::string& service_id) {
+ std::string service_id_hash_string;
+
+ const ByteArray service_id_hash = Utils::Sha256Hash(
+ service_id, NsdServiceInfo::kTypeFromServiceIdHashLength);
+ for (auto byte : std::string(service_id_hash)) {
+ absl::StrAppend(&service_id_hash_string, absl::StrFormat("%02X", byte));
+ }
+
+ return absl::StrFormat(NsdServiceInfo::kNsdTypeFormat,
+ service_id_hash_string);
+}
+
+int WifiLan::GeneratePort(const std::string& service_id,
+ std::pair<std::int32_t, std::int32_t> port_range) {
+ const std::string service_id_hash =
+ std::string(Utils::Sha256Hash(service_id, 4));
+
+ std::uint32_t uint_of_service_id_hash =
+ service_id_hash[0] << 24 | service_id_hash[1] << 16 |
+ service_id_hash[2] << 8 | service_id_hash[3];
+
+ return port_range.first +
+ (uint_of_service_id_hash % (port_range.second - port_range.first));
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/wifi_lan.h b/chromium/third_party/nearby/src/connections/implementation/mediums/wifi_lan.h
new file mode 100644
index 00000000000..c7a3988a556
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/wifi_lan.h
@@ -0,0 +1,198 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MEDIUMS_WIFI_LAN_H_
+#define CORE_INTERNAL_MEDIUMS_WIFI_LAN_H_
+
+#include <cstdint>
+#include <string>
+
+#include "absl/container/flat_hash_map.h"
+#include "absl/container/flat_hash_set.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/cancellation_flag.h"
+#include "internal/platform/nsd_service_info.h"
+#include "internal/platform/multi_thread_executor.h"
+#include "internal/platform/mutex.h"
+#include "internal/platform/wifi_lan.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+class WifiLan {
+ public:
+ using DiscoveredServiceCallback = WifiLanMedium::DiscoveredServiceCallback;
+
+ // Callback that is invoked when a new connection is accepted.
+ struct AcceptedConnectionCallback {
+ std::function<void(WifiLanSocket socket)> accepted_cb =
+ DefaultCallback<WifiLanSocket>();
+ };
+
+ WifiLan() = default;
+ ~WifiLan();
+
+ // Returns true, if WifiLan communications are supported by a platform.
+ bool IsAvailable() const ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Sets custom service info name, endpoint info name in NsdServiceInfo and
+ // then enables WifiLan advertising.
+ // Returns true, if NsdServiceInfo is successfully set, and false otherwise.
+ bool StartAdvertising(const std::string& service_id,
+ NsdServiceInfo& nsd_service_info)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Disables WifiLan advertising.
+ // Returns false if no successful call StartAdvertising() was previously
+ // made, otherwise returns true.
+ bool StopAdvertising(const std::string& service_id)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ bool IsAdvertising(const std::string& service_id) ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Enables WifiLan discovery. Will report any discoverable services
+ // through a callback.
+ // Returns true, if discovery was enabled, false otherwise.
+ bool StartDiscovery(const std::string& service_id,
+ DiscoveredServiceCallback callback)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Disables WifiLan discovery.
+ bool StopDiscovery(const std::string& service_id) ABSL_LOCKS_EXCLUDED(mutex_);
+
+ bool IsDiscovering(const std::string& service_id) ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Starts a worker thread, creates a WifiLan socket, associates it with a
+ // service id.
+ bool StartAcceptingConnections(const std::string& service_id,
+ AcceptedConnectionCallback callback)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Closes socket corresponding to a service id.
+ bool StopAcceptingConnections(const std::string& service_id)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ bool IsAcceptingConnections(const std::string& service_id)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Establishes connection to WifiLan service that was might be started on
+ // another service with StartAcceptingConnections() using the same service_id.
+ // Blocks until connection is established, or server-side is terminated.
+ // Returns socket instance. On success, WifiLanSocket.IsValid() return true.
+ WifiLanSocket Connect(const std::string& service_id,
+ const NsdServiceInfo& service_info,
+ CancellationFlag* cancellation_flag)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Establishes connection to WifiLan service by ip address and port for
+ // bandwidth upgradation.
+ // Returns socket instance. On success, WifiLanSocket.IsValid() return true.
+ WifiLanSocket Connect(const std::string& service_id,
+ const std::string& ip_address, int port,
+ CancellationFlag* cancellation_flag)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Gets ip address + port for remote services on the network to identify and
+ // connect to this service.
+ //
+ // Credential is for the currently-hosted Wifi ServerSocket (if any).
+ std::pair<std::string, int> GetCredentials(const std::string& service_id)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ private:
+ struct AdvertisingInfo {
+ bool Empty() const { return nsd_service_infos.empty(); }
+ void Clear() { nsd_service_infos.clear(); }
+ void Add(const std::string& service_id,
+ const NsdServiceInfo& nsd_service_info) {
+ nsd_service_infos.insert({service_id, nsd_service_info});
+ }
+ void Remove(const std::string& service_id) {
+ nsd_service_infos.erase(service_id);
+ }
+ bool Existed(const std::string& service_id) const {
+ return nsd_service_infos.contains(service_id);
+ }
+ NsdServiceInfo* GetServiceInfo(const std::string& service_id) {
+ const auto& it = nsd_service_infos.find(service_id);
+ if (it == nsd_service_infos.end()) {
+ return nullptr;
+ }
+ return &it->second;
+ }
+
+ absl::flat_hash_map<std::string, NsdServiceInfo> nsd_service_infos;
+ };
+
+ struct DiscoveringInfo {
+ bool Empty() const { return service_ids.empty(); }
+ void Clear() { service_ids.clear(); }
+ void Add(const std::string& service_id) { service_ids.insert(service_id); }
+ void Remove(const std::string& service_id) {
+ service_ids.erase(service_id);
+ }
+ bool Existed(const std::string& service_id) const {
+ return service_ids.contains(service_id);
+ }
+
+ absl::flat_hash_set<std::string> service_ids;
+ };
+
+ static constexpr int kMaxConcurrentAcceptLoops = 5;
+
+ // Same as IsAvailable(), but must be called with mutex_ held.
+ bool IsAvailableLocked() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Same as IsAdvertising(), but must be called with mutex_ held.
+ bool IsAdvertisingLocked(const std::string& service_id)
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Same as IsDiscovering(), but must be called with mutex_ held.
+ bool IsDiscoveringLocked(const std::string& service_id)
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Same as IsAcceptingConnections(), but must be called with mutex_ held.
+ bool IsAcceptingConnectionsLocked(const std::string& service_id)
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Generates mDNS type.
+ std::string GenerateServiceType(const std::string& service_id);
+
+ // Generates port number based on port_range_.
+ int GeneratePort(const std::string& service_id,
+ std::pair<std::int32_t, std::int32_t> port_range);
+
+ mutable Mutex mutex_;
+ WifiLanMedium medium_ ABSL_GUARDED_BY(mutex_);
+ AdvertisingInfo advertising_info_ ABSL_GUARDED_BY(mutex_);
+ DiscoveringInfo discovering_info_ ABSL_GUARDED_BY(mutex_);
+
+ // A thread pool dedicated to running all the accept loops from
+ // StartAcceptingConnections().
+ MultiThreadExecutor accept_loops_runner_{kMaxConcurrentAcceptLoops};
+
+ // A map of service_id -> ServerSocket. If map is non-empty, we
+ // are currently listening for incoming connections.
+ // WifiLanServerSocket instances are used from accept_loops_runner_,
+ // and thus require pointer stability.
+ absl::flat_hash_map<std::string, WifiLanServerSocket> server_sockets_
+ ABSL_GUARDED_BY(mutex_);
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MEDIUMS_WIFI_LAN_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/mediums/wifi_lan_test.cc b/chromium/third_party/nearby/src/connections/implementation/mediums/wifi_lan_test.cc
new file mode 100644
index 00000000000..966cf505803
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mediums/wifi_lan_test.cc
@@ -0,0 +1,348 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/mediums/wifi_lan.h"
+
+#include <string>
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "absl/strings/string_view.h"
+#include "internal/platform/medium_environment.h"
+#include "internal/platform/nsd_service_info.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/wifi_lan.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+
+using FeatureFlags = FeatureFlags::Flags;
+
+constexpr FeatureFlags kTestCases[] = {
+ FeatureFlags{
+ .enable_cancellation_flag = true,
+ },
+ FeatureFlags{
+ .enable_cancellation_flag = false,
+ },
+};
+
+constexpr absl::Duration kWaitDuration = absl::Milliseconds(1000);
+constexpr absl::string_view kServiceID{"com.google.location.nearby.apps.test"};
+constexpr absl::string_view kServiceInfoName{"ServiceInfoName"};
+constexpr absl::string_view kEndpointName{"EndpointName"};
+constexpr absl::string_view kEndpointInfoKey{"n"};
+
+class WifiLanTest : public ::testing::TestWithParam<FeatureFlags> {
+ protected:
+ using DiscoveredServiceCallback = WifiLanMedium::DiscoveredServiceCallback;
+
+ WifiLanTest() { env_.Stop(); }
+
+ MediumEnvironment& env_{MediumEnvironment::Instance()};
+};
+
+TEST_P(WifiLanTest, CanConnect) {
+ FeatureFlags feature_flags = GetParam();
+ env_.SetFeatureFlags(feature_flags);
+ env_.Start();
+ WifiLan wifi_lan_client;
+ WifiLan wifi_lan_server;
+ std::string service_id(kServiceID);
+ std::string service_info_name(kServiceInfoName);
+ std::string endpoint_info_name(kEndpointName);
+ CountDownLatch discovered_latch(1);
+ CountDownLatch accept_latch(1);
+
+ WifiLanSocket socket_for_server;
+ EXPECT_TRUE(wifi_lan_server.StartAcceptingConnections(
+ service_id,
+ {
+ .accepted_cb =
+ [&socket_for_server, &accept_latch](WifiLanSocket socket) {
+ socket_for_server = std::move(socket);
+ accept_latch.CountDown();
+ },
+ }));
+
+ NsdServiceInfo nsd_service_info;
+ nsd_service_info.SetServiceName(service_info_name);
+ nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
+ endpoint_info_name);
+ wifi_lan_server.StartAdvertising(service_id, nsd_service_info);
+
+ NsdServiceInfo discovered_service_info;
+ wifi_lan_client.StartDiscovery(
+ service_id,
+ {
+ .service_discovered_cb =
+ [&discovered_latch, &discovered_service_info](
+ NsdServiceInfo service_info, const std::string& service_id) {
+ NEARBY_LOGS(INFO)
+ << "Discovered service_info=" << &service_info;
+ discovered_service_info = service_info;
+ discovered_latch.CountDown();
+ },
+ });
+ discovered_latch.Await(kWaitDuration).result();
+ ASSERT_TRUE(discovered_service_info.IsValid());
+
+ CancellationFlag flag;
+ WifiLanSocket socket_for_client =
+ wifi_lan_client.Connect(service_id, discovered_service_info, &flag);
+ EXPECT_TRUE(accept_latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(wifi_lan_server.StopAcceptingConnections(service_id));
+ EXPECT_TRUE(wifi_lan_server.StopAdvertising(service_id));
+ EXPECT_TRUE(socket_for_server.IsValid());
+ EXPECT_TRUE(socket_for_client.IsValid());
+ env_.Stop();
+}
+
+TEST_P(WifiLanTest, CanCancelConnect) {
+ FeatureFlags feature_flags = GetParam();
+ env_.SetFeatureFlags(feature_flags);
+ env_.Start();
+ WifiLan wifi_lan_client;
+ WifiLan wifi_lan_server;
+ std::string service_id(kServiceID);
+ std::string service_info_name(kServiceInfoName);
+ std::string endpoint_info_name(kEndpointName);
+ CountDownLatch discovered_latch(1);
+ CountDownLatch accept_latch(1);
+
+ WifiLanSocket socket_for_server;
+ EXPECT_TRUE(wifi_lan_server.StartAcceptingConnections(
+ service_id,
+ {
+ .accepted_cb =
+ [&socket_for_server, &accept_latch](WifiLanSocket socket) {
+ socket_for_server = std::move(socket);
+ accept_latch.CountDown();
+ },
+ }));
+
+ NsdServiceInfo nsd_service_info;
+ nsd_service_info.SetServiceName(service_info_name);
+ nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
+ endpoint_info_name);
+ wifi_lan_server.StartAdvertising(service_id, nsd_service_info);
+
+ NsdServiceInfo discovered_service_info;
+ wifi_lan_client.StartDiscovery(
+ service_id,
+ {
+ .service_discovered_cb =
+ [&discovered_latch, &discovered_service_info](
+ NsdServiceInfo service_info, const std::string& service_id) {
+ NEARBY_LOGS(INFO)
+ << "Discovered service_info=" << &service_info;
+ discovered_service_info = service_info;
+ discovered_latch.CountDown();
+ },
+ });
+ EXPECT_TRUE(discovered_latch.Await(kWaitDuration).result());
+ ASSERT_TRUE(discovered_service_info.IsValid());
+
+ CancellationFlag flag(true);
+ WifiLanSocket socket_for_client =
+ wifi_lan_client.Connect(service_id, discovered_service_info, &flag);
+ // If FeatureFlag is disabled, Cancelled is false as no-op.
+ if (!feature_flags.enable_cancellation_flag) {
+ EXPECT_TRUE(accept_latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(wifi_lan_server.StopAcceptingConnections(service_id));
+ EXPECT_TRUE(wifi_lan_server.StopAdvertising(service_id));
+ EXPECT_TRUE(socket_for_server.IsValid());
+ EXPECT_TRUE(socket_for_client.IsValid());
+ } else {
+ EXPECT_FALSE(accept_latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(wifi_lan_server.StopAcceptingConnections(service_id));
+ EXPECT_TRUE(wifi_lan_server.StopAdvertising(service_id));
+ EXPECT_FALSE(socket_for_server.IsValid());
+ EXPECT_FALSE(socket_for_client.IsValid());
+ }
+ env_.Stop();
+}
+
+INSTANTIATE_TEST_SUITE_P(ParametrisedWifiLanTest, WifiLanTest,
+ ::testing::ValuesIn(kTestCases));
+
+TEST_F(WifiLanTest, CanConstructValidObject) {
+ env_.Start();
+ WifiLan wifi_lan_a;
+ WifiLan wifi_lan_b;
+ std::string service_id(kServiceID);
+
+ EXPECT_TRUE(wifi_lan_a.IsAvailable());
+ EXPECT_TRUE(wifi_lan_b.IsAvailable());
+ env_.Stop();
+}
+
+TEST_F(WifiLanTest, CanStartAdvertising) {
+ env_.Start();
+ WifiLan wifi_lan_a;
+ std::string service_id(kServiceID);
+ std::string service_info_name(kServiceInfoName);
+ std::string endpoint_info_name(kEndpointName);
+
+ EXPECT_TRUE(wifi_lan_a.StartAcceptingConnections(service_id, {}));
+
+ NsdServiceInfo nsd_service_info;
+ nsd_service_info.SetServiceName(service_info_name);
+ nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
+ endpoint_info_name);
+ EXPECT_TRUE(wifi_lan_a.StartAdvertising(service_id, nsd_service_info));
+ EXPECT_TRUE(wifi_lan_a.StopAdvertising(service_id));
+ env_.Stop();
+}
+
+TEST_F(WifiLanTest, CanStartMultipleAdvertising) {
+ env_.Start();
+ WifiLan wifi_lan_a;
+ std::string service_id_1(kServiceID);
+ std::string service_id_2("com.google.location.nearby.apps.test_1");
+ std::string service_info_name_1(kServiceInfoName);
+ std::string service_info_name_2("ServiceInfoName_1");
+ std::string endpoint_info_name(kEndpointName);
+
+ EXPECT_TRUE(wifi_lan_a.StartAcceptingConnections(service_id_1, {}));
+ EXPECT_TRUE(wifi_lan_a.StartAcceptingConnections(service_id_2, {}));
+
+ NsdServiceInfo nsd_service_info_1;
+ nsd_service_info_1.SetServiceName(service_info_name_1);
+ nsd_service_info_1.SetTxtRecord(std::string(kEndpointInfoKey),
+ endpoint_info_name);
+ NsdServiceInfo nsd_service_info_2;
+ nsd_service_info_2.SetServiceName(service_info_name_2);
+ nsd_service_info_2.SetTxtRecord(std::string(kEndpointInfoKey),
+ endpoint_info_name);
+ EXPECT_TRUE(wifi_lan_a.StartAdvertising(service_id_1, nsd_service_info_1));
+ EXPECT_TRUE(wifi_lan_a.StartAdvertising(service_id_2, nsd_service_info_2));
+ EXPECT_TRUE(wifi_lan_a.StopAdvertising(service_id_1));
+ EXPECT_TRUE(wifi_lan_a.StopAdvertising(service_id_2));
+ EXPECT_TRUE(wifi_lan_a.StopAcceptingConnections(service_id_1));
+ EXPECT_TRUE(wifi_lan_a.StopAcceptingConnections(service_id_2));
+ env_.Stop();
+}
+
+TEST_F(WifiLanTest, CanStartDiscovery) {
+ env_.Start();
+ WifiLan wifi_lan_a;
+ std::string service_id(kServiceID);
+
+ EXPECT_TRUE(
+ wifi_lan_a.StartDiscovery(service_id, DiscoveredServiceCallback{}));
+ EXPECT_TRUE(wifi_lan_a.StopDiscovery(service_id));
+ env_.Stop();
+}
+
+TEST_F(WifiLanTest, CanStartMultipleDiscovery) {
+ env_.Start();
+ WifiLan wifi_lan_a;
+ std::string service_id_1(kServiceID);
+ std::string service_id_2("com.google.location.nearby.apps.test_1");
+
+ EXPECT_TRUE(
+ wifi_lan_a.StartDiscovery(service_id_1, DiscoveredServiceCallback{}));
+
+ EXPECT_TRUE(
+ wifi_lan_a.StartDiscovery(service_id_2, DiscoveredServiceCallback{}));
+ EXPECT_TRUE(wifi_lan_a.StopDiscovery(service_id_1));
+ EXPECT_TRUE(wifi_lan_a.StopDiscovery(service_id_2));
+ env_.Stop();
+}
+
+TEST_F(WifiLanTest, CanAdvertiseThatOtherMediumDiscover) {
+ env_.Start();
+ WifiLan wifi_lan_a;
+ WifiLan wifi_lan_b;
+ std::string service_id(kServiceID);
+ std::string service_info_name(kServiceInfoName);
+ std::string endpoint_info_name(kEndpointName);
+ CountDownLatch discovered_latch(1);
+ CountDownLatch lost_latch(1);
+
+ wifi_lan_b.StartDiscovery(
+ service_id, DiscoveredServiceCallback{
+ .service_discovered_cb =
+ [&discovered_latch](NsdServiceInfo service_info,
+ const std::string& service_id) {
+ discovered_latch.CountDown();
+ },
+ .service_lost_cb =
+ [&lost_latch](NsdServiceInfo service_info,
+ const std::string& service_id) {
+ lost_latch.CountDown();
+ },
+ });
+
+ EXPECT_TRUE(wifi_lan_a.StartAcceptingConnections(service_id, {}));
+
+ NsdServiceInfo nsd_service_info;
+ nsd_service_info.SetServiceName(service_info_name);
+ nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
+ endpoint_info_name);
+ EXPECT_TRUE(wifi_lan_a.StartAdvertising(service_id, nsd_service_info));
+ EXPECT_TRUE(discovered_latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(wifi_lan_a.StopAdvertising(service_id));
+ EXPECT_TRUE(lost_latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(wifi_lan_b.StopDiscovery(service_id));
+ env_.Stop();
+}
+
+TEST_F(WifiLanTest, CanDiscoverThatOtherMediumAdvertise) {
+ env_.Start();
+ WifiLan wifi_lan_a;
+ WifiLan wifi_lan_b;
+ std::string service_id(kServiceID);
+ std::string service_info_name(kServiceInfoName);
+ std::string endpoint_info_name(kEndpointName);
+ CountDownLatch discovered_latch(1);
+ CountDownLatch lost_latch(1);
+
+ EXPECT_TRUE(wifi_lan_b.StartAcceptingConnections(service_id, {}));
+
+ NsdServiceInfo nsd_service_info;
+ nsd_service_info.SetServiceName(service_info_name);
+ nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
+ endpoint_info_name);
+ wifi_lan_b.StartAdvertising(service_id, nsd_service_info);
+
+ EXPECT_TRUE(wifi_lan_a.StartDiscovery(
+ service_id, DiscoveredServiceCallback{
+ .service_discovered_cb =
+ [&discovered_latch](NsdServiceInfo service_info,
+ const std::string& service_id) {
+ discovered_latch.CountDown();
+ },
+ .service_lost_cb =
+ [&lost_latch](NsdServiceInfo service_info,
+ const std::string& service_id) {
+ lost_latch.CountDown();
+ },
+ }));
+ EXPECT_TRUE(discovered_latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(wifi_lan_b.StopAdvertising(service_id));
+ EXPECT_TRUE(lost_latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(wifi_lan_a.StopDiscovery(service_id));
+ env_.Stop();
+}
+
+} // namespace
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/message_lite.h b/chromium/third_party/nearby/src/connections/implementation/message_lite.h
index 5ce9d91e88a..5ce9d91e88a 100644
--- a/chromium/third_party/nearby/src/cpp/core/internal/message_lite.h
+++ b/chromium/third_party/nearby/src/connections/implementation/message_lite.h
diff --git a/chromium/third_party/nearby/src/connections/implementation/mock_service_controller.h b/chromium/third_party/nearby/src/connections/implementation/mock_service_controller.h
new file mode 100644
index 00000000000..bea01560517
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mock_service_controller.h
@@ -0,0 +1,92 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MOCK_SERVICE_CONTROLLER_H_
+#define CORE_INTERNAL_MOCK_SERVICE_CONTROLLER_H_
+
+#include "gmock/gmock.h"
+#include "connections/implementation/service_controller.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+/* Mock implementation for ServiceController:
+ * All methods execute asynchronously (in a private executor thread).
+ * To synchronise, two approaches may be used:
+ * 1. For methods that have result callback, we use it to unblock main thread.
+ * 2. For methods that do not have callbacks, we provide a mock implementation
+ * that unblocks main thread.
+ */
+class MockServiceController : public ServiceController {
+ public:
+ MOCK_METHOD(void, Stop, (), (override));
+ MOCK_METHOD(Status, StartAdvertising,
+ (ClientProxy * client, const std::string& service_id,
+ const AdvertisingOptions& advertising_options,
+ const ConnectionRequestInfo& info),
+ (override));
+
+ MOCK_METHOD(void, StopAdvertising, (ClientProxy * client), (override));
+
+ MOCK_METHOD(Status, StartDiscovery,
+ (ClientProxy * client, const std::string& service_id,
+ const DiscoveryOptions& discovery_options,
+ const DiscoveryListener& listener),
+ (override));
+
+ MOCK_METHOD(void, StopDiscovery, (ClientProxy * client), (override));
+
+ MOCK_METHOD(void, InjectEndpoint,
+ (ClientProxy * client, const std::string& service_id,
+ const OutOfBandConnectionMetadata& metadata),
+ (override));
+
+ MOCK_METHOD(Status, RequestConnection,
+ (ClientProxy * client, const std::string& endpoint_id,
+ const ConnectionRequestInfo& info,
+ const ConnectionOptions& connection_options),
+ (override));
+
+ MOCK_METHOD(Status, AcceptConnection,
+ (ClientProxy * client, const std::string& endpoint_id,
+ const PayloadListener& listener),
+ (override));
+
+ MOCK_METHOD(Status, RejectConnection,
+ (ClientProxy * client, const std::string& endpoint_id),
+ (override));
+
+ MOCK_METHOD(void, InitiateBandwidthUpgrade,
+ (ClientProxy * client, const std::string& endpoint_id),
+ (override));
+
+ MOCK_METHOD(void, SendPayload,
+ (ClientProxy * client,
+ const std::vector<std::string>& endpoint_ids, Payload payload),
+ (override));
+
+ MOCK_METHOD(Status, CancelPayload,
+ (ClientProxy * client, std::int64_t payload_id), (override));
+
+ MOCK_METHOD(void, DisconnectFromEndpoint,
+ (ClientProxy * client, const std::string& endpoint_id),
+ (override));
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MOCK_SERVICE_CONTROLLER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/mock_service_controller_router.h b/chromium/third_party/nearby/src/connections/implementation/mock_service_controller_router.h
new file mode 100644
index 00000000000..f3aa02877d4
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/mock_service_controller_router.h
@@ -0,0 +1,101 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_MOCK_SERVICE_CONTROLLER_ROUTER_H_
+#define CORE_INTERNAL_MOCK_SERVICE_CONTROLLER_ROUTER_H_
+
+#include "gmock/gmock.h"
+#include "connections/implementation/service_controller_router.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+class MockServiceControllerRouter : public ServiceControllerRouter {
+ public:
+ MOCK_METHOD(void, StartAdvertising,
+ (ClientProxy * client, absl::string_view service_id,
+ const AdvertisingOptions& advertising_options,
+ const ConnectionRequestInfo& info,
+ const ResultCallback& callback),
+ (override));
+
+ MOCK_METHOD(void, StopAdvertising,
+ (ClientProxy * client, const ResultCallback& callback),
+ (override));
+
+ MOCK_METHOD(void, StartDiscovery,
+ (ClientProxy * client, absl::string_view service_id,
+ const DiscoveryOptions& discovery_options,
+ const DiscoveryListener& listener,
+ const ResultCallback& callback),
+ (override));
+
+ MOCK_METHOD(void, StopDiscovery,
+ (ClientProxy * client, const ResultCallback& callback),
+ (override));
+
+ MOCK_METHOD(void, InjectEndpoint,
+ (ClientProxy * client, absl::string_view service_id,
+ const OutOfBandConnectionMetadata& metadata,
+ const ResultCallback& callback),
+ (override));
+
+ MOCK_METHOD(void, RequestConnection,
+ (ClientProxy * client, absl::string_view endpoint_id,
+ const ConnectionRequestInfo& info,
+ const ConnectionOptions& connection_options,
+ const ResultCallback& callback),
+ (override));
+
+ MOCK_METHOD(void, AcceptConnection,
+ (ClientProxy * client, absl::string_view endpoint_id,
+ const PayloadListener& listener, const ResultCallback& callback),
+ (override));
+
+ MOCK_METHOD(void, RejectConnection,
+ (ClientProxy * client, absl::string_view endpoint_id,
+ const ResultCallback& callback),
+ (override));
+
+ MOCK_METHOD(void, InitiateBandwidthUpgrade,
+ (ClientProxy * client, absl::string_view endpoint_id,
+ const ResultCallback& callback),
+ (override));
+
+ MOCK_METHOD(void, SendPayload,
+ (ClientProxy * client, absl::Span<const std::string> endpoint_ids,
+ Payload payload, const ResultCallback& callback),
+ (override));
+
+ MOCK_METHOD(void, CancelPayload,
+ (ClientProxy * client, std::uint64_t payload_id,
+ const ResultCallback& callback),
+ (override));
+
+ MOCK_METHOD(void, DisconnectFromEndpoint,
+ (ClientProxy * client, absl::string_view endpoint_id,
+ const ResultCallback& callback),
+ (override));
+
+ MOCK_METHOD(void, StopAllEndpoints,
+ (ClientProxy * client, const ResultCallback& callback),
+ (override));
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_MOCK_SERVICE_CONTROLLER_ROUTER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/offline_frames.cc b/chromium/third_party/nearby/src/connections/implementation/offline_frames.cc
new file mode 100644
index 00000000000..41829302adb
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/offline_frames.cc
@@ -0,0 +1,502 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/offline_frames.h"
+
+#include <memory>
+#include <utility>
+
+#include "connections/implementation/message_lite.h"
+#include "connections/implementation/offline_frames_validator.h"
+#include "connections/status.h"
+#include "internal/platform/byte_array.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace parser {
+namespace {
+
+using ExceptionOrOfflineFrame = ExceptionOr<OfflineFrame>;
+using MessageLite = ::google::protobuf::MessageLite;
+
+ByteArray ToBytes(OfflineFrame&& frame) {
+ ByteArray bytes(frame.ByteSizeLong());
+ frame.set_version(OfflineFrame::V1);
+ frame.SerializeToArray(bytes.data(), bytes.size());
+ return bytes;
+}
+
+} // namespace
+
+ExceptionOrOfflineFrame FromBytes(const ByteArray& bytes) {
+ OfflineFrame frame;
+
+ if (frame.ParseFromString(std::string(bytes))) {
+ Exception validation_exception = EnsureValidOfflineFrame(frame);
+ if (validation_exception.Raised()) {
+ return ExceptionOrOfflineFrame(validation_exception);
+ }
+ return ExceptionOrOfflineFrame(std::move(frame));
+ } else {
+ return ExceptionOrOfflineFrame(Exception::kInvalidProtocolBuffer);
+ }
+}
+
+V1Frame::FrameType GetFrameType(const OfflineFrame& frame) {
+ if ((frame.version() == OfflineFrame::V1) && frame.has_v1()) {
+ return frame.v1().type();
+ }
+
+ return V1Frame::UNKNOWN_FRAME_TYPE;
+}
+
+ByteArray ForConnectionRequest(const std::string& endpoint_id,
+ const ByteArray& endpoint_info,
+ std::int32_t nonce, bool supports_5_ghz,
+ const std::string& bssid,
+ const std::vector<Medium>& mediums,
+ std::int32_t keep_alive_interval_millis,
+ std::int32_t keep_alive_timeout_millis) {
+ OfflineFrame frame;
+
+ frame.set_version(OfflineFrame::V1);
+ auto* v1_frame = frame.mutable_v1();
+ v1_frame->set_type(V1Frame::CONNECTION_REQUEST);
+ auto* connection_request = v1_frame->mutable_connection_request();
+ if (!endpoint_id.empty()) connection_request->set_endpoint_id(endpoint_id);
+ if (!endpoint_info.Empty()) {
+ connection_request->set_endpoint_name(std::string(endpoint_info));
+ connection_request->set_endpoint_info(std::string(endpoint_info));
+ }
+ connection_request->set_nonce(nonce);
+ auto* medium_metadata = connection_request->mutable_medium_metadata();
+ medium_metadata->set_supports_5_ghz(supports_5_ghz);
+ if (!bssid.empty()) medium_metadata->set_bssid(bssid);
+ if (!mediums.empty()) {
+ for (const auto& medium : mediums) {
+ connection_request->add_mediums(MediumToConnectionRequestMedium(medium));
+ }
+ }
+ if (keep_alive_interval_millis > 0) {
+ connection_request->set_keep_alive_interval_millis(
+ keep_alive_interval_millis);
+ }
+ if (keep_alive_timeout_millis > 0) {
+ connection_request->set_keep_alive_timeout_millis(
+ keep_alive_timeout_millis);
+ }
+
+ return ToBytes(std::move(frame));
+}
+
+ByteArray ForConnectionResponse(std::int32_t status) {
+ OfflineFrame frame;
+
+ frame.set_version(OfflineFrame::V1);
+ auto* v1_frame = frame.mutable_v1();
+ v1_frame->set_type(V1Frame::CONNECTION_RESPONSE);
+ auto* sub_frame = v1_frame->mutable_connection_response();
+
+ // For backward compatiblility, here still sets both status and response
+ // parameters until the response feature is roll out in all supported
+ // devices.
+ sub_frame->set_status(status);
+ sub_frame->set_response(status == Status::kSuccess
+ ? ConnectionResponseFrame::ACCEPT
+ : ConnectionResponseFrame::REJECT);
+
+ return ToBytes(std::move(frame));
+}
+
+ByteArray ForDataPayloadTransfer(
+ const PayloadTransferFrame::PayloadHeader& header,
+ const PayloadTransferFrame::PayloadChunk& chunk) {
+ OfflineFrame frame;
+
+ frame.set_version(OfflineFrame::V1);
+ auto* v1_frame = frame.mutable_v1();
+ v1_frame->set_type(V1Frame::PAYLOAD_TRANSFER);
+ auto* sub_frame = v1_frame->mutable_payload_transfer();
+ sub_frame->set_packet_type(PayloadTransferFrame::DATA);
+ *sub_frame->mutable_payload_header() = header;
+ *sub_frame->mutable_payload_chunk() = chunk;
+
+ return ToBytes(std::move(frame));
+}
+
+ByteArray ForControlPayloadTransfer(
+ const PayloadTransferFrame::PayloadHeader& header,
+ const PayloadTransferFrame::ControlMessage& control) {
+ OfflineFrame frame;
+
+ frame.set_version(OfflineFrame::V1);
+ auto* v1_frame = frame.mutable_v1();
+ v1_frame->set_type(V1Frame::PAYLOAD_TRANSFER);
+ auto* sub_frame = v1_frame->mutable_payload_transfer();
+ sub_frame->set_packet_type(PayloadTransferFrame::CONTROL);
+ *sub_frame->mutable_payload_header() = header;
+ *sub_frame->mutable_control_message() = control;
+
+ return ToBytes(std::move(frame));
+}
+
+ByteArray ForBwuWifiHotspotPathAvailable(const std::string& ssid,
+ const std::string& password,
+ std::int32_t port,
+ const std::string& gateway,
+ bool supports_disabling_encryption) {
+ OfflineFrame frame;
+
+ frame.set_version(OfflineFrame::V1);
+ auto* v1_frame = frame.mutable_v1();
+ v1_frame->set_type(V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION);
+ auto* sub_frame = v1_frame->mutable_bandwidth_upgrade_negotiation();
+ sub_frame->set_event_type(
+ BandwidthUpgradeNegotiationFrame::UPGRADE_PATH_AVAILABLE);
+ auto* upgrade_path_info = sub_frame->mutable_upgrade_path_info();
+ upgrade_path_info->set_medium(UpgradePathInfo::WIFI_HOTSPOT);
+ upgrade_path_info->set_supports_client_introduction_ack(true);
+ upgrade_path_info->set_supports_disabling_encryption(
+ supports_disabling_encryption);
+ auto* wifi_hotspot_credentials =
+ upgrade_path_info->mutable_wifi_hotspot_credentials();
+ wifi_hotspot_credentials->set_ssid(ssid);
+ wifi_hotspot_credentials->set_password(password);
+ wifi_hotspot_credentials->set_port(port);
+ wifi_hotspot_credentials->set_gateway(gateway);
+
+ return ToBytes(std::move(frame));
+}
+
+ByteArray ForBwuWifiLanPathAvailable(const std::string& ip_address,
+ std::int32_t port) {
+ OfflineFrame frame;
+
+ frame.set_version(OfflineFrame::V1);
+ auto* v1_frame = frame.mutable_v1();
+ v1_frame->set_type(V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION);
+ auto* sub_frame = v1_frame->mutable_bandwidth_upgrade_negotiation();
+ sub_frame->set_event_type(
+ BandwidthUpgradeNegotiationFrame::UPGRADE_PATH_AVAILABLE);
+ auto* upgrade_path_info = sub_frame->mutable_upgrade_path_info();
+ upgrade_path_info->set_medium(UpgradePathInfo::WIFI_LAN);
+ upgrade_path_info->set_supports_client_introduction_ack(true);
+ auto* wifi_lan_socket = upgrade_path_info->mutable_wifi_lan_socket();
+ wifi_lan_socket->set_ip_address(ip_address);
+ wifi_lan_socket->set_wifi_port(port);
+
+ return ToBytes(std::move(frame));
+}
+
+ByteArray ForBwuWifiAwarePathAvailable(const std::string& service_id,
+ const std::string& service_info,
+ const std::string& password,
+ bool supports_disabling_encryption) {
+ OfflineFrame frame;
+
+ frame.set_version(OfflineFrame::V1);
+ auto* v1_frame = frame.mutable_v1();
+ v1_frame->set_type(V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION);
+ auto* sub_frame = v1_frame->mutable_bandwidth_upgrade_negotiation();
+ sub_frame->set_event_type(
+ BandwidthUpgradeNegotiationFrame::UPGRADE_PATH_AVAILABLE);
+ auto* upgrade_path_info = sub_frame->mutable_upgrade_path_info();
+ upgrade_path_info->set_medium(UpgradePathInfo::WIFI_AWARE);
+ upgrade_path_info->set_supports_client_introduction_ack(true);
+ upgrade_path_info->set_supports_disabling_encryption(
+ supports_disabling_encryption);
+ auto* wifi_aware_credentials =
+ upgrade_path_info->mutable_wifi_aware_credentials();
+ wifi_aware_credentials->set_service_id(service_id);
+ wifi_aware_credentials->set_service_info(service_info);
+ if (!password.empty()) wifi_aware_credentials->set_password(password);
+
+ return ToBytes(std::move(frame));
+}
+
+ByteArray ForBwuWifiDirectPathAvailable(const std::string& ssid,
+ const std::string& password,
+ std::int32_t port,
+ std::int32_t frequency,
+ bool supports_disabling_encryption) {
+ OfflineFrame frame;
+
+ frame.set_version(OfflineFrame::V1);
+ auto* v1_frame = frame.mutable_v1();
+ v1_frame->set_type(V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION);
+ auto* sub_frame = v1_frame->mutable_bandwidth_upgrade_negotiation();
+ sub_frame->set_event_type(
+ BandwidthUpgradeNegotiationFrame::UPGRADE_PATH_AVAILABLE);
+ auto* upgrade_path_info = sub_frame->mutable_upgrade_path_info();
+ upgrade_path_info->set_medium(UpgradePathInfo::WIFI_DIRECT);
+ upgrade_path_info->set_supports_client_introduction_ack(true);
+ upgrade_path_info->set_supports_disabling_encryption(
+ supports_disabling_encryption);
+ auto* wifi_direct_credentials =
+ upgrade_path_info->mutable_wifi_direct_credentials();
+ wifi_direct_credentials->set_ssid(ssid);
+ wifi_direct_credentials->set_password(password);
+ wifi_direct_credentials->set_port(port);
+ wifi_direct_credentials->set_frequency(frequency);
+
+ return ToBytes(std::move(frame));
+}
+
+ByteArray ForBwuBluetoothPathAvailable(const std::string& service_id,
+ const std::string& mac_address) {
+ OfflineFrame frame;
+
+ frame.set_version(OfflineFrame::V1);
+ auto* v1_frame = frame.mutable_v1();
+ v1_frame->set_type(V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION);
+ auto* sub_frame = v1_frame->mutable_bandwidth_upgrade_negotiation();
+ sub_frame->set_event_type(
+ BandwidthUpgradeNegotiationFrame::UPGRADE_PATH_AVAILABLE);
+ auto* upgrade_path_info = sub_frame->mutable_upgrade_path_info();
+ upgrade_path_info->set_medium(UpgradePathInfo::BLUETOOTH);
+ upgrade_path_info->set_supports_client_introduction_ack(true);
+ auto* bluetooth_credentials =
+ upgrade_path_info->mutable_bluetooth_credentials();
+ bluetooth_credentials->set_mac_address(mac_address);
+ bluetooth_credentials->set_service_name(service_id);
+
+ return ToBytes(std::move(frame));
+}
+
+ByteArray ForBwuWebrtcPathAvailable(const std::string& peer_id,
+ const LocationHint& location_hint) {
+ OfflineFrame frame;
+
+ frame.set_version(OfflineFrame::V1);
+ auto* v1_frame = frame.mutable_v1();
+ v1_frame->set_type(V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION);
+ auto* sub_frame = v1_frame->mutable_bandwidth_upgrade_negotiation();
+ sub_frame->set_event_type(
+ BandwidthUpgradeNegotiationFrame::UPGRADE_PATH_AVAILABLE);
+ auto* upgrade_path_info = sub_frame->mutable_upgrade_path_info();
+ upgrade_path_info->set_medium(UpgradePathInfo::WEB_RTC);
+ upgrade_path_info->set_supports_client_introduction_ack(true);
+ auto* webrtc_credentials = upgrade_path_info->mutable_web_rtc_credentials();
+ webrtc_credentials->set_peer_id(peer_id);
+ auto* local_location_hint = webrtc_credentials->mutable_location_hint();
+ *local_location_hint = location_hint;
+
+ return ToBytes(std::move(frame));
+}
+
+ByteArray ForBwuLastWrite() {
+ OfflineFrame frame;
+
+ frame.set_version(OfflineFrame::V1);
+ auto* v1_frame = frame.mutable_v1();
+ v1_frame->set_type(V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION);
+ auto* sub_frame = v1_frame->mutable_bandwidth_upgrade_negotiation();
+ sub_frame->set_event_type(
+ BandwidthUpgradeNegotiationFrame::LAST_WRITE_TO_PRIOR_CHANNEL);
+
+ return ToBytes(std::move(frame));
+}
+
+ByteArray ForBwuSafeToClose() {
+ OfflineFrame frame;
+
+ frame.set_version(OfflineFrame::V1);
+ auto* v1_frame = frame.mutable_v1();
+ v1_frame->set_type(V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION);
+ auto* sub_frame = v1_frame->mutable_bandwidth_upgrade_negotiation();
+ sub_frame->set_event_type(
+ BandwidthUpgradeNegotiationFrame::SAFE_TO_CLOSE_PRIOR_CHANNEL);
+
+ return ToBytes(std::move(frame));
+}
+
+ByteArray ForBwuIntroduction(const std::string& endpoint_id) {
+ OfflineFrame frame;
+
+ frame.set_version(OfflineFrame::V1);
+ auto* v1_frame = frame.mutable_v1();
+ v1_frame->set_type(V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION);
+ auto* sub_frame = v1_frame->mutable_bandwidth_upgrade_negotiation();
+ sub_frame->set_event_type(
+ BandwidthUpgradeNegotiationFrame::CLIENT_INTRODUCTION);
+ auto* client_introduction = sub_frame->mutable_client_introduction();
+ client_introduction->set_endpoint_id(endpoint_id);
+
+ return ToBytes(std::move(frame));
+}
+
+ByteArray ForBwuIntroductionAck() {
+ OfflineFrame frame;
+
+ frame.set_version(OfflineFrame::V1);
+ auto* v1_frame = frame.mutable_v1();
+ v1_frame->set_type(V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION);
+ auto* sub_frame = v1_frame->mutable_bandwidth_upgrade_negotiation();
+ sub_frame->set_event_type(
+ BandwidthUpgradeNegotiationFrame::CLIENT_INTRODUCTION_ACK);
+
+ return ToBytes(std::move(frame));
+}
+
+ByteArray ForBwuFailure(const UpgradePathInfo& info) {
+ OfflineFrame frame;
+
+ frame.set_version(OfflineFrame::V1);
+ auto* v1_frame = frame.mutable_v1();
+ v1_frame->set_type(V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION);
+ auto* sub_frame = v1_frame->mutable_bandwidth_upgrade_negotiation();
+ sub_frame->set_event_type(BandwidthUpgradeNegotiationFrame::UPGRADE_FAILURE);
+ auto* upgrade_path_info = sub_frame->mutable_upgrade_path_info();
+ *upgrade_path_info = info;
+
+ return ToBytes(std::move(frame));
+}
+
+ByteArray ForKeepAlive() {
+ OfflineFrame frame;
+
+ frame.set_version(OfflineFrame::V1);
+ auto* v1_frame = frame.mutable_v1();
+ v1_frame->set_type(V1Frame::KEEP_ALIVE);
+ v1_frame->mutable_keep_alive();
+
+ return ToBytes(std::move(frame));
+}
+
+ByteArray ForDisconnection() {
+ OfflineFrame frame;
+
+ frame.set_version(OfflineFrame::V1);
+ auto* v1_frame = frame.mutable_v1();
+ v1_frame->set_type(V1Frame::DISCONNECTION);
+ v1_frame->mutable_disconnection();
+
+ return ToBytes(std::move(frame));
+}
+
+UpgradePathInfo::Medium MediumToUpgradePathInfoMedium(Medium medium) {
+ switch (medium) {
+ case Medium::MDNS:
+ return UpgradePathInfo::MDNS;
+ case Medium::BLUETOOTH:
+ return UpgradePathInfo::BLUETOOTH;
+ case Medium::WIFI_HOTSPOT:
+ return UpgradePathInfo::WIFI_HOTSPOT;
+ case Medium::BLE:
+ return UpgradePathInfo::BLE;
+ case Medium::WIFI_LAN:
+ return UpgradePathInfo::WIFI_LAN;
+ case Medium::WIFI_AWARE:
+ return UpgradePathInfo::WIFI_AWARE;
+ case Medium::NFC:
+ return UpgradePathInfo::NFC;
+ case Medium::WIFI_DIRECT:
+ return UpgradePathInfo::WIFI_DIRECT;
+ case Medium::WEB_RTC:
+ return UpgradePathInfo::WEB_RTC;
+ default:
+ return UpgradePathInfo::UNKNOWN_MEDIUM;
+ }
+}
+
+Medium UpgradePathInfoMediumToMedium(UpgradePathInfo::Medium medium) {
+ switch (medium) {
+ case UpgradePathInfo::MDNS:
+ return Medium::MDNS;
+ case UpgradePathInfo::BLUETOOTH:
+ return Medium::BLUETOOTH;
+ case UpgradePathInfo::WIFI_HOTSPOT:
+ return Medium::WIFI_HOTSPOT;
+ case UpgradePathInfo::BLE:
+ return Medium::BLE;
+ case UpgradePathInfo::WIFI_LAN:
+ return Medium::WIFI_LAN;
+ case UpgradePathInfo::WIFI_AWARE:
+ return Medium::WIFI_AWARE;
+ case UpgradePathInfo::NFC:
+ return Medium::NFC;
+ case UpgradePathInfo::WIFI_DIRECT:
+ return Medium::WIFI_DIRECT;
+ case UpgradePathInfo::WEB_RTC:
+ return Medium::WEB_RTC;
+ default:
+ return Medium::UNKNOWN_MEDIUM;
+ }
+}
+
+ConnectionRequestFrame::Medium MediumToConnectionRequestMedium(Medium medium) {
+ switch (medium) {
+ case Medium::MDNS:
+ return ConnectionRequestFrame::MDNS;
+ case Medium::BLUETOOTH:
+ return ConnectionRequestFrame::BLUETOOTH;
+ case Medium::WIFI_HOTSPOT:
+ return ConnectionRequestFrame::WIFI_HOTSPOT;
+ case Medium::BLE:
+ return ConnectionRequestFrame::BLE;
+ case Medium::WIFI_LAN:
+ return ConnectionRequestFrame::WIFI_LAN;
+ case Medium::WIFI_AWARE:
+ return ConnectionRequestFrame::WIFI_AWARE;
+ case Medium::NFC:
+ return ConnectionRequestFrame::NFC;
+ case Medium::WIFI_DIRECT:
+ return ConnectionRequestFrame::WIFI_DIRECT;
+ case Medium::WEB_RTC:
+ return ConnectionRequestFrame::WEB_RTC;
+ default:
+ return ConnectionRequestFrame::UNKNOWN_MEDIUM;
+ }
+}
+
+Medium ConnectionRequestMediumToMedium(ConnectionRequestFrame::Medium medium) {
+ switch (medium) {
+ case ConnectionRequestFrame::MDNS:
+ return Medium::MDNS;
+ case ConnectionRequestFrame::BLUETOOTH:
+ return Medium::BLUETOOTH;
+ case ConnectionRequestFrame::WIFI_HOTSPOT:
+ return Medium::WIFI_HOTSPOT;
+ case ConnectionRequestFrame::BLE:
+ return Medium::BLE;
+ case ConnectionRequestFrame::WIFI_LAN:
+ return Medium::WIFI_LAN;
+ case ConnectionRequestFrame::WIFI_AWARE:
+ return Medium::WIFI_AWARE;
+ case ConnectionRequestFrame::NFC:
+ return Medium::NFC;
+ case ConnectionRequestFrame::WIFI_DIRECT:
+ return Medium::WIFI_DIRECT;
+ case ConnectionRequestFrame::WEB_RTC:
+ return Medium::WEB_RTC;
+ default:
+ return Medium::UNKNOWN_MEDIUM;
+ }
+}
+
+std::vector<Medium> ConnectionRequestMediumsToMediums(
+ const ConnectionRequestFrame& frame) {
+ std::vector<Medium> result;
+ for (const auto& int_medium : frame.mediums()) {
+ result.push_back(ConnectionRequestMediumToMedium(
+ static_cast<ConnectionRequestFrame::Medium>(int_medium)));
+ }
+ return result;
+}
+
+} // namespace parser
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/offline_frames.h b/chromium/third_party/nearby/src/connections/implementation/offline_frames.h
new file mode 100644
index 00000000000..3dc52290369
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/offline_frames.h
@@ -0,0 +1,105 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_OFFLINE_FRAMES_H_
+#define CORE_INTERNAL_OFFLINE_FRAMES_H_
+
+#include <cstdint>
+#include <vector>
+
+#include "connections/implementation/proto/offline_wire_formats.pb.h"
+#include "connections/connection_options.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/exception.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace parser {
+
+using UpgradePathInfo = BandwidthUpgradeNegotiationFrame::UpgradePathInfo;
+
+// Serialize/Deserialize Nearby Connections Protocol messages.
+
+// Parses incoming message.
+// Returns OfflineFrame if parser was able to understand it, or
+// Exception::kInvalidProtocolBuffer, if parser failed.
+ExceptionOr<OfflineFrame> FromBytes(const ByteArray& offline_frame_bytes);
+
+// Returns FrameType of a parsed message, or
+// V1Frame::UNKNOWN_FRAME_TYPE, if frame contents is not recognized.
+V1Frame::FrameType GetFrameType(const OfflineFrame& offline_frame);
+
+// Builds Connection Request / Response messages.
+ByteArray ForConnectionRequest(const std::string& endpoint_id,
+ const ByteArray& endpoint_info,
+ std::int32_t nonce, bool supports_5_ghz,
+ const std::string& bssid,
+ const std::vector<Medium>& mediums,
+ std::int32_t keep_alive_interval_millis,
+ std::int32_t keep_alive_timeout_millis);
+ByteArray ForConnectionResponse(std::int32_t status);
+
+// Builds Payload transfer messages.
+ByteArray ForDataPayloadTransfer(
+ const PayloadTransferFrame::PayloadHeader& header,
+ const PayloadTransferFrame::PayloadChunk& chunk);
+ByteArray ForControlPayloadTransfer(
+ const PayloadTransferFrame::PayloadHeader& header,
+ const PayloadTransferFrame::ControlMessage& control);
+
+// Builds Bandwidth Upgrade [BWU] messages.
+ByteArray ForBwuIntroduction(const std::string& endpoint_id);
+ByteArray ForBwuIntroductionAck();
+ByteArray ForBwuWifiHotspotPathAvailable(const std::string& ssid,
+ const std::string& password,
+ std::int32_t port,
+ const std::string& gateway,
+ bool supports_disabling_encryption);
+ByteArray ForBwuWifiLanPathAvailable(const std::string& ip_address,
+ std::int32_t port);
+ByteArray ForBwuWifiAwarePathAvailable(const std::string& service_id,
+ const std::string& service_info,
+ const std::string& password,
+ bool supports_disabling_encryption);
+ByteArray ForBwuWifiDirectPathAvailable(const std::string& ssid,
+ const std::string& password,
+ std::int32_t port,
+ std::int32_t frequency,
+ bool supports_disabling_encryption);
+ByteArray ForBwuBluetoothPathAvailable(const std::string& service_id,
+ const std::string& mac_address);
+ByteArray ForBwuWebrtcPathAvailable(const std::string& peer_id,
+ const LocationHint& location_hint_a);
+ByteArray ForBwuFailure(const UpgradePathInfo& info);
+ByteArray ForBwuLastWrite();
+ByteArray ForBwuSafeToClose();
+
+ByteArray ForKeepAlive();
+ByteArray ForDisconnection();
+
+UpgradePathInfo::Medium MediumToUpgradePathInfoMedium(Medium medium);
+Medium UpgradePathInfoMediumToMedium(UpgradePathInfo::Medium medium);
+
+ConnectionRequestFrame::Medium MediumToConnectionRequestMedium(Medium medium);
+Medium ConnectionRequestMediumToMedium(ConnectionRequestFrame::Medium medium);
+std::vector<Medium> ConnectionRequestMediumsToMediums(
+ const ConnectionRequestFrame& connection_request_frame);
+
+} // namespace parser
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_OFFLINE_FRAMES_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/offline_frames_test.cc b/chromium/third_party/nearby/src/connections/implementation/offline_frames_test.cc
new file mode 100644
index 00000000000..d34e431fcb7
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/offline_frames_test.cc
@@ -0,0 +1,394 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/offline_frames.h"
+
+#include <array>
+#include <memory>
+#include <utility>
+#include <vector>
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "absl/strings/string_view.h"
+#include "connections/implementation/proto/offline_wire_formats.pb.h"
+#include "internal/platform/byte_array.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace parser {
+namespace {
+
+using Medium = proto::connections::Medium;
+using ::protobuf_matchers::EqualsProto;
+
+constexpr absl::string_view kEndpointId{"ABC"};
+constexpr absl::string_view kEndpointName{"XYZ"};
+constexpr int kNonce = 1234;
+constexpr bool kSupports5ghz = true;
+constexpr absl::string_view kBssid{"FF:FF:FF:FF:FF:FF"};
+constexpr std::array<Medium, 9> kMediums = {
+ Medium::MDNS, Medium::BLUETOOTH, Medium::WIFI_HOTSPOT,
+ Medium::BLE, Medium::WIFI_LAN, Medium::WIFI_AWARE,
+ Medium::NFC, Medium::WIFI_DIRECT, Medium::WEB_RTC,
+};
+constexpr int kKeepAliveIntervalMillis = 1000;
+constexpr int kKeepAliveTimeoutMillis = 5000;
+
+TEST(OfflineFramesTest, CanParseMessageFromBytes) {
+ OfflineFrame tx_message;
+
+ {
+ tx_message.set_version(OfflineFrame::V1);
+ auto* v1_frame = tx_message.mutable_v1();
+ auto* sub_frame = v1_frame->mutable_connection_request();
+
+ v1_frame->set_type(V1Frame::CONNECTION_REQUEST);
+ // OSS matchers don't like implicitly comparing string_views to strings.
+ sub_frame->set_endpoint_id(std::string(kEndpointId));
+ sub_frame->set_endpoint_name(std::string(kEndpointName));
+ sub_frame->set_endpoint_info(std::string(kEndpointName));
+ sub_frame->set_nonce(kNonce);
+ sub_frame->set_keep_alive_interval_millis(kKeepAliveIntervalMillis);
+ sub_frame->set_keep_alive_timeout_millis(kKeepAliveTimeoutMillis);
+ auto* medium_metadata = sub_frame->mutable_medium_metadata();
+
+ medium_metadata->set_supports_5_ghz(kSupports5ghz);
+ medium_metadata->set_bssid(kBssid);
+
+ for (auto& medium : kMediums) {
+ sub_frame->add_mediums(MediumToConnectionRequestMedium(medium));
+ }
+ }
+ auto serialized_bytes = ByteArray(tx_message.SerializeAsString());
+ auto ret_value = FromBytes(serialized_bytes);
+ ASSERT_TRUE(ret_value.ok());
+ const auto& rx_message = ret_value.result();
+ EXPECT_THAT(rx_message, EqualsProto(tx_message));
+ EXPECT_EQ(GetFrameType(rx_message), V1Frame::CONNECTION_REQUEST);
+ EXPECT_EQ(
+ ConnectionRequestMediumsToMediums(rx_message.v1().connection_request()),
+ std::vector(kMediums.begin(), kMediums.end()));
+}
+
+TEST(OfflineFramesTest, CanGenerateConnectionRequest) {
+ constexpr char kExpected[] =
+ R"pb(
+ version: V1
+ v1: <
+ type: CONNECTION_REQUEST
+ connection_request: <
+ endpoint_id: "ABC"
+ endpoint_name: "XYZ"
+ endpoint_info: "XYZ"
+ nonce: 1234
+ medium_metadata: < supports_5_ghz: true bssid: "FF:FF:FF:FF:FF:FF" >
+ mediums: MDNS
+ mediums: BLUETOOTH
+ mediums: WIFI_HOTSPOT
+ mediums: BLE
+ mediums: WIFI_LAN
+ mediums: WIFI_AWARE
+ mediums: NFC
+ mediums: WIFI_DIRECT
+ mediums: WEB_RTC
+ keep_alive_interval_millis: 1000
+ keep_alive_timeout_millis: 5000
+ >
+ >)pb";
+ ByteArray bytes = ForConnectionRequest(
+ std::string(kEndpointId), ByteArray{std::string(kEndpointName)}, kNonce,
+ kSupports5ghz, std::string(kBssid),
+ std::vector(kMediums.begin(), kMediums.end()), kKeepAliveIntervalMillis,
+ kKeepAliveTimeoutMillis);
+ auto response = FromBytes(bytes);
+ ASSERT_TRUE(response.ok());
+ OfflineFrame message = FromBytes(bytes).result();
+ EXPECT_THAT(message, EqualsProto(kExpected));
+}
+
+TEST(OfflineFramesTest, CanGenerateConnectionResponse) {
+ constexpr char kExpected[] =
+ R"pb(
+ version: V1
+ v1: <
+ type: CONNECTION_RESPONSE
+ connection_response: < status: 1 response: REJECT >
+ >)pb";
+ ByteArray bytes = ForConnectionResponse(1);
+ auto response = FromBytes(bytes);
+ ASSERT_TRUE(response.ok());
+ OfflineFrame message = FromBytes(bytes).result();
+ EXPECT_THAT(message, EqualsProto(kExpected));
+}
+
+TEST(OfflineFramesTest, CanGenerateControlPayloadTransfer) {
+ PayloadTransferFrame::PayloadHeader header;
+ PayloadTransferFrame::ControlMessage control;
+ header.set_id(12345);
+ header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
+ header.set_total_size(1024);
+ control.set_event(PayloadTransferFrame::ControlMessage::PAYLOAD_CANCELED);
+ control.set_offset(150);
+
+ constexpr char kExpected[] =
+ R"pb(
+ version: V1
+ v1: <
+ type: PAYLOAD_TRANSFER
+ payload_transfer: <
+ packet_type: CONTROL,
+ payload_header: < type: BYTES id: 12345 total_size: 1024 >
+ control_message: < event: PAYLOAD_CANCELED offset: 150 >
+ >
+ >)pb";
+ ByteArray bytes = ForControlPayloadTransfer(header, control);
+ auto response = FromBytes(bytes);
+ ASSERT_TRUE(response.ok());
+ OfflineFrame message = FromBytes(bytes).result();
+ EXPECT_THAT(message, EqualsProto(kExpected));
+}
+
+TEST(OfflineFramesTest, CanGenerateDataPayloadTransfer) {
+ PayloadTransferFrame::PayloadHeader header;
+ PayloadTransferFrame::PayloadChunk chunk;
+ header.set_id(12345);
+ header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
+ header.set_total_size(1024);
+ chunk.set_body("payload data");
+ chunk.set_offset(150);
+ chunk.set_flags(1);
+
+ constexpr char kExpected[] =
+ R"pb(
+ version: V1
+ v1: <
+ type: PAYLOAD_TRANSFER
+ payload_transfer: <
+ packet_type: DATA,
+ payload_header: < type: BYTES id: 12345 total_size: 1024 >
+ payload_chunk: < flags: 1 offset: 150 body: "payload data" >
+ >
+ >)pb";
+ ByteArray bytes = ForDataPayloadTransfer(header, chunk);
+ auto response = FromBytes(bytes);
+ ASSERT_TRUE(response.ok());
+ OfflineFrame message = FromBytes(bytes).result();
+ EXPECT_THAT(message, EqualsProto(kExpected));
+}
+
+TEST(OfflineFramesTest, CanGenerateBwuWifiHotspotPathAvailable) {
+ constexpr char kExpected[] =
+ R"pb(
+ version: V1
+ v1: <
+ type: BANDWIDTH_UPGRADE_NEGOTIATION
+ bandwidth_upgrade_negotiation: <
+ event_type: UPGRADE_PATH_AVAILABLE
+ upgrade_path_info: <
+ medium: WIFI_HOTSPOT
+ wifi_hotspot_credentials: <
+ ssid: "ssid"
+ password: "password"
+ port: 1234
+ gateway: "0.0.0.0"
+ >
+ supports_disabling_encryption: false
+ supports_client_introduction_ack: true
+ >
+ >
+ >)pb";
+ ByteArray bytes = ForBwuWifiHotspotPathAvailable("ssid", "password", 1234,
+ "0.0.0.0", false);
+ auto response = FromBytes(bytes);
+ ASSERT_TRUE(response.ok());
+ OfflineFrame message = FromBytes(bytes).result();
+ EXPECT_THAT(message, EqualsProto(kExpected));
+}
+
+TEST(OfflineFramesTest, CanGenerateBwuWifiLanPathAvailable) {
+ constexpr char kExpected[] =
+ R"pb(
+ version: V1
+ v1: <
+ type: BANDWIDTH_UPGRADE_NEGOTIATION
+ bandwidth_upgrade_negotiation: <
+ event_type: UPGRADE_PATH_AVAILABLE
+ upgrade_path_info: <
+ medium: WIFI_LAN
+ wifi_lan_socket: < ip_address: "\x01\x02\x03\x04" wifi_port: 1234 >
+ supports_client_introduction_ack: true
+ >
+ >
+ >)pb";
+ ByteArray bytes = ForBwuWifiLanPathAvailable("\x01\x02\x03\x04", 1234);
+ auto response = FromBytes(bytes);
+ ASSERT_TRUE(response.ok());
+ OfflineFrame message = FromBytes(bytes).result();
+ EXPECT_THAT(message, EqualsProto(kExpected));
+}
+
+TEST(OfflineFramesTest, CanGenerateBwuWifiAwarePathAvailable) {
+ constexpr char kExpected[] =
+ R"pb(
+ version: V1
+ v1: <
+ type: BANDWIDTH_UPGRADE_NEGOTIATION
+ bandwidth_upgrade_negotiation: <
+ event_type: UPGRADE_PATH_AVAILABLE
+ upgrade_path_info: <
+ medium: WIFI_AWARE
+ wifi_aware_credentials: <
+ service_id: "service_id"
+ service_info: "service_info"
+ password: "password"
+ >
+ supports_disabling_encryption: false
+ supports_client_introduction_ack: true
+ >
+ >
+ >)pb";
+ ByteArray bytes = ForBwuWifiAwarePathAvailable("service_id", "service_info",
+ "password", false);
+ auto response = FromBytes(bytes);
+ ASSERT_TRUE(response.ok());
+ OfflineFrame message = FromBytes(bytes).result();
+ EXPECT_THAT(message, EqualsProto(kExpected));
+}
+
+TEST(OfflineFramesTest, CanGenerateBwuWifiDirectPathAvailable) {
+ constexpr char kExpected[] =
+ R"pb(
+ version: V1
+ v1: <
+ type: BANDWIDTH_UPGRADE_NEGOTIATION
+ bandwidth_upgrade_negotiation: <
+ event_type: UPGRADE_PATH_AVAILABLE
+ upgrade_path_info: <
+ medium: WIFI_DIRECT
+ wifi_direct_credentials: <
+ ssid: "DIRECT-A0-0123456789AB"
+ password: "password"
+ port: 1000
+ frequency: 1000
+ >
+ supports_disabling_encryption: false
+ supports_client_introduction_ack: true
+ >
+ >
+ >)pb";
+ ByteArray bytes = ForBwuWifiDirectPathAvailable(
+ "DIRECT-A0-0123456789AB", "password", 1000, 1000, false);
+ auto response = FromBytes(bytes);
+ ASSERT_TRUE(response.ok());
+ OfflineFrame message = FromBytes(bytes).result();
+ EXPECT_THAT(message, EqualsProto(kExpected));
+}
+
+TEST(OfflineFramesTest, CanGenerateBwuBluetoothPathAvailable) {
+ constexpr char kExpected[] =
+ R"pb(
+ version: V1
+ v1: <
+ type: BANDWIDTH_UPGRADE_NEGOTIATION
+ bandwidth_upgrade_negotiation: <
+ event_type: UPGRADE_PATH_AVAILABLE
+ upgrade_path_info: <
+ medium: BLUETOOTH
+ bluetooth_credentials: <
+ service_name: "service"
+ mac_address: "\x11\x22\x33\x44\x55\x66"
+ >
+ supports_client_introduction_ack: true
+ >
+ >
+ >)pb";
+ ByteArray bytes =
+ ForBwuBluetoothPathAvailable("service", "\x11\x22\x33\x44\x55\x66");
+ auto response = FromBytes(bytes);
+ ASSERT_TRUE(response.ok());
+ OfflineFrame message = FromBytes(bytes).result();
+ EXPECT_THAT(message, EqualsProto(kExpected));
+}
+
+TEST(OfflineFramesTest, CanGenerateBwuLastWrite) {
+ constexpr char kExpected[] =
+ R"pb(
+ version: V1
+ v1: <
+ type: BANDWIDTH_UPGRADE_NEGOTIATION
+ bandwidth_upgrade_negotiation: < event_type: LAST_WRITE_TO_PRIOR_CHANNEL >
+ >)pb";
+ ByteArray bytes = ForBwuLastWrite();
+ auto response = FromBytes(bytes);
+ ASSERT_TRUE(response.ok());
+ OfflineFrame message = FromBytes(bytes).result();
+ EXPECT_THAT(message, EqualsProto(kExpected));
+}
+
+TEST(OfflineFramesTest, CanGenerateBwuSafeToClose) {
+ constexpr char kExpected[] =
+ R"pb(
+ version: V1
+ v1: <
+ type: BANDWIDTH_UPGRADE_NEGOTIATION
+ bandwidth_upgrade_negotiation: < event_type: SAFE_TO_CLOSE_PRIOR_CHANNEL >
+ >)pb";
+ ByteArray bytes = ForBwuSafeToClose();
+ auto response = FromBytes(bytes);
+ ASSERT_TRUE(response.ok());
+ OfflineFrame message = FromBytes(bytes).result();
+ EXPECT_THAT(message, EqualsProto(kExpected));
+}
+
+TEST(OfflineFramesTest, CanGenerateBwuIntroduction) {
+ constexpr char kExpected[] =
+ R"pb(
+ version: V1
+ v1: <
+ type: BANDWIDTH_UPGRADE_NEGOTIATION
+ bandwidth_upgrade_negotiation: <
+ event_type: CLIENT_INTRODUCTION
+ client_introduction: < endpoint_id: "ABC" >
+ >
+ >)pb";
+ ByteArray bytes = ForBwuIntroduction(std::string(kEndpointId));
+ auto response = FromBytes(bytes);
+ ASSERT_TRUE(response.ok());
+ OfflineFrame message = FromBytes(bytes).result();
+ EXPECT_THAT(message, EqualsProto(kExpected));
+}
+
+TEST(OfflineFramesTest, CanGenerateKeepAlive) {
+ constexpr char kExpected[] =
+ R"pb(
+ version: V1
+ v1: <
+ type: KEEP_ALIVE
+ keep_alive: <>
+ >)pb";
+ ByteArray bytes = ForKeepAlive();
+ auto response = FromBytes(bytes);
+ ASSERT_TRUE(response.ok());
+ OfflineFrame message = FromBytes(bytes).result();
+ EXPECT_THAT(message, EqualsProto(kExpected));
+}
+
+} // namespace
+} // namespace parser
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/offline_frames_validator.cc b/chromium/third_party/nearby/src/connections/implementation/offline_frames_validator.cc
new file mode 100644
index 00000000000..00260f55c1f
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/offline_frames_validator.cc
@@ -0,0 +1,381 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/offline_frames_validator.h"
+
+#include <regex> //NOLINT
+
+#include "connections/implementation/proto/offline_wire_formats.pb.h"
+#include "connections/implementation/internal_payload.h"
+#include "connections/implementation/offline_frames.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace parser {
+namespace {
+
+using PayloadChunk = PayloadTransferFrame::PayloadChunk;
+using ControlMessage = PayloadTransferFrame::ControlMessage;
+using ClientIntroduction = BandwidthUpgradeNegotiationFrame::ClientIntroduction;
+using WifiHotspotCredentials = UpgradePathInfo::WifiHotspotCredentials;
+using WifiLanSocket = UpgradePathInfo::WifiLanSocket;
+using WifiAwareCredentials = UpgradePathInfo::WifiAwareCredentials;
+using WifiDirectCredentials = UpgradePathInfo::WifiDirectCredentials;
+using BluetoothCredentials = UpgradePathInfo::BluetoothCredentials;
+using WebRtcCredentials = UpgradePathInfo::WebRtcCredentials;
+using Medium = location::nearby::connections::Medium;
+
+constexpr absl::string_view kIpv4PatternString{
+ "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
+ "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
+ "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
+ "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"};
+constexpr absl::string_view kIpv6PatternString{
+ "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
+ "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
+ "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
+ "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
+ "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
+ "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"};
+constexpr absl::string_view kWifiDirectSsidPatternString{
+ "^DIRECT-[a-zA-Z0-9]{2}.*$"};
+constexpr int kWifiDirectSsidMaxLength = 32;
+constexpr int kWifiPasswordSsidMinLength = 8;
+constexpr int kWifiPasswordSsidMaxLength = 64;
+
+inline bool WithinRange(int value, int min, int max) {
+ return value >= min && value < max;
+}
+
+Exception EnsureValidConnectionRequestFrame(
+ const ConnectionRequestFrame& frame) {
+ if (!frame.has_endpoint_id()) return {Exception::kInvalidProtocolBuffer};
+ if (!frame.has_endpoint_name()) return {Exception::kInvalidProtocolBuffer};
+
+ // For backwards compatibility reasons, no other fields should be
+ // null-checked for this frame. Parameter checking (eg. must be within this
+ // range) is fine.
+ return {Exception::kSuccess};
+}
+
+Exception EnsureValidConnectionResponseFrame(
+ const ConnectionResponseFrame& frame) {
+ // For backwards compatibility reasons, no other fields should be null-checked
+ // for this frame. Parameter checking (eg. must be within this range) is fine.
+ return {Exception::kSuccess};
+}
+
+Exception EnsureValidPayloadTransferDataFrame(const PayloadChunk& payload_chunk,
+ std::int64_t totalSize) {
+ if (!payload_chunk.has_flags()) return {Exception::kInvalidProtocolBuffer};
+
+ // Special case. The body can be null iff the chunk is flagged as the last
+ // chunk.
+ bool is_last_chunk = (payload_chunk.flags() &
+ PayloadTransferFrame::PayloadChunk::LAST_CHUNK) != 0;
+ if (!payload_chunk.has_body() && !is_last_chunk)
+ return {Exception::kInvalidProtocolBuffer};
+ if (!payload_chunk.has_offset() || payload_chunk.offset() < 0)
+ return {Exception::kInvalidProtocolBuffer};
+ if (totalSize != InternalPayload::kIndeterminateSize &&
+ totalSize < payload_chunk.offset()) {
+ return {Exception::kInvalidProtocolBuffer};
+ }
+
+ // For backwards compatibility reasons, no other fields should be null-checked
+ // for this frame. Parameter checking (eg. must be within this range) is fine.
+ return {Exception::kSuccess};
+}
+
+Exception EnsureValidPayloadTransferControlFrame(
+ const ControlMessage& control_message, std::int64_t totalSize) {
+ if (!control_message.has_offset() || control_message.offset() < 0)
+ return {Exception::kInvalidProtocolBuffer};
+ if (totalSize != InternalPayload::kIndeterminateSize &&
+ totalSize < control_message.offset()) {
+ return {Exception::kInvalidProtocolBuffer};
+ }
+
+ // For backwards compatibility reasons, no other fields should be null-checked
+ // for this frame. Parameter checking (eg. must be within this range) is fine.
+ return {Exception::kSuccess};
+}
+
+Exception EnsureValidPayloadTransferFrame(const PayloadTransferFrame& frame) {
+ if (!frame.has_payload_header()) return {Exception::kInvalidProtocolBuffer};
+ if (!frame.payload_header().has_total_size() ||
+ (frame.payload_header().total_size() < 0 &&
+ frame.payload_header().total_size() !=
+ InternalPayload::kIndeterminateSize))
+ return {Exception::kInvalidProtocolBuffer};
+ if (!frame.has_packet_type()) return {Exception::kInvalidProtocolBuffer};
+
+ switch (frame.packet_type()) {
+ case PayloadTransferFrame::DATA:
+ if (frame.has_payload_chunk()) {
+ return EnsureValidPayloadTransferDataFrame(
+ frame.payload_chunk(), frame.payload_header().total_size());
+ }
+ return {Exception::kInvalidProtocolBuffer};
+
+ case PayloadTransferFrame::CONTROL:
+ if (frame.has_control_message()) {
+ return EnsureValidPayloadTransferControlFrame(
+ frame.control_message(), frame.payload_header().total_size());
+ }
+ return {Exception::kInvalidProtocolBuffer};
+
+ default:
+ break;
+ }
+
+ // For backwards compatibility reasons, no other fields should be null-checked
+ // for this frame. Parameter checking (eg. must be within this range) is fine.
+ return {Exception::kSuccess};
+}
+
+Exception EnsureValidBandwidthUpgradeWifiHotspotPathAvailableFrame(
+ const WifiHotspotCredentials& wifi_hotspot_credentials) {
+ if (!wifi_hotspot_credentials.has_ssid())
+ return {Exception::kInvalidProtocolBuffer};
+ if (!wifi_hotspot_credentials.has_password() ||
+ !WithinRange(wifi_hotspot_credentials.password().length(),
+ kWifiPasswordSsidMinLength, kWifiPasswordSsidMaxLength))
+ return {Exception::kInvalidProtocolBuffer};
+ if (!wifi_hotspot_credentials.has_gateway())
+ return {Exception::kInvalidProtocolBuffer};
+ const std::regex ip4_pattern(std::string(kIpv4PatternString).c_str());
+ const std::regex ip6_pattern(std::string(kIpv6PatternString).c_str());
+ if (!(std::regex_match(wifi_hotspot_credentials.gateway(), ip4_pattern) ||
+ std::regex_match(wifi_hotspot_credentials.gateway(), ip6_pattern)))
+ return {Exception::kInvalidProtocolBuffer};
+
+ // For backwards compatibility reasons, no other fields should be null-checked
+ // for this frame. Parameter checking (eg. must be within this range) is fine.
+ return {Exception::kSuccess};
+}
+
+Exception EnsureValidBandwidthUpgradeWifiLanPathAvailableFrame(
+ const WifiLanSocket& wifi_lan_socket) {
+ if (!wifi_lan_socket.has_ip_address())
+ return {Exception::kInvalidProtocolBuffer};
+ if (!wifi_lan_socket.has_wifi_port() || wifi_lan_socket.wifi_port() < 0)
+ return {Exception::kInvalidProtocolBuffer};
+
+ // For backwards compatibility reasons, no other fields should be null-checked
+ // for this frame. Parameter checking (eg. must be within this range) is fine.
+ return {Exception::kSuccess};
+}
+
+Exception EnsureValidBandwidthUpgradeWifiAwarePathAvailableFrame(
+ const WifiAwareCredentials& wifi_aware_credentials) {
+ if (!wifi_aware_credentials.has_service_id())
+ return {Exception::kInvalidProtocolBuffer};
+ if (!wifi_aware_credentials.has_service_info())
+ return {Exception::kInvalidProtocolBuffer};
+
+ // For backwards compatibility reasons, no other fields should be null-checked
+ // for this frame. Parameter checking (eg. must be within this range) is fine.
+ return {Exception::kSuccess};
+}
+
+Exception EnsureValidBandwidthUpgradeWifiDirectPathAvailableFrame(
+ const WifiDirectCredentials& wifi_direct_credentials) {
+ const std::regex ssid_pattern(
+ std::string(kWifiDirectSsidPatternString).c_str());
+ if (!wifi_direct_credentials.has_ssid() ||
+ !(wifi_direct_credentials.ssid().length() < kWifiDirectSsidMaxLength &&
+ std::regex_match(wifi_direct_credentials.ssid(), ssid_pattern)))
+ return {Exception::kInvalidProtocolBuffer};
+
+ if (!wifi_direct_credentials.has_password() ||
+ !WithinRange(wifi_direct_credentials.password().length(),
+ kWifiPasswordSsidMinLength, kWifiPasswordSsidMaxLength))
+ return {Exception::kInvalidProtocolBuffer};
+
+ if (!wifi_direct_credentials.has_frequency() ||
+ wifi_direct_credentials.frequency() < -1)
+ return {Exception::kInvalidProtocolBuffer};
+
+ // For backwards compatibility reasons, no other fields should be null-checked
+ // for this frame. Parameter checking (eg. must be within this range) is fine.
+ return {Exception::kSuccess};
+}
+
+Exception EnsureValidBandwidthUpgradeBluetoothPathAvailableFrame(
+ const BluetoothCredentials& bluetooth_credentials) {
+ if (!bluetooth_credentials.has_service_name())
+ return {Exception::kInvalidProtocolBuffer};
+ if (!bluetooth_credentials.has_mac_address())
+ return {Exception::kInvalidProtocolBuffer};
+
+ // For backwards compatibility reasons, no other fields should be null-checked
+ // for this frame. Parameter checking (eg. must be within this range) is fine.
+ return {Exception::kSuccess};
+}
+
+Exception EnsureValidBandwidthUpgradeWebRtcPathAvailableFrame(
+ const WebRtcCredentials& web_rtc_credentials) {
+ if (!web_rtc_credentials.has_peer_id())
+ return {Exception::kInvalidProtocolBuffer};
+
+ // For backwards compatibility reasons, no other fields should be null-checked
+ // for this frame. Parameter checking (eg. must be within this range) is fine.
+ return {Exception::kSuccess};
+}
+
+Exception EnsureValidBandwidthUpgradePathAvailableFrame(
+ const UpgradePathInfo& upgrade_path_info) {
+ if (!upgrade_path_info.has_medium())
+ return {Exception::kInvalidProtocolBuffer};
+ switch (static_cast<Medium>(upgrade_path_info.medium())) {
+ case Medium::WIFI_HOTSPOT:
+ if (upgrade_path_info.has_wifi_hotspot_credentials()) {
+ return EnsureValidBandwidthUpgradeWifiHotspotPathAvailableFrame(
+ upgrade_path_info.wifi_hotspot_credentials());
+ }
+ return {Exception::kInvalidProtocolBuffer};
+
+ case Medium::WIFI_LAN:
+ if (upgrade_path_info.has_wifi_lan_socket()) {
+ return EnsureValidBandwidthUpgradeWifiLanPathAvailableFrame(
+ upgrade_path_info.wifi_lan_socket());
+ }
+ return {Exception::kInvalidProtocolBuffer};
+
+ case Medium::WIFI_AWARE:
+ if (upgrade_path_info.has_wifi_aware_credentials()) {
+ return EnsureValidBandwidthUpgradeWifiAwarePathAvailableFrame(
+ upgrade_path_info.wifi_aware_credentials());
+ }
+ return {Exception::kInvalidProtocolBuffer};
+
+ case Medium::WIFI_DIRECT:
+ if (upgrade_path_info.has_wifi_direct_credentials()) {
+ return EnsureValidBandwidthUpgradeWifiDirectPathAvailableFrame(
+ upgrade_path_info.wifi_direct_credentials());
+ }
+ return {Exception::kInvalidProtocolBuffer};
+
+ case Medium::BLUETOOTH:
+ if (upgrade_path_info.has_bluetooth_credentials()) {
+ return EnsureValidBandwidthUpgradeBluetoothPathAvailableFrame(
+ upgrade_path_info.bluetooth_credentials());
+ }
+ return {Exception::kInvalidProtocolBuffer};
+
+ case Medium::WEB_RTC:
+ if (upgrade_path_info.has_web_rtc_credentials()) {
+ return EnsureValidBandwidthUpgradeWebRtcPathAvailableFrame(
+ upgrade_path_info.web_rtc_credentials());
+ }
+ return {Exception::kInvalidProtocolBuffer};
+
+ default:
+ break;
+ }
+
+ // For backwards compatibility reasons, no other fields should be null-checked
+ // for this frame. Parameter checking (eg. must be within this range) is fine.
+ return {Exception::kSuccess};
+}
+
+Exception EnsureValidBandwidthUpgradeClientIntroductionFrame(
+ const ClientIntroduction& client_introduction) {
+ if (!client_introduction.has_endpoint_id())
+ return {Exception::kInvalidProtocolBuffer};
+
+ // For backwards compatibility reasons, no other fields should be null-checked
+ // for this frame. Parameter checking (eg. must be within this range) is fine.
+ return {Exception::kSuccess};
+}
+
+Exception EnsureValidBandwidthUpgradeNegotiationFrame(
+ const BandwidthUpgradeNegotiationFrame& frame) {
+ if (!frame.has_event_type()) return {Exception::kInvalidProtocolBuffer};
+
+ switch (frame.event_type()) {
+ case BandwidthUpgradeNegotiationFrame::UPGRADE_PATH_AVAILABLE:
+ if (frame.has_upgrade_path_info()) {
+ return EnsureValidBandwidthUpgradePathAvailableFrame(
+ frame.upgrade_path_info());
+ }
+ return {Exception::kInvalidProtocolBuffer};
+
+ case BandwidthUpgradeNegotiationFrame::CLIENT_INTRODUCTION:
+ if (frame.has_client_introduction()) {
+ return EnsureValidBandwidthUpgradeClientIntroductionFrame(
+ frame.client_introduction());
+ }
+ return {Exception::kInvalidProtocolBuffer};
+
+ default:
+ break;
+ }
+
+ // For backwards compatibility reasons, no other fields should be null-checked
+ // for this frame. Parameter checking (eg. must be within this range) is fine.
+ return {Exception::kSuccess};
+}
+
+} // namespace
+
+Exception EnsureValidOfflineFrame(const OfflineFrame& offline_frame) {
+ V1Frame::FrameType frame_type = GetFrameType(offline_frame);
+ switch (frame_type) {
+ case V1Frame::CONNECTION_REQUEST:
+ if (offline_frame.has_v1() &&
+ offline_frame.v1().has_connection_request()) {
+ return EnsureValidConnectionRequestFrame(
+ offline_frame.v1().connection_request());
+ }
+ return {Exception::kInvalidProtocolBuffer};
+
+ case V1Frame::CONNECTION_RESPONSE:
+ if (offline_frame.has_v1() &&
+ offline_frame.v1().has_connection_response()) {
+ return EnsureValidConnectionResponseFrame(
+ offline_frame.v1().connection_response());
+ }
+ return {Exception::kInvalidProtocolBuffer};
+
+ case V1Frame::PAYLOAD_TRANSFER:
+ if (offline_frame.has_v1() && offline_frame.v1().has_payload_transfer()) {
+ return EnsureValidPayloadTransferFrame(
+ offline_frame.v1().payload_transfer());
+ }
+ return {Exception::kInvalidProtocolBuffer};
+
+ case V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION:
+ if (offline_frame.has_v1() &&
+ offline_frame.v1().has_bandwidth_upgrade_negotiation()) {
+ return EnsureValidBandwidthUpgradeNegotiationFrame(
+ offline_frame.v1().bandwidth_upgrade_negotiation());
+ }
+ return {Exception::kInvalidProtocolBuffer};
+
+ case V1Frame::KEEP_ALIVE:
+ case V1Frame::UNKNOWN_FRAME_TYPE:
+ default:
+ // Nothing to check for these frames.
+ break;
+ }
+ return {Exception::kSuccess};
+}
+
+} // namespace parser
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/offline_frames_validator.h b/chromium/third_party/nearby/src/connections/implementation/offline_frames_validator.h
new file mode 100644
index 00000000000..14a5de757a2
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/offline_frames_validator.h
@@ -0,0 +1,33 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_OFFLINE_FRAMES_VALIDATOR_H_
+#define CORE_INTERNAL_OFFLINE_FRAMES_VALIDATOR_H_
+
+#include "connections/implementation/proto/offline_wire_formats.pb.h"
+#include "internal/platform/exception.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace parser {
+
+Exception EnsureValidOfflineFrame(const OfflineFrame& offline_frame);
+
+} // namespace parser
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_OFFLINE_FRAMES_VALIDATOR_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/offline_frames_validator_test.cc b/chromium/third_party/nearby/src/connections/implementation/offline_frames_validator_test.cc
new file mode 100644
index 00000000000..3e069733fa3
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/offline_frames_validator_test.cc
@@ -0,0 +1,569 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/offline_frames_validator.h"
+
+#include <string>
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "absl/strings/string_view.h"
+#include "connections/implementation/proto/offline_wire_formats.pb.h"
+#include "connections/implementation/offline_frames.h"
+#include "internal/platform/byte_array.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace parser {
+namespace {
+
+constexpr absl::string_view kEndpointId{"ABC"};
+constexpr absl::string_view kEndpointName{"XYZ"};
+constexpr int kNonce = 1234;
+constexpr bool kSupports5ghz = true;
+constexpr absl::string_view kBssid{"FF:FF:FF:FF:FF:FF"};
+constexpr int kStatusAccepted = 0;
+constexpr absl::string_view kSsid = "ssid";
+constexpr absl::string_view kPassword = "password";
+constexpr absl::string_view kWifiHotspotGateway = "0.0.0.0";
+constexpr absl::string_view kWifiDirectSsid = "DIRECT-A0-0123456789AB";
+constexpr absl::string_view kWifiDirectPassword = "WIFIDIRECT123456";
+constexpr int kWifiDirectFrequency = 1000;
+constexpr int kPort = 1000;
+constexpr bool kSupportsDisablingEncryption = true;
+constexpr std::array<Medium, 9> kMediums = {
+ Medium::MDNS, Medium::BLUETOOTH, Medium::WIFI_HOTSPOT,
+ Medium::BLE, Medium::WIFI_LAN, Medium::WIFI_AWARE,
+ Medium::NFC, Medium::WIFI_DIRECT, Medium::WEB_RTC,
+};
+constexpr int kKeepAliveIntervalMillis = 1000;
+constexpr int kKeepAliveTimeoutMillis = 5000;
+
+TEST(OfflineFramesValidatorTest, ValidatesAsOkWithValidConnectionRequestFrame) {
+ OfflineFrame offline_frame;
+
+ ByteArray bytes = ForConnectionRequest(
+ std::string(kEndpointId), ByteArray{std::string(kEndpointName)}, kNonce,
+ kSupports5ghz, std::string(kBssid),
+ std::vector(kMediums.begin(), kMediums.end()), kKeepAliveIntervalMillis,
+ kKeepAliveTimeoutMillis);
+ offline_frame.ParseFromString(std::string(bytes));
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame);
+
+ ASSERT_TRUE(ret_value.Ok());
+}
+
+TEST(OfflineFramesValidatorTest,
+ ValidatesAsFailWithNullConnectionRequestFrame) {
+ OfflineFrame offline_frame;
+
+ ByteArray bytes = ForConnectionRequest(
+ std::string(kEndpointId), ByteArray{std::string(kEndpointName)}, kNonce,
+ kSupports5ghz, std::string(kBssid),
+ std::vector(kMediums.begin(), kMediums.end()), kKeepAliveIntervalMillis,
+ kKeepAliveTimeoutMillis);
+ offline_frame.ParseFromString(std::string(bytes));
+ auto* v1_frame = offline_frame.mutable_v1();
+
+ v1_frame->clear_connection_request();
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame);
+
+ ASSERT_FALSE(ret_value.Ok());
+}
+
+TEST(OfflineFramesValidatorTest,
+ ValidatesAsFailWithNullEndpointIdInConnectionRequestFrame) {
+ OfflineFrame offline_frame;
+
+ std::string empty_enpoint_id;
+ ByteArray bytes = ForConnectionRequest(
+ empty_enpoint_id, ByteArray{std::string(kEndpointName)}, kNonce,
+ kSupports5ghz, std::string(kBssid),
+ std::vector(kMediums.begin(), kMediums.end()), kKeepAliveIntervalMillis,
+ kKeepAliveTimeoutMillis);
+ offline_frame.ParseFromString(std::string(bytes));
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame);
+
+ ASSERT_FALSE(ret_value.Ok());
+}
+
+TEST(OfflineFramesValidatorTest,
+ ValidatesAsFailWithNullEndpointInfoInConnectionRequestFrame) {
+ OfflineFrame offline_frame;
+
+ ByteArray empty_endpoint_info;
+ ByteArray bytes = ForConnectionRequest(
+ std::string(kEndpointId), empty_endpoint_info, kNonce, kSupports5ghz,
+ std::string(kBssid), std::vector(kMediums.begin(), kMediums.end()),
+ kKeepAliveIntervalMillis, kKeepAliveTimeoutMillis);
+ offline_frame.ParseFromString(std::string(bytes));
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame);
+
+ ASSERT_FALSE(ret_value.Ok());
+}
+
+TEST(OfflineFramesValidatorTest,
+ ValidatesAsOkWithNullBssidInConnectionRequestFrame) {
+ OfflineFrame offline_frame;
+
+ std::string empty_bssid;
+ ByteArray bytes = ForConnectionRequest(
+ std::string(kEndpointId), ByteArray{std::string(kEndpointName)}, kNonce,
+ kSupports5ghz, empty_bssid, std::vector(kMediums.begin(), kMediums.end()),
+ kKeepAliveIntervalMillis, kKeepAliveTimeoutMillis);
+ offline_frame.ParseFromString(std::string(bytes));
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame);
+
+ ASSERT_TRUE(ret_value.Ok());
+}
+
+TEST(OfflineFramesValidatorTest,
+ ValidatesAsOkWithNullMediumsInConnectionRequestFrame) {
+ OfflineFrame offline_frame;
+
+ std::vector<Medium> empty_mediums;
+ ByteArray bytes = ForConnectionRequest(
+ std::string(kEndpointId), ByteArray{std::string(kEndpointName)}, kNonce,
+ kSupports5ghz, std::string(kBssid), empty_mediums,
+ kKeepAliveIntervalMillis, kKeepAliveTimeoutMillis);
+ offline_frame.ParseFromString(std::string(bytes));
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame);
+
+ ASSERT_TRUE(ret_value.Ok());
+}
+
+TEST(OfflineFramesValidatorTest,
+ ValidatesAsOkWithValidConnectionResponseFrame) {
+ OfflineFrame offline_frame;
+
+ ByteArray bytes = ForConnectionResponse(kStatusAccepted);
+ offline_frame.ParseFromString(std::string(bytes));
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame);
+
+ ASSERT_TRUE(ret_value.Ok());
+}
+
+TEST(OfflineFramesValidatorTest,
+ ValidatesAsFailWithNullConnectionResponseFrame) {
+ OfflineFrame offline_frame;
+
+ ByteArray bytes = ForConnectionResponse(kStatusAccepted);
+ offline_frame.ParseFromString(std::string(bytes));
+ auto* v1_frame = offline_frame.mutable_v1();
+
+ v1_frame->clear_connection_response();
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame);
+
+ ASSERT_FALSE(ret_value.Ok());
+}
+
+TEST(OfflineFramesValidatorTest,
+ ValidatesAsFailWithUnexpectedStatusInConnectionResponseFrame) {
+ OfflineFrame offline_frame;
+
+ ByteArray bytes = ForConnectionResponse(-1);
+ offline_frame.ParseFromString(std::string(bytes));
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame);
+
+ // To maintain forward compatibility, we allow unexpected status codes.
+ ASSERT_TRUE(ret_value.Ok());
+}
+
+TEST(OfflineFramesValidatorTest, ValidatesAsOkWithValidPayloadTransferFrame) {
+ PayloadTransferFrame::PayloadHeader header;
+ PayloadTransferFrame::PayloadChunk chunk;
+ header.set_id(12345);
+ header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
+ // Sending files larger than 2gb was previously broken (see cl/372382338).
+ // This tests a file larger than int max.
+ header.set_total_size(3e10);
+ chunk.set_body("payload data");
+ chunk.set_offset(150);
+ chunk.set_flags(1);
+
+ OfflineFrame offline_frame;
+
+ ByteArray bytes = ForDataPayloadTransfer(header, chunk);
+ offline_frame.ParseFromString(std::string(bytes));
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame);
+
+ ASSERT_TRUE(ret_value.Ok());
+}
+
+TEST(OfflineFramesValidatorTest, ValidatesAsFailWithNullPayloadTransferFrame) {
+ PayloadTransferFrame::PayloadHeader header;
+ PayloadTransferFrame::PayloadChunk chunk;
+ chunk.set_body("payload data");
+ chunk.set_offset(150);
+ chunk.set_flags(1);
+
+ OfflineFrame offline_frame;
+
+ ByteArray bytes = ForDataPayloadTransfer(header, chunk);
+ offline_frame.ParseFromString(std::string(bytes));
+ auto* v1_frame = offline_frame.mutable_v1();
+
+ v1_frame->clear_payload_transfer();
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame);
+
+ ASSERT_FALSE(ret_value.Ok());
+}
+
+TEST(OfflineFramesValidatorTest,
+ ValidatesAsFailWithNullPayloadHeaderInPayloadTransferFrame) {
+ PayloadTransferFrame::PayloadHeader header;
+ PayloadTransferFrame::PayloadChunk chunk;
+ header.set_id(12345);
+ header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
+ header.set_total_size(1024);
+ chunk.set_body("payload data");
+ chunk.set_offset(150);
+ chunk.set_flags(1);
+
+ OfflineFrame offline_frame;
+
+ ByteArray bytes = ForDataPayloadTransfer(header, chunk);
+ offline_frame.ParseFromString(std::string(bytes));
+ auto* v1_frame = offline_frame.mutable_v1();
+ auto* payload_transfer = v1_frame->mutable_payload_transfer();
+
+ payload_transfer->clear_payload_header();
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame);
+
+ ASSERT_FALSE(ret_value.Ok());
+}
+
+TEST(OfflineFramesValidatorTest,
+ ValidatesAsFailWithInvalidSizeInPayloadHeader) {
+ PayloadTransferFrame::PayloadHeader header;
+ PayloadTransferFrame::PayloadChunk chunk;
+ header.set_id(12345);
+ header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
+ header.set_total_size(-5);
+ chunk.set_body("payload data");
+ chunk.set_offset(150);
+ chunk.set_flags(1);
+
+ OfflineFrame offline_frame;
+
+ ByteArray bytes = ForDataPayloadTransfer(header, chunk);
+ offline_frame.ParseFromString(std::string(bytes));
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame);
+
+ ASSERT_FALSE(ret_value.Ok());
+}
+
+TEST(OfflineFramesValidatorTest,
+ ValidatesAsFailWithNullPayloadChunkInPayloadTransferFrame) {
+ PayloadTransferFrame::PayloadHeader header;
+ PayloadTransferFrame::PayloadChunk chunk;
+ header.set_id(12345);
+ header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
+ header.set_total_size(1024);
+ chunk.set_body("payload data");
+ chunk.set_offset(150);
+ chunk.set_flags(1);
+
+ OfflineFrame offline_frame;
+
+ ByteArray bytes = ForDataPayloadTransfer(header, chunk);
+ offline_frame.ParseFromString(std::string(bytes));
+ auto* v1_frame = offline_frame.mutable_v1();
+ auto* payload_transfer = v1_frame->mutable_payload_transfer();
+
+ payload_transfer->clear_payload_chunk();
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame);
+
+ ASSERT_FALSE(ret_value.Ok());
+}
+
+TEST(OfflineFramesValidatorTest,
+ ValidatesAsFailWithInvalidOffsetInPayloadChunk) {
+ PayloadTransferFrame::PayloadHeader header;
+ PayloadTransferFrame::PayloadChunk chunk;
+ header.set_id(12345);
+ header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
+ header.set_total_size(1024);
+ chunk.set_body("payload data");
+ chunk.set_offset(-1);
+ chunk.set_flags(1);
+
+ OfflineFrame offline_frame;
+
+ ByteArray bytes = ForDataPayloadTransfer(header, chunk);
+ offline_frame.ParseFromString(std::string(bytes));
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame);
+
+ ASSERT_FALSE(ret_value.Ok());
+}
+
+TEST(OfflineFramesValidatorTest,
+ ValidatesAsFailWithInvalidLargeOffsetInPayloadChunk) {
+ PayloadTransferFrame::PayloadHeader header;
+ PayloadTransferFrame::PayloadChunk chunk;
+ header.set_id(12345);
+ header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
+ header.set_total_size(1024);
+ chunk.set_body("payload data");
+ chunk.set_offset(4999);
+ chunk.set_flags(1);
+
+ OfflineFrame offline_frame;
+
+ ByteArray bytes = ForDataPayloadTransfer(header, chunk);
+ offline_frame.ParseFromString(std::string(bytes));
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame);
+
+ ASSERT_FALSE(ret_value.Ok());
+}
+
+TEST(OfflineFramesValidatorTest,
+ ValidatesAsFailWithInvalidFlagsInPayloadChunk) {
+ PayloadTransferFrame::PayloadHeader header;
+ PayloadTransferFrame::PayloadChunk chunk;
+ header.set_id(12345);
+ header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
+ header.set_total_size(1024);
+ chunk.set_body("payload data");
+ chunk.set_offset(150);
+ chunk.set_flags(1);
+
+ OfflineFrame offline_frame;
+
+ ByteArray bytes = ForDataPayloadTransfer(header, chunk);
+ offline_frame.ParseFromString(std::string(bytes));
+ auto* v1_frame = offline_frame.mutable_v1();
+ auto* payload_transfer = v1_frame->mutable_payload_transfer();
+ auto* payload_chunk = payload_transfer->mutable_payload_chunk();
+
+ payload_chunk->clear_flags();
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame);
+
+ ASSERT_FALSE(ret_value.Ok());
+}
+
+TEST(OfflineFramesValidatorTest,
+ ValidatesAsFailWithNullControlMessageInPayloadTransferFrame) {
+ PayloadTransferFrame::PayloadHeader header;
+ PayloadTransferFrame::ControlMessage control;
+ header.set_id(12345);
+ header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
+ header.set_total_size(1024);
+ control.set_event(PayloadTransferFrame::ControlMessage::PAYLOAD_CANCELED);
+ control.set_offset(150);
+
+ OfflineFrame offline_frame;
+
+ ByteArray bytes = ForControlPayloadTransfer(header, control);
+ offline_frame.ParseFromString(std::string(bytes));
+
+ auto* v1_frame = offline_frame.mutable_v1();
+ auto* payload_transfer = v1_frame->mutable_payload_transfer();
+
+ payload_transfer->clear_control_message();
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame);
+
+ ASSERT_FALSE(ret_value.Ok());
+}
+
+TEST(OfflineFramesValidatorTest,
+ ValidatesAsFailWithInvalidNegativeOffsetInControlMessage) {
+ PayloadTransferFrame::PayloadHeader header;
+ PayloadTransferFrame::ControlMessage control;
+ header.set_id(12345);
+ header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
+ header.set_total_size(1024);
+ control.set_event(PayloadTransferFrame::ControlMessage::PAYLOAD_CANCELED);
+ control.set_offset(-1);
+
+ OfflineFrame offline_frame;
+
+ ByteArray bytes = ForControlPayloadTransfer(header, control);
+ offline_frame.ParseFromString(std::string(bytes));
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame);
+
+ ASSERT_FALSE(ret_value.Ok());
+}
+
+TEST(OfflineFramesValidatorTest,
+ ValidatesAsFailWithInvalidLargeOffsetInControlMessage) {
+ PayloadTransferFrame::PayloadHeader header;
+ PayloadTransferFrame::ControlMessage control;
+ header.set_id(12345);
+ header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
+ header.set_total_size(1024);
+ control.set_event(PayloadTransferFrame::ControlMessage::PAYLOAD_CANCELED);
+ control.set_offset(4999);
+
+ OfflineFrame offline_frame;
+
+ ByteArray bytes = ForControlPayloadTransfer(header, control);
+ offline_frame.ParseFromString(std::string(bytes));
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame);
+
+ ASSERT_FALSE(ret_value.Ok());
+}
+
+TEST(OfflineFramesValidatorTest,
+ ValidatesAsOkWithValidBandwidthUpgradeNegotiationFrame) {
+ OfflineFrame offline_frame;
+
+ ByteArray bytes = ForBwuWifiHotspotPathAvailable(
+ std::string(kSsid), std::string(kPassword), kPort,
+ std::string(kWifiHotspotGateway), kSupportsDisablingEncryption);
+ offline_frame.ParseFromString(std::string(bytes));
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame);
+
+ ASSERT_TRUE(ret_value.Ok());
+}
+
+TEST(OfflineFramesValidatorTest,
+ ValidatesAsFailWithNullBandwidthUpgradeNegotiationFrame) {
+ OfflineFrame offline_frame;
+
+ ByteArray bytes = ForBwuWifiHotspotPathAvailable(
+ std::string(kSsid), std::string(kPassword), kPort,
+ std::string(kWifiHotspotGateway), kSupportsDisablingEncryption);
+ offline_frame.ParseFromString(std::string(bytes));
+ auto* v1_frame = offline_frame.mutable_v1();
+
+ v1_frame->clear_bandwidth_upgrade_negotiation();
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame);
+
+ ASSERT_FALSE(ret_value.Ok());
+}
+
+TEST(OfflineFramesValidatorTest, ValidatesAsOkBandwidthUpgradeWifiDirect) {
+ OfflineFrame offline_frame;
+
+ ByteArray bytes = ForBwuWifiDirectPathAvailable(
+ std::string(kWifiDirectSsid), std::string(kWifiDirectPassword), kPort,
+ kWifiDirectFrequency, kSupportsDisablingEncryption);
+ offline_frame.ParseFromString(std::string(bytes));
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame);
+
+ ASSERT_TRUE(ret_value.Ok());
+}
+
+TEST(OfflineFramesValidatorTest,
+ ValidatesValidFrequencyInBandwidthUpgradeWifiDirect) {
+ OfflineFrame offline_frame_1;
+ OfflineFrame offline_frame_2;
+
+ // Anything less than -1 is invalid
+ ByteArray bytes = ForBwuWifiDirectPathAvailable(
+ std::string(kWifiDirectSsid), std::string(kWifiDirectPassword), kPort, -2,
+ kSupportsDisablingEncryption);
+ offline_frame_1.ParseFromString(std::string(bytes));
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame_1);
+
+ ASSERT_FALSE(ret_value.Ok());
+
+ // But -1 itself is not invalid
+ bytes = ForBwuWifiDirectPathAvailable(std::string(kWifiDirectSsid),
+ std::string(kWifiDirectPassword), kPort,
+ -1, kSupportsDisablingEncryption);
+ offline_frame_2.ParseFromString(std::string(bytes));
+
+ ret_value = EnsureValidOfflineFrame(offline_frame_2);
+
+ ASSERT_TRUE(ret_value.Ok());
+}
+
+TEST(OfflineFramesValidatorTest,
+ ValidatesAsFailWithInvalidSsidInBandwidthUpgradeWifiDirect) {
+ OfflineFrame offline_frame_1;
+ OfflineFrame offline_frame_2;
+
+ std::string wifi_direct_ssid{"DIRECT-A*-0123456789AB"};
+ ByteArray bytes = ForBwuWifiDirectPathAvailable(
+ wifi_direct_ssid, std::string(kWifiDirectPassword), kPort,
+ kWifiDirectFrequency, kSupportsDisablingEncryption);
+ offline_frame_1.ParseFromString(std::string(bytes));
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame_1);
+
+ ASSERT_FALSE(ret_value.Ok());
+
+ std::string wifi_direct_ssid_wrong_length =
+ std::string{kWifiDirectSsid} + "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
+ bytes = ForBwuWifiDirectPathAvailable(
+ wifi_direct_ssid_wrong_length, std::string(kWifiDirectPassword), kPort,
+ kWifiDirectFrequency, kSupportsDisablingEncryption);
+ offline_frame_2.ParseFromString(std::string(bytes));
+
+ ret_value = EnsureValidOfflineFrame(offline_frame_2);
+
+ ASSERT_FALSE(ret_value.Ok());
+}
+
+TEST(OfflineFramesValidatorTest,
+ ValidatesAsFailWithInvalidPasswordInBandwidthUpgradeWifiDirect) {
+ OfflineFrame offline_frame_1;
+ OfflineFrame offline_frame_2;
+
+ std::string short_wifi_direct_password{"Test"};
+ ByteArray bytes = ForBwuWifiDirectPathAvailable(
+ std::string(kWifiDirectSsid), short_wifi_direct_password, kPort,
+ kWifiDirectFrequency, kSupportsDisablingEncryption);
+ offline_frame_1.ParseFromString(std::string(bytes));
+
+ auto ret_value = EnsureValidOfflineFrame(offline_frame_1);
+
+ ASSERT_FALSE(ret_value.Ok());
+
+ std::string long_wifi_direct_password =
+ std::string{kWifiDirectSsid} +
+ "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789";
+ bytes = ForBwuWifiDirectPathAvailable(
+ std::string(kWifiDirectSsid), long_wifi_direct_password, kPort,
+ kWifiDirectFrequency, kSupportsDisablingEncryption);
+ offline_frame_2.ParseFromString(std::string(bytes));
+
+ ret_value = EnsureValidOfflineFrame(offline_frame_2);
+
+ ASSERT_FALSE(ret_value.Ok());
+}
+
+} // namespace
+} // namespace parser
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/offline_service_controller.cc b/chromium/third_party/nearby/src/connections/implementation/offline_service_controller.cc
new file mode 100644
index 00000000000..ccecbee2d00
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/offline_service_controller.cc
@@ -0,0 +1,147 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/offline_service_controller.h"
+
+#include <string>
+
+#include "absl/strings/str_join.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+OfflineServiceController::~OfflineServiceController() { Stop(); }
+
+void OfflineServiceController::Stop() {
+ NEARBY_LOGS(INFO) << "Initiating shutdown of OfflineServiceController.";
+ if (stop_.Set(true)) return;
+ payload_manager_.DisconnectFromEndpointManager();
+ pcp_manager_.DisconnectFromEndpointManager();
+ NEARBY_LOGS(INFO) << "OfflineServiceController has shut down.";
+}
+
+Status OfflineServiceController::StartAdvertising(
+ ClientProxy* client, const std::string& service_id,
+ const AdvertisingOptions& advertising_options,
+ const ConnectionRequestInfo& info) {
+ if (stop_) return {Status::kOutOfOrderApiCall};
+ NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
+ << " requested advertising to start.";
+ return pcp_manager_.StartAdvertising(client, service_id, advertising_options,
+ info);
+}
+
+void OfflineServiceController::StopAdvertising(ClientProxy* client) {
+ if (stop_) return;
+ NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
+ << " requested advertising to stop.";
+ pcp_manager_.StopAdvertising(client);
+}
+
+Status OfflineServiceController::StartDiscovery(
+ ClientProxy* client, const std::string& service_id,
+ const DiscoveryOptions& discovery_options,
+ const DiscoveryListener& listener) {
+ if (stop_) return {Status::kOutOfOrderApiCall};
+ NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
+ << " requested discovery to start.";
+ return pcp_manager_.StartDiscovery(client, service_id, discovery_options,
+ listener);
+}
+
+void OfflineServiceController::StopDiscovery(ClientProxy* client) {
+ if (stop_) return;
+ NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
+ << " requested discovery to stop.";
+ pcp_manager_.StopDiscovery(client);
+}
+
+void OfflineServiceController::InjectEndpoint(
+ ClientProxy* client, const std::string& service_id,
+ const OutOfBandConnectionMetadata& metadata) {
+ if (stop_) return;
+ pcp_manager_.InjectEndpoint(client, service_id, metadata);
+}
+
+Status OfflineServiceController::RequestConnection(
+ ClientProxy* client, const std::string& endpoint_id,
+ const ConnectionRequestInfo& info,
+ const ConnectionOptions& connection_options) {
+ if (stop_) return {Status::kOutOfOrderApiCall};
+ NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
+ << " requested a connection to endpoint_id=" << endpoint_id;
+ return pcp_manager_.RequestConnection(client, endpoint_id, info,
+ connection_options);
+}
+
+Status OfflineServiceController::AcceptConnection(
+ ClientProxy* client, const std::string& endpoint_id,
+ const PayloadListener& listener) {
+ if (stop_) return {Status::kOutOfOrderApiCall};
+ NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
+ << " accepted the connection with endpoint_id="
+ << endpoint_id;
+ return pcp_manager_.AcceptConnection(client, endpoint_id, listener);
+}
+
+Status OfflineServiceController::RejectConnection(
+ ClientProxy* client, const std::string& endpoint_id) {
+ if (stop_) return {Status::kOutOfOrderApiCall};
+ NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
+ << " rejected the connection with endpoint_id="
+ << endpoint_id;
+ return pcp_manager_.RejectConnection(client, endpoint_id);
+}
+
+void OfflineServiceController::InitiateBandwidthUpgrade(
+ ClientProxy* client, const std::string& endpoint_id) {
+ if (stop_) return;
+ NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
+ << " initiated a manual bandwidth upgrade with endpoint_id="
+ << endpoint_id;
+ bwu_manager_.InitiateBwuForEndpoint(client, endpoint_id);
+}
+
+void OfflineServiceController::SendPayload(
+ ClientProxy* client, const std::vector<std::string>& endpoint_ids,
+ Payload payload) {
+ if (stop_) return;
+ NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
+ << " is sending payload_id=" << payload.GetId()
+ << " to endpoint_ids={" << absl::StrJoin(endpoint_ids, ",")
+ << "}";
+ payload_manager_.SendPayload(client, endpoint_ids, std::move(payload));
+}
+
+Status OfflineServiceController::CancelPayload(ClientProxy* client,
+ std::int64_t payload_id) {
+ if (stop_) return {Status::kOutOfOrderApiCall};
+ NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
+ << " cancelled payload_id=" << payload_id;
+ return payload_manager_.CancelPayload(client, payload_id);
+}
+
+void OfflineServiceController::DisconnectFromEndpoint(
+ ClientProxy* client, const std::string& endpoint_id) {
+ if (stop_) return;
+ NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
+ << " requested a disconnection from endpoint_id="
+ << endpoint_id;
+ endpoint_manager_.UnregisterEndpoint(client, endpoint_id);
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/offline_service_controller.h b/chromium/third_party/nearby/src/connections/implementation/offline_service_controller.h
new file mode 100644
index 00000000000..5c9de7b3656
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/offline_service_controller.h
@@ -0,0 +1,100 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_OFFLINE_SERVICE_CONTROLLER_H_
+#define CORE_INTERNAL_OFFLINE_SERVICE_CONTROLLER_H_
+
+#include <cstdint>
+#include <string>
+#include <vector>
+
+#include "connections/implementation/bwu_manager.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/endpoint_channel_manager.h"
+#include "connections/implementation/endpoint_manager.h"
+#include "connections/implementation/injected_bluetooth_device_store.h"
+#include "connections/implementation/mediums/mediums.h"
+#include "connections/implementation/payload_manager.h"
+#include "connections/implementation/pcp_manager.h"
+#include "connections/implementation/service_controller.h"
+#include "connections/listeners.h"
+#include "connections/payload.h"
+#include "connections/status.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+class OfflineServiceController : public ServiceController {
+ public:
+ OfflineServiceController() = default;
+ ~OfflineServiceController() override;
+
+ Status StartAdvertising(ClientProxy* client, const std::string& service_id,
+ const AdvertisingOptions& advertising_options,
+ const ConnectionRequestInfo& info) override;
+
+ void StopAdvertising(ClientProxy* client) override;
+
+ Status StartDiscovery(ClientProxy* client, const std::string& service_id,
+ const DiscoveryOptions& discovery_options,
+ const DiscoveryListener& listener) override;
+ void StopDiscovery(ClientProxy* client) override;
+
+ void InjectEndpoint(ClientProxy* client, const std::string& service_id,
+ const OutOfBandConnectionMetadata& metadata) override;
+
+ Status RequestConnection(
+ ClientProxy* client, const std::string& endpoint_id,
+ const ConnectionRequestInfo& info,
+ const ConnectionOptions& connection_options) override;
+ Status AcceptConnection(ClientProxy* client, const std::string& endpoint_id,
+ const PayloadListener& listener) override;
+ Status RejectConnection(ClientProxy* client,
+ const std::string& endpoint_id) override;
+
+ void InitiateBandwidthUpgrade(ClientProxy* client,
+ const std::string& endpoint_id) override;
+
+ void SendPayload(ClientProxy* client,
+ const std::vector<std::string>& endpoint_ids,
+ Payload payload) override;
+ Status CancelPayload(ClientProxy* client, Payload::Id payload_id) override;
+
+ void DisconnectFromEndpoint(ClientProxy* client,
+ const std::string& endpoint_id) override;
+
+ void Stop() override;
+
+ private:
+ // Note that the order of declaration of these is crucial, because we depend
+ // on the destructors running (strictly) in the reverse order; a deviation
+ // from that will lead to crashes at runtime.
+ AtomicBoolean stop_{false};
+ Mediums mediums_;
+ EndpointChannelManager channel_manager_;
+ EndpointManager endpoint_manager_{&channel_manager_};
+ PayloadManager payload_manager_{endpoint_manager_};
+ BwuManager bwu_manager_{
+ mediums_, endpoint_manager_, channel_manager_, {}, {}};
+ InjectedBluetoothDeviceStore injected_bluetooth_device_store_;
+ PcpManager pcp_manager_{mediums_, channel_manager_, endpoint_manager_,
+ bwu_manager_, injected_bluetooth_device_store_};
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_OFFLINE_SERVICE_CONTROLLER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/offline_service_controller_test.cc b/chromium/third_party/nearby/src/connections/implementation/offline_service_controller_test.cc
new file mode 100644
index 00000000000..78ff4e6ee14
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/offline_service_controller_test.cc
@@ -0,0 +1,389 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/offline_service_controller.h"
+
+#include <array>
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "connections/implementation/offline_simulation_user.h"
+#include "internal/platform/medium_environment.h"
+#include "internal/platform/output_stream.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/pipe.h"
+#include "internal/platform/system_clock.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+
+using ::testing::Eq;
+
+constexpr std::array<char, 6> kFakeMacAddress = {'a', 'b', 'c', 'd', 'e', 'f'};
+constexpr absl::string_view kServiceId = "service-id";
+constexpr absl::string_view kDeviceA = "device-a";
+constexpr absl::string_view kDeviceB = "device-b";
+constexpr absl::string_view kMessage = "message";
+constexpr absl::Duration kProgressTimeout = absl::Milliseconds(1500);
+constexpr absl::Duration kDefaultTimeout = absl::Milliseconds(1500);
+constexpr absl::Duration kDisconnectTimeout = absl::Milliseconds(15000);
+
+constexpr BooleanMediumSelector kTestCases[] = {
+ BooleanMediumSelector{
+ .bluetooth = true,
+ },
+ BooleanMediumSelector{
+ .wifi_lan = true,
+ },
+ BooleanMediumSelector{
+ .bluetooth = true,
+ .wifi_lan = true,
+ },
+};
+
+class OfflineServiceControllerTest
+ : public ::testing::TestWithParam<BooleanMediumSelector> {
+ protected:
+ OfflineServiceControllerTest() { env_.Stop(); }
+
+ bool SetupConnection(OfflineSimulationUser& user_a,
+ OfflineSimulationUser& user_b) {
+ user_a.StartAdvertising(std::string(kServiceId), &connect_latch_);
+ user_b.StartDiscovery(std::string(kServiceId), &discover_latch_);
+ EXPECT_TRUE(discover_latch_.Await(kDefaultTimeout).result());
+ EXPECT_EQ(user_b.GetDiscovered().service_id, kServiceId);
+ EXPECT_EQ(user_b.GetDiscovered().endpoint_info, user_a.GetInfo());
+ EXPECT_FALSE(user_b.GetDiscovered().endpoint_id.empty());
+ NEARBY_LOG(INFO, "EP-B: [discovered] %s",
+ user_b.GetDiscovered().endpoint_id.c_str());
+ user_b.RequestConnection(&connect_latch_);
+ EXPECT_TRUE(connect_latch_.Await(kDefaultTimeout).result());
+ EXPECT_FALSE(user_a.GetDiscovered().endpoint_id.empty());
+ NEARBY_LOG(INFO, "EP-A: [discovered] %s",
+ user_a.GetDiscovered().endpoint_id.c_str());
+ NEARBY_LOG(INFO, "Both users discovered their peers.");
+ user_a.AcceptConnection(&accept_latch_);
+ user_b.AcceptConnection(&accept_latch_);
+ EXPECT_TRUE(accept_latch_.Await(kDefaultTimeout).result());
+ NEARBY_LOG(INFO, "Both users reached connected state.");
+ return user_a.IsConnected() && user_b.IsConnected();
+ }
+
+ CountDownLatch discover_latch_{1};
+ CountDownLatch lost_latch_{1};
+ CountDownLatch connect_latch_{2};
+ CountDownLatch accept_latch_{2};
+ CountDownLatch payload_latch_{1};
+ MediumEnvironment& env_ = MediumEnvironment::Instance();
+};
+
+TEST_P(OfflineServiceControllerTest, CanCreateOne) {
+ env_.Start();
+ OfflineSimulationUser user_a(kDeviceA, GetParam());
+ env_.Stop();
+}
+
+TEST_P(OfflineServiceControllerTest, CanCreateMany) {
+ env_.Start();
+ OfflineSimulationUser user_a(kDeviceA, GetParam());
+ OfflineSimulationUser user_b(kDeviceB, GetParam());
+ env_.Stop();
+}
+
+TEST_P(OfflineServiceControllerTest, CanStartAdvertising) {
+ env_.Start();
+ OfflineSimulationUser user_a(kDeviceA, GetParam());
+ OfflineSimulationUser user_b(kDeviceB, GetParam());
+ EXPECT_FALSE(user_a.IsAdvertising());
+ EXPECT_THAT(user_a.StartAdvertising(std::string(kServiceId), nullptr),
+ Eq(Status{Status::kSuccess}));
+ EXPECT_TRUE(user_a.IsAdvertising());
+ env_.Stop();
+}
+
+TEST_P(OfflineServiceControllerTest, CanStartDiscoveryBeforeAdvertising) {
+ env_.Start();
+ OfflineSimulationUser user_a(kDeviceA, GetParam());
+ OfflineSimulationUser user_b(kDeviceB, GetParam());
+ EXPECT_FALSE(user_b.IsDiscovering());
+ EXPECT_THAT(user_b.StartDiscovery(std::string(kServiceId), &discover_latch_),
+ Eq(Status{Status::kSuccess}));
+ EXPECT_TRUE(user_b.IsDiscovering());
+ EXPECT_THAT(user_a.StartAdvertising(std::string(kServiceId), nullptr),
+ Eq(Status{Status::kSuccess}));
+ EXPECT_TRUE(discover_latch_.Await(kDefaultTimeout).result());
+ user_a.Stop();
+ user_b.Stop();
+ env_.Stop();
+}
+
+TEST_P(OfflineServiceControllerTest, CanStartDiscoveryAfterAdvertising) {
+ env_.Start();
+ OfflineSimulationUser user_a(kDeviceA, GetParam());
+ OfflineSimulationUser user_b(kDeviceB, GetParam());
+ EXPECT_FALSE(user_b.IsDiscovering());
+ EXPECT_FALSE(user_b.IsAdvertising());
+ EXPECT_THAT(user_a.StartAdvertising(std::string(kServiceId), nullptr),
+ Eq(Status{Status::kSuccess}));
+ EXPECT_THAT(user_b.StartDiscovery(std::string(kServiceId), &discover_latch_),
+ Eq(Status{Status::kSuccess}));
+ EXPECT_TRUE(user_a.IsAdvertising());
+ EXPECT_TRUE(user_b.IsDiscovering());
+ EXPECT_TRUE(discover_latch_.Await(kDefaultTimeout).result());
+ user_a.Stop();
+ user_b.Stop();
+ env_.Stop();
+}
+
+TEST_P(OfflineServiceControllerTest, CanStopAdvertising) {
+ env_.Start();
+ OfflineSimulationUser user_a(kDeviceA, GetParam());
+ OfflineSimulationUser user_b(kDeviceB, GetParam());
+ EXPECT_FALSE(user_a.IsAdvertising());
+ EXPECT_THAT(user_a.StartAdvertising(std::string(kServiceId), nullptr),
+ Eq(Status{Status::kSuccess}));
+ EXPECT_TRUE(user_a.IsAdvertising());
+ user_a.StopAdvertising();
+ EXPECT_FALSE(user_a.IsAdvertising());
+ EXPECT_THAT(user_b.StartDiscovery(std::string(kServiceId), &discover_latch_,
+ &lost_latch_),
+ Eq(Status{Status::kSuccess}));
+ EXPECT_TRUE(user_b.IsDiscovering());
+ auto discover_none = discover_latch_.Await(kDefaultTimeout).GetResult();
+ if (!discover_none) {
+ EXPECT_TRUE(true);
+ } else {
+ // There are rare cases (1/1000) that advertisment data has been captured by
+ // discovery device before advertising is stopped. So we need to check if
+ // lost_cb has grabbed the event in the end to prove the advertising service
+ // is stopped.
+ EXPECT_TRUE(lost_latch_.Await(kDefaultTimeout).result());
+ }
+ user_a.Stop();
+ user_b.Stop();
+ env_.Stop();
+}
+
+TEST_P(OfflineServiceControllerTest, CanStopDiscovery) {
+ env_.Start();
+ OfflineSimulationUser user_a(kDeviceA, GetParam());
+ OfflineSimulationUser user_b(kDeviceB, GetParam());
+ EXPECT_FALSE(user_b.IsDiscovering());
+ EXPECT_THAT(user_b.StartDiscovery(std::string(kServiceId), &discover_latch_),
+ Eq(Status{Status::kSuccess}));
+ EXPECT_TRUE(user_b.IsDiscovering());
+ user_b.StopDiscovery();
+ EXPECT_FALSE(user_b.IsDiscovering());
+ EXPECT_THAT(user_a.StartAdvertising(std::string(kServiceId), nullptr),
+ Eq(Status{Status::kSuccess}));
+ EXPECT_FALSE(discover_latch_.Await(kDefaultTimeout).result());
+ user_a.Stop();
+ user_b.Stop();
+ env_.Stop();
+}
+
+TEST_P(OfflineServiceControllerTest, CanConnect) {
+ env_.Start();
+ OfflineSimulationUser user_a(kDeviceA, GetParam());
+ OfflineSimulationUser user_b(kDeviceB, GetParam());
+ EXPECT_THAT(user_a.StartAdvertising(std::string(kServiceId), &connect_latch_),
+ Eq(Status{Status::kSuccess}));
+ EXPECT_THAT(user_b.StartDiscovery(std::string(kServiceId), &discover_latch_),
+ Eq(Status{Status::kSuccess}));
+ EXPECT_TRUE(discover_latch_.Await(kDefaultTimeout).result());
+ EXPECT_THAT(user_b.RequestConnection(&connect_latch_),
+ Eq(Status{Status::kSuccess}));
+ EXPECT_TRUE(connect_latch_.Await(kDefaultTimeout).result());
+ user_a.Stop();
+ user_b.Stop();
+ env_.Stop();
+}
+
+TEST_P(OfflineServiceControllerTest, CanAcceptConnection) {
+ env_.Start();
+ OfflineSimulationUser user_a(kDeviceA, GetParam());
+ OfflineSimulationUser user_b(kDeviceB, GetParam());
+ EXPECT_THAT(user_a.StartAdvertising(std::string(kServiceId), &connect_latch_),
+ Eq(Status{Status::kSuccess}));
+ EXPECT_THAT(user_b.StartDiscovery(std::string(kServiceId), &discover_latch_),
+ Eq(Status{Status::kSuccess}));
+ EXPECT_TRUE(discover_latch_.Await(kDefaultTimeout).result());
+ EXPECT_THAT(user_b.RequestConnection(&connect_latch_),
+ Eq(Status{Status::kSuccess}));
+ EXPECT_TRUE(connect_latch_.Await(kDefaultTimeout).result());
+ EXPECT_THAT(user_a.AcceptConnection(&accept_latch_),
+ Eq(Status{Status::kSuccess}));
+ EXPECT_THAT(user_b.AcceptConnection(&accept_latch_),
+ Eq(Status{Status::kSuccess}));
+ EXPECT_TRUE(accept_latch_.Await(kDefaultTimeout).result());
+ EXPECT_TRUE(user_a.IsConnected());
+ EXPECT_TRUE(user_b.IsConnected());
+ user_a.Stop();
+ user_b.Stop();
+ env_.Stop();
+}
+
+TEST_P(OfflineServiceControllerTest, CanRejectConnection) {
+ env_.Start();
+ OfflineSimulationUser user_a(kDeviceA, GetParam());
+ OfflineSimulationUser user_b(kDeviceB, GetParam());
+ CountDownLatch reject_latch(1);
+ EXPECT_THAT(user_a.StartAdvertising(std::string(kServiceId), &connect_latch_),
+ Eq(Status{Status::kSuccess}));
+ EXPECT_THAT(user_b.StartDiscovery(std::string(kServiceId), &discover_latch_),
+ Eq(Status{Status::kSuccess}));
+ EXPECT_TRUE(discover_latch_.Await(kDefaultTimeout).result());
+ EXPECT_THAT(user_b.RequestConnection(&connect_latch_),
+ Eq(Status{Status::kSuccess}));
+ EXPECT_TRUE(connect_latch_.Await(kDefaultTimeout).result());
+ user_a.ExpectRejectedConnection(reject_latch);
+ EXPECT_THAT(user_b.RejectConnection(nullptr), Eq(Status{Status::kSuccess}));
+ EXPECT_TRUE(reject_latch.Await(kDefaultTimeout).result());
+ user_a.Stop();
+ user_b.Stop();
+ env_.Stop();
+}
+
+TEST_P(OfflineServiceControllerTest, CanSendBytePayload) {
+ env_.Start();
+ OfflineSimulationUser user_a(kDeviceA, GetParam());
+ OfflineSimulationUser user_b(kDeviceB, GetParam());
+ ASSERT_TRUE(SetupConnection(user_a, user_b));
+ ByteArray message(std::string{kMessage});
+ user_a.SendPayload(Payload(message));
+ user_b.ExpectPayload(payload_latch_);
+ EXPECT_TRUE(payload_latch_.Await(kDefaultTimeout).result());
+ EXPECT_EQ(user_b.GetPayload().AsBytes(), message);
+ user_a.Stop();
+ user_b.Stop();
+ env_.Stop();
+}
+
+TEST_P(OfflineServiceControllerTest, CanSendStreamPayload) {
+ env_.Start();
+ OfflineSimulationUser user_a(kDeviceA, GetParam());
+ OfflineSimulationUser user_b(kDeviceB, GetParam());
+ ASSERT_TRUE(SetupConnection(user_a, user_b));
+ ByteArray message(std::string{kMessage});
+ auto pipe = std::make_shared<Pipe>();
+ OutputStream& tx = pipe->GetOutputStream();
+ user_a.SendPayload(Payload([pipe]() -> InputStream& {
+ return pipe->GetInputStream(); // NOLINT
+ }));
+ user_b.ExpectPayload(payload_latch_);
+ tx.Write(message);
+ EXPECT_TRUE(payload_latch_.Await(kDefaultTimeout).result());
+ EXPECT_NE(user_b.GetPayload().AsStream(), nullptr);
+ InputStream& rx = *user_b.GetPayload().AsStream();
+ ASSERT_TRUE(user_b.WaitForProgress(
+ [size = message.size()](const PayloadProgressInfo& info) -> bool {
+ return info.bytes_transferred >= size;
+ },
+ kProgressTimeout));
+ EXPECT_EQ(rx.Read(Pipe::kChunkSize).result(), message);
+ user_a.Stop();
+ user_b.Stop();
+ env_.Stop();
+}
+
+TEST_P(OfflineServiceControllerTest, CanCancelStreamPayload) {
+ env_.Start();
+ OfflineSimulationUser user_a(kDeviceA, GetParam());
+ OfflineSimulationUser user_b(kDeviceB, GetParam());
+ ASSERT_TRUE(SetupConnection(user_a, user_b));
+ ByteArray message(std::string{kMessage});
+ auto pipe = std::make_shared<Pipe>();
+ OutputStream& tx = pipe->GetOutputStream();
+ user_a.SendPayload(Payload([pipe]() -> InputStream& {
+ return pipe->GetInputStream(); // NOLINT
+ }));
+ user_b.ExpectPayload(payload_latch_);
+ tx.Write(message);
+ EXPECT_TRUE(payload_latch_.Await(kDefaultTimeout).result());
+ EXPECT_NE(user_b.GetPayload().AsStream(), nullptr);
+ InputStream& rx = *user_b.GetPayload().AsStream();
+ ASSERT_TRUE(user_b.WaitForProgress(
+ [size = message.size()](const PayloadProgressInfo& info) -> bool {
+ return info.bytes_transferred >= size;
+ },
+ kProgressTimeout));
+ EXPECT_EQ(rx.Read(Pipe::kChunkSize).result(), message);
+ user_b.CancelPayload();
+ int count = 0;
+ while (true) {
+ count++;
+ if (!tx.Write(message).Ok()) break;
+ SystemClock::Sleep(kDefaultTimeout);
+ }
+ EXPECT_TRUE(user_a.WaitForProgress(
+ [](const PayloadProgressInfo& info) -> bool {
+ return info.status == PayloadProgressInfo::Status::kCanceled;
+ },
+ kProgressTimeout));
+ EXPECT_LT(count, 10);
+ user_a.Stop();
+ user_b.Stop();
+ env_.Stop();
+}
+
+TEST_P(OfflineServiceControllerTest, CanDisconnect) {
+ env_.Start();
+ CountDownLatch disconnect_latch(1);
+ OfflineSimulationUser user_a(kDeviceA, GetParam());
+ OfflineSimulationUser user_b(kDeviceB, GetParam());
+ ASSERT_TRUE(SetupConnection(user_a, user_b));
+ NEARBY_LOGS(INFO) << "Disconnecting";
+ user_b.ExpectDisconnect(disconnect_latch);
+ user_b.Disconnect();
+ EXPECT_TRUE(disconnect_latch.Await(kDisconnectTimeout).result());
+ NEARBY_LOGS(INFO) << "Disconnected";
+ EXPECT_FALSE(user_b.IsConnected());
+ user_a.Stop();
+ user_b.Stop();
+ env_.Stop();
+}
+
+INSTANTIATE_TEST_SUITE_P(ParametrisedOfflineServiceControllerTest,
+ OfflineServiceControllerTest,
+ ::testing::ValuesIn(kTestCases));
+
+// Verifies that InjectEndpoint() can be run successfully; does not test the
+// full connection flow given that normal discovery/advertisement is skipped.
+// Note: Not parameterized because InjectEndpoint only works over Bluetooth.
+TEST_F(OfflineServiceControllerTest, InjectEndpoint) {
+ env_.Start();
+ OfflineSimulationUser user_a(kDeviceA,
+ BooleanMediumSelector{.bluetooth = true});
+ EXPECT_THAT(user_a.StartDiscovery(std::string(kServiceId),
+ /*found_latch=*/nullptr),
+ Eq(Status{Status::kSuccess}));
+ EXPECT_TRUE(user_a.IsDiscovering());
+ user_a.InjectEndpoint(
+ std::string(kServiceId),
+ OutOfBandConnectionMetadata{
+ .medium = Medium::BLUETOOTH,
+ .remote_bluetooth_mac_address = ByteArray(kFakeMacAddress),
+ });
+ user_a.Stop();
+ env_.Stop();
+}
+
+} // namespace
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/offline_simulation_user.cc b/chromium/third_party/nearby/src/connections/implementation/offline_simulation_user.cc
new file mode 100644
index 00000000000..d18faafadcd
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/offline_simulation_user.cc
@@ -0,0 +1,202 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/offline_simulation_user.h"
+
+#include "absl/functional/bind_front.h"
+#include "connections/listeners.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/system_clock.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+void OfflineSimulationUser::OnConnectionInitiated(
+ const std::string& endpoint_id, const ConnectionResponseInfo& info,
+ bool is_outgoing) {
+ if (is_outgoing) {
+ NEARBY_LOG(INFO, "RequestConnection: initiated_cb called");
+ } else {
+ NEARBY_LOG(INFO, "StartAdvertising: initiated_cb called");
+ discovered_ = DiscoveredInfo{
+ .endpoint_id = endpoint_id,
+ .endpoint_info = GetInfo(),
+ .service_id = service_id_,
+ };
+ }
+ if (initiated_latch_) initiated_latch_->CountDown();
+}
+
+void OfflineSimulationUser::OnConnectionAccepted(
+ const std::string& endpoint_id) {
+ if (accept_latch_) accept_latch_->CountDown();
+}
+
+void OfflineSimulationUser::OnConnectionRejected(const std::string& endpoint_id,
+ Status status) {
+ if (reject_latch_) reject_latch_->CountDown();
+}
+
+void OfflineSimulationUser::OnEndpointDisconnect(
+ const std::string& endpoint_id) {
+ NEARBY_LOGS(INFO) << "OnEndpointDisconnect: self=" << this
+ << "; id=" << endpoint_id;
+ if (disconnect_latch_) disconnect_latch_->CountDown();
+}
+
+void OfflineSimulationUser::OnEndpointFound(const std::string& endpoint_id,
+ const ByteArray& endpoint_info,
+ const std::string& service_id) {
+ NEARBY_LOG(INFO, "Device discovered: id=%s", endpoint_id.c_str());
+ discovered_ = DiscoveredInfo{
+ .endpoint_id = endpoint_id,
+ .endpoint_info = endpoint_info,
+ .service_id = service_id,
+ };
+ if (found_latch_) found_latch_->CountDown();
+}
+
+void OfflineSimulationUser::OnEndpointLost(const std::string& endpoint_id) {
+ if (lost_latch_) lost_latch_->CountDown();
+}
+
+void OfflineSimulationUser::OnPayload(const std::string& endpoint_id,
+ Payload payload) {
+ payload_ = std::move(payload);
+ if (payload_latch_) payload_latch_->CountDown();
+}
+
+void OfflineSimulationUser::OnPayloadProgress(const std::string& endpoint_id,
+ const PayloadProgressInfo& info) {
+ MutexLock lock(&progress_mutex_);
+ progress_info_ = info;
+ if (future_ && predicate_ && predicate_(info)) future_->Set(true);
+}
+
+bool OfflineSimulationUser::WaitForProgress(
+ std::function<bool(const PayloadProgressInfo&)> predicate,
+ absl::Duration timeout) {
+ Future<bool> future;
+ {
+ MutexLock lock(&progress_mutex_);
+ if (predicate(progress_info_)) return true;
+ future_ = &future;
+ predicate_ = std::move(predicate);
+ }
+ auto response = future.Get(timeout);
+ {
+ MutexLock lock(&progress_mutex_);
+ future_ = nullptr;
+ predicate_ = nullptr;
+ }
+ return response.ok() && response.result();
+}
+
+Status OfflineSimulationUser::StartAdvertising(const std::string& service_id,
+ CountDownLatch* latch) {
+ initiated_latch_ = latch;
+ service_id_ = service_id;
+ ConnectionListener listener = {
+ .initiated_cb =
+ std::bind(&OfflineSimulationUser::OnConnectionInitiated, this,
+ std::placeholders::_1, std::placeholders::_2, false),
+ .accepted_cb =
+ absl::bind_front(&OfflineSimulationUser::OnConnectionAccepted, this),
+ .rejected_cb =
+ absl::bind_front(&OfflineSimulationUser::OnConnectionRejected, this),
+ .disconnected_cb =
+ absl::bind_front(&OfflineSimulationUser::OnEndpointDisconnect, this),
+ };
+ return ctrl_.StartAdvertising(&client_, service_id_, advertising_options_,
+ {
+ .endpoint_info = info_,
+ .listener = std::move(listener),
+ });
+}
+
+void OfflineSimulationUser::StopAdvertising() {
+ ctrl_.StopAdvertising(&client_);
+}
+
+Status OfflineSimulationUser::StartDiscovery(const std::string& service_id,
+ CountDownLatch* found_latch,
+ CountDownLatch* lost_latch) {
+ found_latch_ = found_latch;
+ lost_latch_ = lost_latch;
+ DiscoveryListener listener = {
+ .endpoint_found_cb =
+ absl::bind_front(&OfflineSimulationUser::OnEndpointFound, this),
+ .endpoint_lost_cb =
+ absl::bind_front(&OfflineSimulationUser::OnEndpointLost, this),
+ };
+ return ctrl_.StartDiscovery(&client_, service_id, discovery_options_,
+ std::move(listener));
+}
+
+void OfflineSimulationUser::StopDiscovery() { ctrl_.StopDiscovery(&client_); }
+
+void OfflineSimulationUser::InjectEndpoint(
+ const std::string& service_id,
+ const OutOfBandConnectionMetadata& metadata) {
+ ctrl_.InjectEndpoint(&client_, service_id, metadata);
+}
+
+Status OfflineSimulationUser::RequestConnection(CountDownLatch* latch) {
+ initiated_latch_ = latch;
+ ConnectionListener listener = {
+ .initiated_cb =
+ std::bind(&OfflineSimulationUser::OnConnectionInitiated, this,
+ std::placeholders::_1, std::placeholders::_2, true),
+ .accepted_cb =
+ absl::bind_front(&OfflineSimulationUser::OnConnectionAccepted, this),
+ .rejected_cb =
+ absl::bind_front(&OfflineSimulationUser::OnConnectionRejected, this),
+ .disconnected_cb =
+ absl::bind_front(&OfflineSimulationUser::OnEndpointDisconnect, this),
+ };
+ client_.AddCancellationFlag(discovered_.endpoint_id);
+ return ctrl_.RequestConnection(&client_, discovered_.endpoint_id,
+ {
+ .endpoint_info = discovered_.endpoint_info,
+ .listener = std::move(listener),
+ },
+ connection_options_);
+}
+
+Status OfflineSimulationUser::AcceptConnection(CountDownLatch* latch) {
+ accept_latch_ = latch;
+ PayloadListener listener = {
+ .payload_cb = absl::bind_front(&OfflineSimulationUser::OnPayload, this),
+ .payload_progress_cb =
+ absl::bind_front(&OfflineSimulationUser::OnPayloadProgress, this),
+ };
+ return ctrl_.AcceptConnection(&client_, discovered_.endpoint_id,
+ std::move(listener));
+}
+
+Status OfflineSimulationUser::RejectConnection(CountDownLatch* latch) {
+ reject_latch_ = latch;
+ return ctrl_.RejectConnection(&client_, discovered_.endpoint_id);
+}
+
+void OfflineSimulationUser::Disconnect() {
+ NEARBY_LOGS(INFO) << "Disconnecting from id=" << discovered_.endpoint_id;
+ ctrl_.DisconnectFromEndpoint(&client_, discovered_.endpoint_id);
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/offline_simulation_user.h b/chromium/third_party/nearby/src/connections/implementation/offline_simulation_user.h
new file mode 100644
index 00000000000..f032d9e4556
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/offline_simulation_user.h
@@ -0,0 +1,207 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_OFFLINE_SIMULATION_USER_H_
+#define CORE_INTERNAL_OFFLINE_SIMULATION_USER_H_
+
+#include <string>
+
+#include "gtest/gtest.h"
+#include "absl/strings/string_view.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/offline_service_controller.h"
+#include "internal/platform/atomic_boolean.h"
+#include "internal/platform/condition_variable.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/future.h"
+
+// Test-only class to help run end-to-end simulations for nearby connections
+// protocol.
+//
+// This is a "standalone" version of PcpManager. It can run independently,
+// provided MediumEnvironment has adequate support for all medium types in use.
+namespace location {
+namespace nearby {
+namespace connections {
+
+class OfflineSimulationUser {
+ public:
+ struct DiscoveredInfo {
+ std::string endpoint_id;
+ ByteArray endpoint_info;
+ std::string service_id;
+
+ bool Empty() const { return endpoint_id.empty(); }
+ void Clear() { endpoint_id.clear(); }
+ };
+
+ explicit OfflineSimulationUser(
+ absl::string_view device_name,
+ BooleanMediumSelector allowed = BooleanMediumSelector())
+ : info_{ByteArray{std::string(device_name)}},
+ advertising_options_{
+ {
+ Strategy::kP2pCluster,
+ allowed,
+ },
+ },
+ connection_options_{
+ .keep_alive_interval_millis = FeatureFlags::GetInstance()
+ .GetFlags()
+ .keep_alive_interval_millis,
+ .keep_alive_timeout_millis = FeatureFlags::GetInstance()
+ .GetFlags()
+ .keep_alive_timeout_millis,
+ },
+ discovery_options_{{
+ Strategy::kP2pCluster,
+ allowed,
+ }} {}
+ virtual ~OfflineSimulationUser() = default;
+
+ // Calls PcpManager::StartAdvertising().
+ // If latch is provided, will call latch->CountDown() in the initiated_cb
+ // callback.
+ Status StartAdvertising(const std::string& service_id, CountDownLatch* latch);
+
+ // Calls PcpManager::StopAdvertising().
+ void StopAdvertising();
+
+ // Calls PcpManager::StartDiscovery().
+ // If found_latch is provided, will call found_latch->CountDown() in the
+ // endpoint_found_cb callback.
+ // If lost_latch is provided, will call lost_latch->CountDown() in the
+ // endpoint_lost_cb callback.
+ Status StartDiscovery(const std::string& service_id,
+ CountDownLatch* found_latch,
+ CountDownLatch* lost_latch = nullptr);
+
+ // Calls PcpManager::StopDiscovery().
+ void StopDiscovery();
+
+ // Calls PcpManager::InjectEndpoint();
+ void InjectEndpoint(const std::string& service_id,
+ const OutOfBandConnectionMetadata& metadata);
+
+ // Calls PcpManager::RequestConnection().
+ // If latch is provided, latch->CountDown() will be called in the initiated_cb
+ // callback.
+ Status RequestConnection(CountDownLatch* latch);
+
+ // Calls PcpManager::AcceptConnection.
+ // If latch is provided, latch->CountDown() will be called in the accepted_cb
+ // callback.
+ Status AcceptConnection(CountDownLatch* latch);
+
+ // Calls PcpManager::RejectConnection.
+ // If latch is provided, latch->CountDown() will be called in the rejected_cb
+ // callback.
+ Status RejectConnection(CountDownLatch* latch);
+
+ // Unlike acceptance, rejection does not have to be mutual, in order to work.
+ // This method will allow to synchronize on the remote rejection, without
+ // performing a local rejection.
+ // latch.CountDown() will be called in the rejected_cb callback.
+ void ExpectRejectedConnection(CountDownLatch& latch) {
+ reject_latch_ = &latch;
+ }
+
+ void ExpectPayload(CountDownLatch& latch) { payload_latch_ = &latch; }
+ void ExpectDisconnect(CountDownLatch& latch) { disconnect_latch_ = &latch; }
+
+ const DiscoveredInfo& GetDiscovered() const { return discovered_; }
+ ByteArray GetInfo() const { return info_; }
+
+ bool WaitForProgress(std::function<bool(const PayloadProgressInfo&)> pred,
+ absl::Duration timeout);
+
+ Payload& GetPayload() { return payload_; }
+ void SendPayload(Payload payload) {
+ sender_payload_id_ = payload.GetId();
+ ctrl_.SendPayload(&client_, {discovered_.endpoint_id}, std::move(payload));
+ }
+
+ Status CancelPayload() {
+ if (sender_payload_id_) {
+ return ctrl_.CancelPayload(&client_, sender_payload_id_);
+ } else {
+ return ctrl_.CancelPayload(&client_, payload_.GetId());
+ }
+ }
+
+ void Disconnect();
+
+ bool IsAdvertising() const { return client_.IsAdvertising(); }
+
+ bool IsDiscovering() const { return client_.IsDiscovering(); }
+
+ bool IsConnected() const {
+ return client_.IsConnectedToEndpoint(discovered_.endpoint_id);
+ }
+
+ void Stop() {
+ StopAdvertising();
+ StopDiscovery();
+ ctrl_.Stop();
+ }
+
+ protected:
+ // ConnectionListener callbacks
+ void OnConnectionInitiated(const std::string& endpoint_id,
+ const ConnectionResponseInfo& info,
+ bool is_outgoing);
+ void OnConnectionAccepted(const std::string& endpoint_id);
+ void OnConnectionRejected(const std::string& endpoint_id, Status status);
+ void OnEndpointDisconnect(const std::string& endpoint_id);
+
+ // DiscoveryListener callbacks
+ void OnEndpointFound(const std::string& endpoint_id,
+ const ByteArray& endpoint_info,
+ const std::string& service_id);
+ void OnEndpointLost(const std::string& endpoint_id);
+
+ // PayloadListener callbacks
+ void OnPayload(const std::string& endpoint_id, Payload payload);
+ void OnPayloadProgress(const std::string& endpoint_id,
+ const PayloadProgressInfo& info);
+
+ std::string service_id_;
+ DiscoveredInfo discovered_;
+ ByteArray info_;
+ AdvertisingOptions advertising_options_;
+ ConnectionOptions connection_options_;
+ DiscoveryOptions discovery_options_;
+ Mutex progress_mutex_;
+ ConditionVariable progress_sync_{&progress_mutex_};
+ PayloadProgressInfo progress_info_;
+ Payload payload_;
+ Payload::Id sender_payload_id_ = 0;
+ CountDownLatch* initiated_latch_ = nullptr;
+ CountDownLatch* accept_latch_ = nullptr;
+ CountDownLatch* reject_latch_ = nullptr;
+ CountDownLatch* found_latch_ = nullptr;
+ CountDownLatch* lost_latch_ = nullptr;
+ CountDownLatch* payload_latch_ = nullptr;
+ CountDownLatch* disconnect_latch_ = nullptr;
+ Future<bool>* future_ = nullptr;
+ std::function<bool(const PayloadProgressInfo&)> predicate_;
+ ClientProxy client_;
+ OfflineServiceController ctrl_;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_OFFLINE_SIMULATION_USER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/p2p_cluster_pcp_handler.cc b/chromium/third_party/nearby/src/connections/implementation/p2p_cluster_pcp_handler.cc
new file mode 100644
index 00000000000..b380139d6ce
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/p2p_cluster_pcp_handler.cc
@@ -0,0 +1,1366 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/p2p_cluster_pcp_handler.h"
+
+#include "absl/functional/bind_front.h"
+#include "absl/strings/escaping.h"
+#include "connections/implementation/base_pcp_handler.h"
+#include "connections/implementation/ble_advertisement.h"
+#include "connections/implementation/ble_endpoint_channel.h"
+#include "connections/implementation/bluetooth_endpoint_channel.h"
+#include "connections/implementation/bwu_manager.h"
+#include "connections/implementation/mediums/utils.h"
+#include "connections/implementation/webrtc_endpoint_channel.h"
+#include "connections/implementation/wifi_lan_endpoint_channel.h"
+#include "internal/platform/nsd_service_info.h"
+#include "internal/platform/types.h"
+#include "internal/platform/crypto.h"
+#include "proto/connections_enums.pb.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+ByteArray P2pClusterPcpHandler::GenerateHash(const std::string& source,
+ size_t size) {
+ return Utils::Sha256Hash(source, size);
+}
+
+bool P2pClusterPcpHandler::ShouldAdvertiseBluetoothMacOverBle(
+ PowerLevel power_level) {
+ return power_level == PowerLevel::kHighPower;
+}
+
+bool P2pClusterPcpHandler::ShouldAcceptBluetoothConnections(
+ const AdvertisingOptions& advertising_options) {
+ return advertising_options.enable_bluetooth_listening;
+}
+
+P2pClusterPcpHandler::P2pClusterPcpHandler(
+ Mediums* mediums, EndpointManager* endpoint_manager,
+ EndpointChannelManager* endpoint_channel_manager, BwuManager* bwu_manager,
+ InjectedBluetoothDeviceStore& injected_bluetooth_device_store, Pcp pcp)
+ : BasePcpHandler(mediums, endpoint_manager, endpoint_channel_manager,
+ bwu_manager, pcp),
+ bluetooth_radio_(mediums->GetBluetoothRadio()),
+ bluetooth_medium_(mediums->GetBluetoothClassic()),
+ ble_medium_(mediums->GetBle()),
+ wifi_lan_medium_(mediums->GetWifiLan()),
+ webrtc_medium_(mediums->GetWebRtc()),
+ injected_bluetooth_device_store_(injected_bluetooth_device_store) {}
+
+// Returns a vector or mediums sorted in order or decreasing priority for
+// all the supported mediums.
+// Example: WiFi_LAN, WEB_RTC, BT, BLE
+std::vector<proto::connections::Medium>
+P2pClusterPcpHandler::GetConnectionMediumsByPriority() {
+ std::vector<proto::connections::Medium> mediums;
+ if (wifi_lan_medium_.IsAvailable()) {
+ mediums.push_back(proto::connections::WIFI_LAN);
+ }
+ if (webrtc_medium_.IsAvailable()) {
+ mediums.push_back(proto::connections::WEB_RTC);
+ }
+ if (bluetooth_medium_.IsAvailable()) {
+ mediums.push_back(proto::connections::BLUETOOTH);
+ }
+ if (ble_medium_.IsAvailable()) {
+ mediums.push_back(proto::connections::BLE);
+ }
+ return mediums;
+}
+
+proto::connections::Medium P2pClusterPcpHandler::GetDefaultUpgradeMedium() {
+ return proto::connections::WIFI_LAN;
+}
+
+BasePcpHandler::StartOperationResult P2pClusterPcpHandler::StartAdvertisingImpl(
+ ClientProxy* client, const std::string& service_id,
+ const std::string& local_endpoint_id, const ByteArray& local_endpoint_info,
+ const AdvertisingOptions& advertising_options) {
+ std::vector<proto::connections::Medium> mediums_started_successfully;
+
+ WebRtcState web_rtc_state{WebRtcState::kUnconnectable};
+
+ if (advertising_options.allowed.wifi_lan) {
+ proto::connections::Medium wifi_lan_medium =
+ StartWifiLanAdvertising(client, service_id, local_endpoint_id,
+ local_endpoint_info, web_rtc_state);
+ if (wifi_lan_medium != proto::connections::UNKNOWN_MEDIUM) {
+ NEARBY_LOGS(INFO)
+ << "P2pClusterPcpHandler::StartAdvertisingImpl: WifiLan added";
+ mediums_started_successfully.push_back(wifi_lan_medium);
+ }
+ }
+
+ if (advertising_options.allowed.bluetooth) {
+ const ByteArray bluetooth_hash =
+ GenerateHash(service_id, BluetoothDeviceName::kServiceIdHashLength);
+ proto::connections::Medium bluetooth_medium = StartBluetoothAdvertising(
+ client, service_id, bluetooth_hash, local_endpoint_id,
+ local_endpoint_info, web_rtc_state);
+ if (bluetooth_medium != proto::connections::UNKNOWN_MEDIUM) {
+ NEARBY_LOG(INFO, "P2pClusterPcpHandler::StartAdvertisingImpl: BT added");
+ mediums_started_successfully.push_back(bluetooth_medium);
+ bluetooth_classic_advertiser_client_id_ = client->GetClientId();
+ }
+ }
+
+ if (advertising_options.allowed.ble) {
+ proto::connections::Medium ble_medium = StartBleAdvertising(
+ client, service_id, local_endpoint_id, local_endpoint_info,
+ advertising_options, web_rtc_state);
+ if (ble_medium != proto::connections::UNKNOWN_MEDIUM) {
+ NEARBY_LOGS(INFO)
+ << "P2pClusterPcpHandler::StartAdvertisingImpl: Ble added";
+ mediums_started_successfully.push_back(ble_medium);
+ }
+ }
+
+ if (mediums_started_successfully.empty()) {
+ NEARBY_LOGS(ERROR) << "Failed StartAdvertising("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << ") for client=" << client->GetClientId();
+ return {
+ .status = {Status::kBluetoothError},
+ };
+ }
+
+ // The rest of the operations for startAdvertising() will continue
+ // asynchronously via
+ // IncomingBluetoothConnectionProcessor.onIncomingBluetoothConnection(), so
+ // leave it to that to signal any errors that may occur.
+ return {
+ .status = {Status::kSuccess},
+ .mediums = std::move(mediums_started_successfully),
+ };
+}
+
+Status P2pClusterPcpHandler::StopAdvertisingImpl(ClientProxy* client) {
+ if (client->GetClientId() == bluetooth_classic_advertiser_client_id_) {
+ bluetooth_medium_.TurnOffDiscoverability();
+ bluetooth_classic_advertiser_client_id_ = 0;
+ } else {
+ NEARBY_LOGS(INFO) << "Skipped BT TurnOffDiscoverability for client="
+ << client->GetClientId()
+ << ", client that turned on discoverability is "
+ << bluetooth_classic_advertiser_client_id_;
+ }
+
+ bluetooth_medium_.StopAcceptingConnections(client->GetAdvertisingServiceId());
+
+ ble_medium_.StopAdvertising(client->GetAdvertisingServiceId());
+ ble_medium_.StopAcceptingConnections(client->GetAdvertisingServiceId());
+
+ wifi_lan_medium_.StopAdvertising(client->GetAdvertisingServiceId());
+ wifi_lan_medium_.StopAcceptingConnections(client->GetAdvertisingServiceId());
+
+ return {Status::kSuccess};
+}
+
+bool P2pClusterPcpHandler::IsRecognizedBluetoothEndpoint(
+ const std::string& name_string, const std::string& service_id,
+ const BluetoothDeviceName& name) const {
+ if (!name.IsValid()) {
+ NEARBY_LOGS(INFO)
+ << name_string
+ << " doesn't conform to the BluetoothDeviceName format, discarding.";
+ return false;
+ }
+
+ if (name.GetPcp() != GetPcp()) {
+ NEARBY_LOGS(INFO) << name_string << " doesn't match on Pcp; expected "
+ << PcpToStrategy(GetPcp()).GetName() << ", found "
+ << PcpToStrategy(name.GetPcp()).GetName();
+ return false;
+ }
+
+ ByteArray expected_service_id_hash =
+ GenerateHash(service_id, BluetoothDeviceName::kServiceIdHashLength);
+
+ if (name.GetServiceIdHash() != expected_service_id_hash) {
+ NEARBY_LOGS(INFO) << name_string
+ << " doesn't match on expected service_id_hash; expected "
+ << absl::BytesToHexString(expected_service_id_hash.data())
+ << ", found "
+ << absl::BytesToHexString(name.GetServiceIdHash().data());
+ return false;
+ }
+
+ return true;
+}
+
+void P2pClusterPcpHandler::BluetoothDeviceDiscoveredHandler(
+ ClientProxy* client, const std::string& service_id,
+ BluetoothDevice device) {
+ RunOnPcpHandlerThread(
+ "p2p-bt-device-discovered",
+ [this, client, service_id, device]()
+ RUN_ON_PCP_HANDLER_THREAD() {
+ // Make sure we are still discovering before proceeding.
+ if (!client->IsDiscovering()) {
+ NEARBY_LOGS(WARNING) << "Skipping discovery of BluetoothDevice "
+ << device.GetName()
+ << " because we are no longer discovering.";
+ return;
+ }
+
+ // Parse the Bluetooth device name.
+ const std::string device_name_string = device.GetName();
+ BluetoothDeviceName device_name(device_name_string);
+
+ // Make sure the Bluetooth device name points to a valid
+ // endpoint we're discovering.
+ if (!IsRecognizedBluetoothEndpoint(device_name_string, service_id,
+ device_name)) {
+ NEARBY_LOGS(INFO) << "Found unrecognized BluetoothDeviceName "
+ << device_name_string;
+ return;
+ }
+
+ // Report the discovered endpoint to the client.
+ NEARBY_LOGS(INFO)
+ << "Found BluetoothDeviceName " << device_name_string
+ << " (with endpoint_id=" << device_name.GetEndpointId()
+ << " and endpoint_info="
+ << absl::BytesToHexString(device_name.GetEndpointInfo().data())
+ << ").";
+ OnEndpointFound(
+ client,
+ std::make_shared<BluetoothEndpoint>(BluetoothEndpoint{
+ {device_name.GetEndpointId(), device_name.GetEndpointInfo(),
+ service_id, proto::connections::Medium::BLUETOOTH,
+ device_name.GetWebRtcState()},
+ device,
+ }));
+ });
+}
+
+void P2pClusterPcpHandler::BluetoothNameChangedHandler(
+ ClientProxy* client, const std::string& service_id,
+ BluetoothDevice device) {
+ RunOnPcpHandlerThread(
+ "p2p-bt-name-changed",
+ [this, client, service_id, device]() RUN_ON_PCP_HANDLER_THREAD() {
+ // Make sure we are still discovering before proceeding.
+ if (!client->IsDiscovering()) {
+ NEARBY_LOGS(WARNING)
+ << "Ignoring lost BluetoothDevice " << device.GetName()
+ << " because Connections is no longer discovering.";
+ return;
+ }
+
+ // Parse the Bluetooth device name.
+ const std::string device_name_string = device.GetName();
+ BluetoothDeviceName device_name(device_name_string);
+ NEARBY_LOGS(INFO) << "BT discovery handler (CHANGED) [client_id="
+ << client->GetClientId()
+ << ", service_id=" << service_id
+ << "]: processing new name " << device_name_string;
+
+ // By this point, the BluetoothDevice passed to us has a different name
+ // than what we may have discovered before. We need to iterate over the
+ // found BluetoothEndpoints and compare their addresses to see the
+ // devices are the same. We are not guaranteed to discover a match,
+ // since the old name may not have been formatted for Nearby
+ // Connections.
+ for (auto endpoint :
+ GetDiscoveredEndpoints(proto::connections::Medium::BLUETOOTH)) {
+ BluetoothEndpoint* bluetoothEndpoint =
+ static_cast<BluetoothEndpoint*>(endpoint);
+ NEARBY_LOGS(INFO)
+ << "BT discovery handler (CHANGED) [client_id="
+ << client->GetClientId() << ", service_id=" << service_id
+ << "]: comparing MAC addresses with existing endpoint "
+ << bluetoothEndpoint->bluetooth_device.GetName()
+ << ". They have MAC address "
+ << bluetoothEndpoint->bluetooth_device.GetMacAddress()
+ << " and the new endpoint has MAC address "
+ << device.GetMacAddress();
+ if (bluetoothEndpoint->bluetooth_device.GetMacAddress() ==
+ device.GetMacAddress()) {
+ // Report the BluetoothEndpoint as lost to the client.
+ NEARBY_LOGS(INFO) << "Reporting lost BluetoothDevice "
+ << bluetoothEndpoint->bluetooth_device.GetName()
+ << ", due to device name change.";
+ OnEndpointLost(client, *endpoint);
+ break;
+ }
+ }
+
+ // Make sure the Bluetooth device name points to a valid
+ // endpoint we're discovering.
+ if (!IsRecognizedBluetoothEndpoint(device_name_string, service_id,
+ device_name)) {
+ NEARBY_LOGS(INFO) << "Found unrecognized BluetoothDeviceName "
+ << device_name_string;
+ return;
+ }
+
+ // Report the discovered endpoint to the client.
+ NEARBY_LOGS(INFO) << "Found BluetoothDeviceName " << device_name_string
+ << " (with endpoint_id="
+ << device_name.GetEndpointId()
+ << " and endpoint_info="
+ << absl::BytesToHexString(
+ device_name.GetEndpointInfo().data())
+ << ").";
+ OnEndpointFound(
+ client,
+ std::make_shared<BluetoothEndpoint>(BluetoothEndpoint{
+ {device_name.GetEndpointId(), device_name.GetEndpointInfo(),
+ service_id, proto::connections::Medium::BLUETOOTH,
+ device_name.GetWebRtcState()},
+ device,
+ }));
+ });
+}
+
+void P2pClusterPcpHandler::BluetoothDeviceLostHandler(
+ ClientProxy* client, const std::string& service_id,
+ BluetoothDevice& device) {
+ const std::string& device_name_string = device.GetName();
+ RunOnPcpHandlerThread(
+ "p2p-bt-device-lost", [this, client, service_id,
+ device_name_string]() RUN_ON_PCP_HANDLER_THREAD() {
+ // Make sure we are still discovering before proceeding.
+ if (!client->IsDiscovering()) {
+ NEARBY_LOGS(WARNING)
+ << "Ignoring lost BluetoothDevice " << device_name_string
+ << " because Connections is no "
+ "longer discovering.";
+ return;
+ }
+
+ // Parse the Bluetooth device name.
+ BluetoothDeviceName device_name(device_name_string);
+
+ // Make sure the Bluetooth device name points to a valid
+ // endpoint we're discovering.
+ if (!IsRecognizedBluetoothEndpoint(device_name_string, service_id,
+ device_name))
+ return;
+
+ // Report the BluetoothEndpoint as lost to the client.
+ NEARBY_LOGS(INFO) << "Processing lost BluetoothDeviceName "
+ << device_name_string;
+ OnEndpointLost(client, DiscoveredEndpoint{
+ device_name.GetEndpointId(),
+ device_name.GetEndpointInfo(), service_id,
+ proto::connections::Medium::BLUETOOTH,
+ WebRtcState::kUndefined});
+ });
+}
+
+bool P2pClusterPcpHandler::IsRecognizedBleEndpoint(
+ const std::string& service_id,
+ const BleAdvertisement& advertisement) const {
+ if (!advertisement.IsValid()) {
+ NEARBY_LOGS(INFO)
+ << "BleAdvertisement doesn't conform to the format, discarding.";
+ return false;
+ }
+
+ if (advertisement.GetVersion() != kBleAdvertisementVersion) {
+ NEARBY_LOGS(INFO) << "BleAdvertisement has an unknown version; expected "
+ << static_cast<int>(kBleAdvertisementVersion)
+ << ", found "
+ << static_cast<int>(advertisement.GetVersion());
+ return false;
+ }
+
+ if (advertisement.GetPcp() != GetPcp()) {
+ NEARBY_LOGS(INFO) << "BleAdvertisement doesn't match on Pcp; expected "
+ << PcpToStrategy(GetPcp()).GetName() << ", found "
+ << PcpToStrategy(advertisement.GetPcp()).GetName();
+ return false;
+ }
+
+ // Check ServiceId for normal advertisement.
+ // ServiceIdHash is empty for fast advertisement.
+ if (!advertisement.IsFastAdvertisement()) {
+ ByteArray expected_service_id_hash =
+ GenerateHash(service_id, BleAdvertisement::kServiceIdHashLength);
+
+ if (advertisement.GetServiceIdHash() != expected_service_id_hash) {
+ NEARBY_LOGS(INFO)
+ << "BleAdvertisement doesn't match on expected service_id_hash; "
+ "expected "
+ << absl::BytesToHexString(expected_service_id_hash.data())
+ << ", found "
+ << absl::BytesToHexString(advertisement.GetServiceIdHash().data());
+ return false;
+ }
+ }
+
+ return true;
+}
+
+void P2pClusterPcpHandler::BlePeripheralDiscoveredHandler(
+ ClientProxy* client, BlePeripheral& peripheral,
+ const std::string& service_id, const ByteArray& advertisement_bytes,
+ bool fast_advertisement) {
+ RunOnPcpHandlerThread(
+ "p2p-ble-device-discovered",
+ [this, client, &peripheral, service_id, advertisement_bytes,
+ fast_advertisement]() RUN_ON_PCP_HANDLER_THREAD() {
+ // Make sure we are still discovering before proceeding.
+ if (!client->IsDiscovering()) {
+ NEARBY_LOGS(WARNING)
+ << "Skipping discovery of BleAdvertisement header "
+ << absl::BytesToHexString(advertisement_bytes.data())
+ << " because we are no longer discovering.";
+ return;
+ }
+
+ // Parse the BLE advertisement bytes.
+ BleAdvertisement advertisement(fast_advertisement, advertisement_bytes);
+
+ // Make sure the BLE advertisement points to a valid
+ // endpoint we're discovering.
+ if (!IsRecognizedBleEndpoint(service_id, advertisement)) return;
+
+ // Store all the state we need to be able to re-create a BleEndpoint
+ // in BlePeripheralLostHandler, since that isn't privy to
+ // the bytes of the ble advertisement itself.
+ found_ble_endpoints_.emplace(
+ peripheral.GetName(),
+ BleEndpointState(advertisement.GetEndpointId(),
+ advertisement.GetEndpointInfo()));
+
+ // Report the discovered endpoint to the client.
+ NEARBY_LOGS(INFO) << "Found BleAdvertisement "
+ << absl::BytesToHexString(advertisement_bytes.data())
+ << " (with endpoint_id="
+ << advertisement.GetEndpointId()
+ << ", and endpoint_info="
+ << absl::BytesToHexString(
+ advertisement.GetEndpointInfo().data())
+ << ").",
+ OnEndpointFound(client,
+ std::make_shared<BleEndpoint>(BleEndpoint{
+ {advertisement.GetEndpointId(),
+ advertisement.GetEndpointInfo(), service_id,
+ proto::connections::Medium::BLE,
+ advertisement.GetWebRtcState()},
+ peripheral,
+ }));
+
+ // Make sure we can connect to this device via Classic Bluetooth.
+ std::string remote_bluetooth_mac_address =
+ advertisement.GetBluetoothMacAddress();
+ if (remote_bluetooth_mac_address.empty()) {
+ NEARBY_LOGS(INFO)
+ << "No Bluetooth Classic MAC address found in advertisement.";
+ return;
+ }
+
+ BluetoothDevice remote_bluetooth_device =
+ bluetooth_medium_.GetRemoteDevice(remote_bluetooth_mac_address);
+ if (!remote_bluetooth_device.IsValid()) {
+ NEARBY_LOGS(INFO)
+ << "A valid Bluetooth device could not be derived from the MAC "
+ "address "
+ << remote_bluetooth_mac_address;
+ return;
+ }
+
+ OnEndpointFound(client,
+ std::make_shared<BluetoothEndpoint>(BluetoothEndpoint{
+ {
+ advertisement.GetEndpointId(),
+ advertisement.GetEndpointInfo(),
+ service_id,
+ proto::connections::Medium::BLUETOOTH,
+ advertisement.GetWebRtcState(),
+ },
+ remote_bluetooth_device,
+ }));
+ });
+}
+
+void P2pClusterPcpHandler::BlePeripheralLostHandler(
+ ClientProxy* client, BlePeripheral& peripheral,
+ const std::string& service_id) {
+ std::string peripheral_name = peripheral.GetName();
+ NEARBY_LOG(INFO, "Ble: [LOST, SCHED] peripheral_name=%s",
+ peripheral_name.c_str());
+ RunOnPcpHandlerThread(
+ "p2p-ble-device-lost",
+ [this, client, service_id, &peripheral]() RUN_ON_PCP_HANDLER_THREAD() {
+ // Make sure we are still discovering before proceeding.
+ if (!client->IsDiscovering()) {
+ NEARBY_LOGS(WARNING)
+ << "Ignoring lost BlePeripheral " << peripheral.GetName()
+ << " because we are no longer discovering.";
+ return;
+ }
+
+ // Remove this BlePeripheral from found_ble_endpoints_, and
+ // report the endpoint as lost to the client.
+ auto item = found_ble_endpoints_.find(peripheral.GetName());
+ if (item != found_ble_endpoints_.end()) {
+ BleEndpointState ble_endpoint_state(item->second);
+ found_ble_endpoints_.erase(item);
+
+ // Report the discovered endpoint to the client.
+ NEARBY_LOGS(INFO)
+ << "Lost BleEndpoint for BlePeripheral " << peripheral.GetName()
+ << " (with endpoint_id=" << ble_endpoint_state.endpoint_id
+ << " and endpoint_info="
+ << absl::BytesToHexString(ble_endpoint_state.endpoint_info.data())
+ << ").";
+ OnEndpointLost(client, DiscoveredEndpoint{
+ ble_endpoint_state.endpoint_id,
+ ble_endpoint_state.endpoint_info,
+ service_id,
+ proto::connections::Medium::BLE,
+ WebRtcState::kUndefined,
+ });
+ }
+ });
+}
+
+bool P2pClusterPcpHandler::IsRecognizedWifiLanEndpoint(
+ const std::string& service_id,
+ const WifiLanServiceInfo& wifi_lan_service_info) const {
+ if (!wifi_lan_service_info.IsValid()) {
+ NEARBY_LOGS(INFO)
+ << "WifiLanServiceInfo doesn't conform to the format, discarding.";
+ return false;
+ }
+
+ if (wifi_lan_service_info.GetPcp() != GetPcp()) {
+ NEARBY_LOGS(INFO)
+ << "WifiLanServiceInfo doesn't match on Pcp; expected "
+ << PcpToStrategy(GetPcp()).GetName() << ", found "
+ << PcpToStrategy(wifi_lan_service_info.GetPcp()).GetName();
+ return false;
+ }
+
+ ByteArray expected_service_id_hash =
+ GenerateHash(service_id, WifiLanServiceInfo::kServiceIdHashLength);
+
+ if (wifi_lan_service_info.GetServiceIdHash() != expected_service_id_hash) {
+ NEARBY_LOGS(INFO)
+ << "WifiLanServiceInfo doesn't match on expected service_id_hash; "
+ "expected "
+ << absl::BytesToHexString(expected_service_id_hash.data()) << ", found "
+ << absl::BytesToHexString(
+ wifi_lan_service_info.GetServiceIdHash().data());
+ return false;
+ }
+
+ return true;
+}
+
+void P2pClusterPcpHandler::WifiLanServiceDiscoveredHandler(
+ ClientProxy* client, NsdServiceInfo service_info,
+ const std::string& service_id) {
+ RunOnPcpHandlerThread(
+ "p2p-wifi-service-discovered",
+ [this, client, service_id, service_info]() RUN_ON_PCP_HANDLER_THREAD() {
+ // Make sure we are still discovering before proceeding.
+ if (!client->IsDiscovering()) {
+ NEARBY_LOGS(WARNING) << "Skipping discovery of NsdServiceInfo "
+ << service_info.GetServiceName()
+ << " because we are no longer discovering.";
+ return;
+ }
+
+ // Parse the WifiLanServiceInfo.
+ WifiLanServiceInfo wifi_lan_service_info(service_info);
+ // Make sure the WifiLan service name points to a valid
+ // endpoint we're discovering.
+ if (!IsRecognizedWifiLanEndpoint(service_id, wifi_lan_service_info)) {
+ return;
+ }
+
+ // Report the discovered endpoint to the client.
+ NEARBY_LOGS(INFO) << "Found NsdServiceInfo "
+ << service_info.GetServiceName()
+ << " (with endpoint_id="
+ << wifi_lan_service_info.GetEndpointId()
+ << "and endpoint_info="
+ << absl::BytesToHexString(
+ wifi_lan_service_info.GetEndpointInfo().data())
+ << ").";
+ OnEndpointFound(client,
+ std::make_shared<WifiLanEndpoint>(WifiLanEndpoint{
+ {
+ wifi_lan_service_info.GetEndpointId(),
+ wifi_lan_service_info.GetEndpointInfo(),
+ service_id,
+ proto::connections::Medium::WIFI_LAN,
+ wifi_lan_service_info.GetWebRtcState(),
+ },
+ service_info,
+ }));
+ });
+}
+
+void P2pClusterPcpHandler::WifiLanServiceLostHandler(
+ ClientProxy* client, NsdServiceInfo service_info,
+ const std::string& service_id) {
+ NEARBY_LOGS(INFO) << "WifiLan: [LOST, SCHED] service_info=" << &service_info
+ << ", service_name=" << service_info.GetServiceName();
+ RunOnPcpHandlerThread(
+ "p2p-wifi-service-lost",
+ [this, client, service_id, service_info]() RUN_ON_PCP_HANDLER_THREAD() {
+ // Make sure we are still discovering before proceeding.
+ if (!client->IsDiscovering()) {
+ NEARBY_LOGS(WARNING) << "Ignoring lost NsdServiceInfo "
+ << service_info.GetServiceName()
+ << " because we are no longer "
+ "discovering.";
+ return;
+ }
+
+ // Parse the WifiLanServiceInfo.
+ WifiLanServiceInfo wifi_lan_service_info(service_info);
+
+ // Make sure the WifiLan service name points to a valid
+ // endpoint we're discovering.
+ if (!IsRecognizedWifiLanEndpoint(service_id, wifi_lan_service_info))
+ return;
+
+ // Report the lost endpoint to the client.
+ NEARBY_LOGS(INFO) << "Lost NsdServiceInfo "
+ << service_info.GetServiceName()
+ << " (with endpoint_id="
+ << wifi_lan_service_info.GetEndpointId()
+ << " and endpoint_info="
+ << absl::BytesToHexString(
+ wifi_lan_service_info.GetEndpointInfo().data())
+ << ").";
+ OnEndpointLost(client, DiscoveredEndpoint{
+ wifi_lan_service_info.GetEndpointId(),
+ wifi_lan_service_info.GetEndpointInfo(),
+ service_id,
+ proto::connections::Medium::WIFI_LAN,
+ WebRtcState::kUndefined,
+ });
+ });
+}
+
+BasePcpHandler::StartOperationResult P2pClusterPcpHandler::StartDiscoveryImpl(
+ ClientProxy* client, const std::string& service_id,
+ const DiscoveryOptions& discovery_options) {
+ // If this is an out-of-band connection, do not start actual discovery, since
+ // this connection is intended to be completed via InjectEndpointImpl().
+ if (discovery_options.is_out_of_band_connection) {
+ return {.status = {Status::kSuccess},
+ .mediums = discovery_options.allowed.GetMediums(true)};
+ }
+
+ std::vector<proto::connections::Medium> mediums_started_successfully;
+
+ if (discovery_options.allowed.wifi_lan) {
+ proto::connections::Medium wifi_lan_medium = StartWifiLanDiscovery(
+ {
+ .service_discovered_cb = absl::bind_front(
+ &P2pClusterPcpHandler::WifiLanServiceDiscoveredHandler, this,
+ client),
+ .service_lost_cb = absl::bind_front(
+ &P2pClusterPcpHandler::WifiLanServiceLostHandler, this, client),
+ },
+ client, service_id);
+ if (wifi_lan_medium != proto::connections::UNKNOWN_MEDIUM) {
+ NEARBY_LOGS(INFO)
+ << "P2pClusterPcpHandler::StartDiscoveryImpl: WifiLan added";
+ mediums_started_successfully.push_back(wifi_lan_medium);
+ }
+ }
+
+ if (discovery_options.allowed.bluetooth) {
+ proto::connections::Medium bluetooth_medium = StartBluetoothDiscovery(
+ {
+ .device_discovered_cb = absl::bind_front(
+ &P2pClusterPcpHandler::BluetoothDeviceDiscoveredHandler, this,
+ client, service_id),
+ .device_name_changed_cb = absl::bind_front(
+ &P2pClusterPcpHandler::BluetoothNameChangedHandler, this,
+ client, service_id),
+ .device_lost_cb = absl::bind_front(
+ &P2pClusterPcpHandler::BluetoothDeviceLostHandler, this, client,
+ service_id),
+ },
+ client, service_id);
+ if (bluetooth_medium != proto::connections::UNKNOWN_MEDIUM) {
+ NEARBY_LOG(INFO, "P2pClusterPcpHandler::StartDiscoveryImpl: BT added");
+ mediums_started_successfully.push_back(bluetooth_medium);
+ bluetooth_classic_discoverer_client_id_ = client->GetClientId();
+ }
+ }
+
+ if (discovery_options.allowed.ble) {
+ proto::connections::Medium ble_medium = StartBleScanning(
+ {
+ .peripheral_discovered_cb = absl::bind_front(
+ &P2pClusterPcpHandler::BlePeripheralDiscoveredHandler, this,
+ client),
+ .peripheral_lost_cb = absl::bind_front(
+ &P2pClusterPcpHandler::BlePeripheralLostHandler, this, client),
+ },
+ client, service_id, discovery_options.fast_advertisement_service_uuid);
+ if (ble_medium != proto::connections::UNKNOWN_MEDIUM) {
+ NEARBY_LOG(INFO, "P2pClusterPcpHandler::StartDiscoveryImpl: Ble added");
+ mediums_started_successfully.push_back(ble_medium);
+ }
+ }
+
+ if (mediums_started_successfully.empty()) {
+ NEARBY_LOGS(ERROR)
+ << "Failed StartDiscovery() for client=" << client->GetClientId()
+ << " because we couldn't scan on Bluetooth, BLE, or WifiLan for "
+ "service_id="
+ << service_id;
+ return {
+ .status = {Status::kBluetoothError},
+ };
+ }
+
+ return {
+ .status = {Status::kSuccess},
+ .mediums = std::move(mediums_started_successfully),
+ };
+}
+
+Status P2pClusterPcpHandler::StopDiscoveryImpl(ClientProxy* client) {
+ wifi_lan_medium_.StopDiscovery(client->GetDiscoveryServiceId());
+ if (client->GetClientId() == bluetooth_classic_discoverer_client_id_) {
+ bluetooth_medium_.StopDiscovery();
+ bluetooth_classic_discoverer_client_id_ = 0;
+ } else {
+ NEARBY_LOGS(INFO) << "Skipped BT StopDiscovery for client="
+ << client->GetClientId()
+ << ", client that started discovery is "
+ << bluetooth_classic_discoverer_client_id_;
+ }
+
+ ble_medium_.StopScanning(client->GetDiscoveryServiceId());
+ return {Status::kSuccess};
+}
+
+Status P2pClusterPcpHandler::InjectEndpointImpl(
+ ClientProxy* client, const std::string& service_id,
+ const OutOfBandConnectionMetadata& metadata) {
+ NEARBY_LOGS(INFO) << "InjectEndpoint.";
+ // Bluetooth is the only supported out-of-band connection medium.
+ if (metadata.medium != Medium::BLUETOOTH) {
+ NEARBY_LOGS(WARNING) << "InjectEndpointImpl: Only Bluetooth is supported.";
+ return {Status::kError};
+ }
+
+ BluetoothDevice remote_bluetooth_device =
+ injected_bluetooth_device_store_.CreateInjectedBluetoothDevice(
+ metadata.remote_bluetooth_mac_address, metadata.endpoint_id,
+ metadata.endpoint_info,
+ GenerateHash(service_id, BluetoothDeviceName::kServiceIdHashLength),
+ GetPcp());
+
+ if (!remote_bluetooth_device.IsValid()) {
+ NEARBY_LOG(WARNING, "InjectEndpointImpl: Invalid parameters.");
+ return {Status::kError};
+ }
+
+ BluetoothDeviceDiscoveredHandler(client, service_id, remote_bluetooth_device);
+ return {Status::kSuccess};
+}
+
+BasePcpHandler::ConnectImplResult P2pClusterPcpHandler::ConnectImpl(
+ ClientProxy* client, BasePcpHandler::DiscoveredEndpoint* endpoint) {
+ if (!endpoint) {
+ return BasePcpHandler::ConnectImplResult{
+ .status = {Status::kError},
+ };
+ }
+ switch (endpoint->medium) {
+ case proto::connections::Medium::BLUETOOTH: {
+ auto* bluetooth_endpoint = down_cast<BluetoothEndpoint*>(endpoint);
+ if (bluetooth_endpoint) {
+ return BluetoothConnectImpl(client, bluetooth_endpoint);
+ }
+ break;
+ }
+ case proto::connections::Medium::BLE: {
+ auto* ble_endpoint = down_cast<BleEndpoint*>(endpoint);
+ if (ble_endpoint) {
+ return BleConnectImpl(client, ble_endpoint);
+ }
+ break;
+ }
+ case proto::connections::Medium::WIFI_LAN: {
+ auto* wifi_lan_endpoint = down_cast<WifiLanEndpoint*>(endpoint);
+ if (wifi_lan_endpoint) {
+ return WifiLanConnectImpl(client, wifi_lan_endpoint);
+ }
+ break;
+ }
+ case proto::connections::Medium::WEB_RTC: {
+ break;
+ }
+ default:
+ break;
+ }
+
+ return BasePcpHandler::ConnectImplResult{
+ .status = {Status::kError},
+ };
+}
+
+proto::connections::Medium P2pClusterPcpHandler::StartBluetoothAdvertising(
+ ClientProxy* client, const std::string& service_id,
+ const ByteArray& service_id_hash, const std::string& local_endpoint_id,
+ const ByteArray& local_endpoint_info, WebRtcState web_rtc_state) {
+ // Start listening for connections before advertising in case a connection
+ // request comes in very quickly.
+ NEARBY_LOG(
+ INFO,
+ "P2pClusterPcpHandler::StartBluetoothAdvertising: service=%s: start",
+ service_id.c_str());
+ if (!bluetooth_medium_.IsAcceptingConnections(service_id)) {
+ if (!bluetooth_radio_.Enable() ||
+ !bluetooth_medium_.StartAcceptingConnections(
+ service_id, {.accepted_cb = [this, client, local_endpoint_info](
+ BluetoothSocket socket) {
+ if (!socket.IsValid()) {
+ NEARBY_LOGS(WARNING)
+ << "Invalid socket in accept callback("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "), client=" << client->GetClientId();
+ return;
+ }
+ RunOnPcpHandlerThread(
+ "p2p-bt-on-incoming-connection",
+ [this, client, local_endpoint_info,
+ socket = std::move(socket)]()
+ RUN_ON_PCP_HANDLER_THREAD() mutable {
+ std::string remote_device_name =
+ socket.GetRemoteDevice().GetName();
+ auto channel =
+ absl::make_unique<BluetoothEndpointChannel>(
+ remote_device_name, socket);
+ ByteArray remote_device_info{remote_device_name};
+
+ OnIncomingConnection(
+ client, remote_device_info, std::move(channel),
+ proto::connections::Medium::BLUETOOTH);
+ });
+ }})) {
+ NEARBY_LOGS(WARNING)
+ << "In StartBluetoothAdvertising("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "), client=" << client->GetClientId()
+ << " failed to start listening for incoming Bluetooth "
+ "connections to service_id="
+ << service_id;
+ return proto::connections::UNKNOWN_MEDIUM;
+ }
+ NEARBY_LOGS(INFO)
+ << "In StartBluetoothAdvertising("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "), client=" << client->GetClientId()
+ << " started listening for incoming Bluetooth connections to "
+ "service_id="
+ << service_id;
+ }
+
+ // Generate a BluetoothDeviceName with which to become Bluetooth discoverable.
+ // TODO(b/169550050): Implement UWBAddress.
+ std::string device_name(BluetoothDeviceName(
+ kBluetoothDeviceNameVersion, GetPcp(), local_endpoint_id, service_id_hash,
+ local_endpoint_info, ByteArray{}, web_rtc_state));
+ if (device_name.empty()) {
+ NEARBY_LOGS(WARNING) << "In StartBluetoothAdvertising("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "), client=" << client->GetClientId()
+ << " failed to generate BluetoothDeviceName {version="
+ << static_cast<int>(kBluetoothDeviceNameVersion)
+ << ", pcp=" << PcpToStrategy(GetPcp()).GetName()
+ << ", endpoint_id=" << local_endpoint_id
+ << ", service_id_hash="
+ << absl::BytesToHexString(service_id_hash.data())
+ << ", endpoint_info="
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "}.";
+ bluetooth_medium_.StopAcceptingConnections(service_id);
+ return proto::connections::UNKNOWN_MEDIUM;
+ }
+ NEARBY_LOGS(INFO) << "In StartBluetoothAdvertising("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "), client=" << client->GetClientId()
+ << " generated BluetoothDeviceName " << device_name
+ << " with service_id=" << service_id;
+
+ // Become Bluetooth discoverable.
+ if (!bluetooth_medium_.TurnOnDiscoverability(device_name)) {
+ NEARBY_LOGS(INFO)
+ << "In StartBluetoothAdvertising("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "), client=" << client->GetClientId()
+ << " couldn't start Bluetooth advertising with BluetoothDeviceName "
+ << device_name;
+ bluetooth_medium_.StopAcceptingConnections(service_id);
+ return proto::connections::UNKNOWN_MEDIUM;
+ }
+ NEARBY_LOGS(INFO)
+ << "In StartBluetoothAdvertising("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "), client=" << client->GetClientId()
+ << " started Bluetooth advertising with BluetoothDeviceName "
+ << device_name;
+ return proto::connections::BLUETOOTH;
+}
+
+proto::connections::Medium P2pClusterPcpHandler::StartBluetoothDiscovery(
+ BluetoothDiscoveredDeviceCallback callback, ClientProxy* client,
+ const std::string& service_id) {
+ if (bluetooth_radio_.Enable() &&
+ bluetooth_medium_.StartDiscovery(std::move(callback))) {
+ NEARBY_LOGS(INFO) << "In StartBluetoothDiscovery(), client="
+ << client->GetClientId()
+ << " started scanning for Bluetooth for service_id="
+ << service_id;
+ return proto::connections::BLUETOOTH;
+ } else {
+ NEARBY_LOGS(INFO) << "In StartBluetoothDiscovery(), client="
+ << client->GetClientId()
+ << " couldn't start scanning on Bluetooth for service_id="
+ << service_id;
+ return proto::connections::UNKNOWN_MEDIUM;
+ }
+}
+
+BasePcpHandler::ConnectImplResult P2pClusterPcpHandler::BluetoothConnectImpl(
+ ClientProxy* client, BluetoothEndpoint* endpoint) {
+ NEARBY_LOGS(VERBOSE) << "Client " << client->GetClientId()
+ << " is attempting to connect to endpoint(id="
+ << endpoint->endpoint_id << ") over Bluetooth Classic.";
+ BluetoothDevice& device = endpoint->bluetooth_device;
+
+ BluetoothSocket bluetooth_socket = bluetooth_medium_.Connect(
+ device, endpoint->service_id,
+ client->GetCancellationFlag(endpoint->endpoint_id));
+ if (!bluetooth_socket.IsValid()) {
+ NEARBY_LOGS(ERROR)
+ << "In BluetoothConnectImpl(), failed to connect to Bluetooth device "
+ << device.GetName() << " for endpoint(id=" << endpoint->endpoint_id
+ << ").";
+ return BasePcpHandler::ConnectImplResult{
+ .status = {Status::kBluetoothError},
+ };
+ }
+
+ auto channel = absl::make_unique<BluetoothEndpointChannel>(
+ endpoint->endpoint_id, bluetooth_socket);
+ NEARBY_LOGS(VERBOSE) << "Client" << client->GetClientId()
+ << " created Bluetooth endpoint channel to endpoint(id="
+ << endpoint->endpoint_id << ").";
+ return BasePcpHandler::ConnectImplResult{
+ .medium = proto::connections::Medium::BLUETOOTH,
+ .status = {Status::kSuccess},
+ .endpoint_channel = std::move(channel),
+ };
+}
+
+proto::connections::Medium P2pClusterPcpHandler::StartBleAdvertising(
+ ClientProxy* client, const std::string& service_id,
+ const std::string& local_endpoint_id, const ByteArray& local_endpoint_info,
+ const AdvertisingOptions& advertising_options, WebRtcState web_rtc_state) {
+ bool fast_advertisement =
+ !advertising_options.fast_advertisement_service_uuid.empty();
+ PowerLevel power_level = advertising_options.low_power
+ ? PowerLevel::kLowPower
+ : PowerLevel::kHighPower;
+
+ // Start listening for connections before advertising in case a connection
+ // request comes in very quickly. BLE allows connecting over BLE itself, as
+ // well as advertising the Bluetooth MAC address to allow connecting over
+ // Bluetooth Classic.
+ NEARBY_LOGS(INFO) << "P2pClusterPcpHandler::StartBleAdvertising: service_id="
+ << service_id << " : start";
+ if (!ble_medium_.IsAcceptingConnections(service_id)) {
+ if (!bluetooth_radio_.Enable() ||
+ !ble_medium_.StartAcceptingConnections(
+ service_id, {.accepted_cb = [this, client, local_endpoint_info](
+ BleSocket socket,
+ const std::string& service_id) {
+ if (!socket.IsValid()) {
+ NEARBY_LOGS(WARNING)
+ << "Invalid socket in accept callback("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "), client=" << client->GetClientId();
+ return;
+ }
+ RunOnPcpHandlerThread(
+ "p2p-ble-on-incoming-connection",
+ [this, client, local_endpoint_info, service_id,
+ socket = std::move(socket)]()
+ RUN_ON_PCP_HANDLER_THREAD() mutable {
+ std::string remote_peripheral_name =
+ socket.GetRemotePeripheral().GetName();
+ auto channel = absl::make_unique<BleEndpointChannel>(
+ remote_peripheral_name, socket);
+ ByteArray remote_peripheral_info =
+ socket.GetRemotePeripheral().GetAdvertisementBytes(
+ service_id);
+
+ OnIncomingConnection(client, remote_peripheral_info,
+ std::move(channel),
+ proto::connections::Medium::BLE);
+ });
+ }})) {
+ NEARBY_LOGS(WARNING)
+ << "In StartBleAdvertising("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "), client=" << client->GetClientId()
+ << " failed to start accepting for incoming BLE connections to "
+ "service_id="
+ << service_id;
+ return proto::connections::UNKNOWN_MEDIUM;
+ }
+ NEARBY_LOGS(INFO)
+ << "In StartBleAdvertising("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "), client=" << client->GetClientId()
+ << " started accepting for incoming BLE connections to service_id="
+ << service_id;
+ }
+
+ if (ShouldAdvertiseBluetoothMacOverBle(power_level) ||
+ ShouldAcceptBluetoothConnections(advertising_options)) {
+ if (bluetooth_medium_.IsAvailable() &&
+ !bluetooth_medium_.IsAcceptingConnections(service_id)) {
+ if (!bluetooth_radio_.Enable() ||
+ !bluetooth_medium_.StartAcceptingConnections(
+ service_id, {.accepted_cb = [this, client, local_endpoint_info](
+ BluetoothSocket socket) {
+ if (!socket.IsValid()) {
+ NEARBY_LOGS(WARNING)
+ << "In BT StartAcceptingConnections.accepted_cb("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "), client=" << client->GetClientId()
+ << ": Invalid socket in accept callback.";
+ return;
+ }
+ RunOnPcpHandlerThread(
+ "p2p-bt-on-incoming-connection",
+ [this, client, local_endpoint_info,
+ socket = std::move(socket)]()
+ RUN_ON_PCP_HANDLER_THREAD() mutable {
+ std::string remote_device_name =
+ socket.GetRemoteDevice().GetName();
+ auto channel =
+ absl::make_unique<BluetoothEndpointChannel>(
+ remote_device_name, socket);
+ ByteArray remote_device_info{remote_device_name};
+
+ OnIncomingConnection(
+ client, remote_device_info, std::move(channel),
+ proto::connections::Medium::BLUETOOTH);
+ });
+ }})) {
+ NEARBY_LOGS(WARNING)
+ << "In BT StartBleAdvertising("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "), client=" << client->GetClientId()
+ << " failed to start accepting for incoming BLE connections to "
+ "service_id="
+ << service_id;
+ ble_medium_.StopAcceptingConnections(service_id);
+ return proto::connections::UNKNOWN_MEDIUM;
+ }
+ NEARBY_LOGS(INFO)
+ << "In BT StartBleAdvertising("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "), client=" << client->GetClientId()
+ << " started accepting for incoming BLE connections to service_id="
+ << service_id;
+ }
+ }
+
+ NEARBY_LOGS(INFO) << "In StartBleAdvertising("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "), client=" << client->GetClientId()
+ << " start to generate BleAdvertisement with service_id="
+ << service_id
+ << ", local endpoint_id=" << local_endpoint_id;
+ // Generate a BleAdvertisement. If a fast advertisement service UUID was
+ // provided, create a fast BleAdvertisement.
+ ByteArray advertisement_bytes;
+ // TODO(b/169550050): Implement UWBAddress.
+ if (fast_advertisement) {
+ advertisement_bytes = ByteArray(
+ BleAdvertisement(kBleAdvertisementVersion, GetPcp(), local_endpoint_id,
+ local_endpoint_info, ByteArray{}));
+ } else {
+ const ByteArray service_id_hash =
+ GenerateHash(service_id, BleAdvertisement::kServiceIdHashLength);
+ std::string bluetooth_mac_address;
+ if (bluetooth_medium_.IsAvailable() &&
+ ShouldAdvertiseBluetoothMacOverBle(power_level))
+ bluetooth_mac_address = bluetooth_medium_.GetMacAddress();
+
+ advertisement_bytes = ByteArray(
+ BleAdvertisement(kBleAdvertisementVersion, GetPcp(), service_id_hash,
+ local_endpoint_id, local_endpoint_info,
+ bluetooth_mac_address, ByteArray{}, web_rtc_state));
+ }
+ if (advertisement_bytes.Empty()) {
+ NEARBY_LOGS(WARNING) << "In StartBleAdvertising("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "), client=" << client->GetClientId()
+ << " failed to create an advertisement.",
+ ble_medium_.StopAcceptingConnections(service_id);
+ return proto::connections::UNKNOWN_MEDIUM;
+ }
+
+ NEARBY_LOGS(INFO) << "In StartBleAdvertising("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "), client=" << client->GetClientId()
+ << " generated BleAdvertisement with service_id="
+ << service_id;
+
+ if (!ble_medium_.StartAdvertising(
+ service_id, advertisement_bytes,
+ advertising_options.fast_advertisement_service_uuid)) {
+ NEARBY_LOGS(WARNING)
+ << "In StartBleAdvertising("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "), client=" << client->GetClientId()
+ << " couldn't start BLE Advertising with BleAdvertisement "
+ << absl::BytesToHexString(advertisement_bytes.data());
+ ble_medium_.StopAcceptingConnections(service_id);
+ return proto::connections::UNKNOWN_MEDIUM;
+ }
+ NEARBY_LOGS(INFO) << "In startBleAdvertising("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "), client=" << client->GetClientId()
+ << " started BLE Advertising with BleAdvertisement "
+ << absl::BytesToHexString(advertisement_bytes.data());
+ return proto::connections::BLE;
+}
+
+proto::connections::Medium P2pClusterPcpHandler::StartBleScanning(
+ BleDiscoveredPeripheralCallback callback, ClientProxy* client,
+ const std::string& service_id,
+ const std::string& fast_advertisement_service_uuid) {
+ if (bluetooth_radio_.Enable() &&
+ ble_medium_.StartScanning(service_id, fast_advertisement_service_uuid,
+ std::move(callback))) {
+ NEARBY_LOGS(INFO)
+ << "In StartBleScanning(), client=" << client->GetClientId()
+ << " started scanning for BLE advertisements for service_id="
+ << service_id;
+ return proto::connections::BLE;
+ } else {
+ NEARBY_LOGS(INFO) << "In StartBleScanning(), client="
+ << client->GetClientId()
+ << " couldn't start scanning on BLE for service_id="
+ << service_id;
+ return proto::connections::UNKNOWN_MEDIUM;
+ }
+}
+
+BasePcpHandler::ConnectImplResult P2pClusterPcpHandler::BleConnectImpl(
+ ClientProxy* client, BleEndpoint* endpoint) {
+ NEARBY_LOGS(VERBOSE) << "Client " << client->GetClientId()
+ << " is attempting to connect to endpoint(id="
+ << endpoint->endpoint_id << ") over BLE.";
+
+ BlePeripheral& peripheral = endpoint->ble_peripheral;
+
+ BleSocket ble_socket =
+ ble_medium_.Connect(peripheral, endpoint->service_id,
+ client->GetCancellationFlag(endpoint->endpoint_id));
+ if (!ble_socket.IsValid()) {
+ NEARBY_LOGS(ERROR)
+ << "In BleConnectImpl(), failed to connect to BLE device "
+ << peripheral.GetName() << " for endpoint(id=" << endpoint->endpoint_id
+ << ").";
+ return BasePcpHandler::ConnectImplResult{
+ .status = {Status::kBleError},
+ };
+ }
+
+ auto channel =
+ absl::make_unique<BleEndpointChannel>(endpoint->endpoint_id, ble_socket);
+
+ return BasePcpHandler::ConnectImplResult{
+ .medium = proto::connections::Medium::BLE,
+ .status = {Status::kSuccess},
+ .endpoint_channel = std::move(channel),
+ };
+}
+
+proto::connections::Medium P2pClusterPcpHandler::StartWifiLanAdvertising(
+ ClientProxy* client, const std::string& service_id,
+ const std::string& local_endpoint_id, const ByteArray& local_endpoint_info,
+ WebRtcState web_rtc_state) {
+ // Start listening for connections before advertising in case a connection
+ // request comes in very quickly.
+ NEARBY_LOGS(INFO) << "P2pClusterPcpHandler::StartWifiLanAdvertising: service="
+ << service_id << ": start";
+ if (!wifi_lan_medium_.IsAcceptingConnections(service_id)) {
+ if (!wifi_lan_medium_.StartAcceptingConnections(
+ service_id,
+ {.accepted_cb = [this, client, local_endpoint_info,
+ local_endpoint_id](WifiLanSocket socket) {
+ if (!socket.IsValid()) {
+ NEARBY_LOGS(WARNING)
+ << "Invalid socket in accept callback("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "), client=" << client->GetClientId();
+ return;
+ }
+ RunOnPcpHandlerThread(
+ "p2p-wifi-on-incoming-connection",
+ [this, client, local_endpoint_id, local_endpoint_info,
+ socket = std::move(
+ socket)]() RUN_ON_PCP_HANDLER_THREAD() mutable {
+ std::string remote_service_name = local_endpoint_id;
+ auto channel = absl::make_unique<WifiLanEndpointChannel>(
+ remote_service_name, socket);
+ ByteArray remote_service_name_byte{remote_service_name};
+
+ OnIncomingConnection(client, remote_service_name_byte,
+ std::move(channel),
+ proto::connections::Medium::WIFI_LAN);
+ });
+ }})) {
+ NEARBY_LOGS(WARNING)
+ << "In StartWifiLanAdvertising("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "), client=" << client->GetClientId()
+ << " failed to start listening for incoming WifiLan connections "
+ "to service_id="
+ << service_id;
+ return proto::connections::UNKNOWN_MEDIUM;
+ }
+ NEARBY_LOGS(INFO) << "In StartWifiLanAdvertising("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "), client=" << client->GetClientId()
+ << " started listening for incoming WifiLan connections "
+ "to service_id = "
+ << service_id;
+ }
+
+ // Generate a WifiLanServiceInfo with which to become WifiLan discoverable.
+ // TODO(b/169550050): Implement UWBAddress.
+ const ByteArray service_id_hash =
+ GenerateHash(service_id, WifiLanServiceInfo::kServiceIdHashLength);
+ WifiLanServiceInfo service_info{kWifiLanServiceInfoVersion,
+ GetPcp(),
+ local_endpoint_id,
+ service_id_hash,
+ local_endpoint_info,
+ ByteArray{},
+ web_rtc_state};
+ NsdServiceInfo nsd_service_info(service_info);
+ if (!nsd_service_info.IsValid()) {
+ NEARBY_LOGS(WARNING) << "In StartWifiLanAdvertising("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "), client=" << client->GetClientId()
+ << " failed to generate WifiLanServiceInfo {version="
+ << static_cast<int>(kWifiLanServiceInfoVersion)
+ << ", pcp=" << PcpToStrategy(GetPcp()).GetName()
+ << ", endpoint_id=" << local_endpoint_id
+ << ", service_id_hash="
+ << absl::BytesToHexString(service_id_hash.data())
+ << ", endpoint_info="
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "}.";
+ wifi_lan_medium_.StopAcceptingConnections(service_id);
+ return proto::connections::UNKNOWN_MEDIUM;
+ }
+ NEARBY_LOGS(INFO) << "In StartWifiLanAdvertising("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "), client=" << client->GetClientId()
+ << " generated WifiLanServiceInfo "
+ << nsd_service_info.GetServiceName()
+ << " with service_id=" << service_id;
+
+ if (!wifi_lan_medium_.StartAdvertising(service_id, nsd_service_info)) {
+ NEARBY_LOGS(INFO) << "In StartWifiLanAdvertising("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "), client=" << client->GetClientId()
+ << " couldn't advertise with WifiLanServiceInfo "
+ << nsd_service_info.GetServiceName();
+ wifi_lan_medium_.StopAcceptingConnections(service_id);
+ return proto::connections::UNKNOWN_MEDIUM;
+ }
+ NEARBY_LOGS(INFO) << "In StartWifiLanAdvertising("
+ << absl::BytesToHexString(local_endpoint_info.data())
+ << "), client=" << client->GetClientId()
+ << " advertised with WifiLanServiceInfo "
+ << nsd_service_info.GetServiceName();
+ return proto::connections::WIFI_LAN;
+}
+
+proto::connections::Medium P2pClusterPcpHandler::StartWifiLanDiscovery(
+ WifiLanDiscoveredServiceCallback callback, ClientProxy* client,
+ const std::string& service_id) {
+ if (wifi_lan_medium_.StartDiscovery(service_id, std::move(callback))) {
+ NEARBY_LOGS(INFO) << "In StartWifiLanDiscovery(), client="
+ << client->GetClientId()
+ << " started scanning for Wifi devices for service_id="
+ << service_id;
+ return proto::connections::WIFI_LAN;
+ } else {
+ NEARBY_LOGS(INFO) << "In StartWifiLanDiscovery(), client="
+ << client->GetClientId()
+ << " couldn't start scanning on Wifi for service_id="
+ << service_id;
+ return proto::connections::UNKNOWN_MEDIUM;
+ }
+}
+
+BasePcpHandler::ConnectImplResult P2pClusterPcpHandler::WifiLanConnectImpl(
+ ClientProxy* client, WifiLanEndpoint* endpoint) {
+ NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
+ << " is attempting to connect to endpoint(id="
+ << endpoint->endpoint_id << ") over WifiLan.";
+ WifiLanSocket socket = wifi_lan_medium_.Connect(
+ endpoint->service_id, endpoint->service_info,
+ client->GetCancellationFlag(endpoint->endpoint_id));
+ NEARBY_LOGS(ERROR) << "In WifiLanConnectImpl(), connect to service "
+ << " socket=" << &socket.GetImpl()
+ << " for endpoint(id=" << endpoint->endpoint_id << ").";
+ if (!socket.IsValid()) {
+ NEARBY_LOGS(ERROR)
+ << "In WifiLanConnectImpl(), failed to connect to service "
+ << endpoint->service_info.GetServiceName()
+ << " for endpoint(id=" << endpoint->endpoint_id << ").";
+ return BasePcpHandler::ConnectImplResult{
+ .status = {Status::kWifiLanError},
+ };
+ }
+
+ auto channel =
+ absl::make_unique<WifiLanEndpointChannel>(endpoint->endpoint_id, socket);
+ NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
+ << " created WifiLan endpoint channel to endpoint(id="
+ << endpoint->endpoint_id << ").";
+ return BasePcpHandler::ConnectImplResult{
+ .medium = proto::connections::Medium::WIFI_LAN,
+ .status = {Status::kSuccess},
+ .endpoint_channel = std::move(channel),
+ };
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/p2p_cluster_pcp_handler.h b/chromium/third_party/nearby/src/connections/implementation/p2p_cluster_pcp_handler.h
new file mode 100644
index 00000000000..54fbb30dbe4
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/p2p_cluster_pcp_handler.h
@@ -0,0 +1,210 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_P2P_CLUSTER_PCP_HANDLER_H_
+#define CORE_INTERNAL_P2P_CLUSTER_PCP_HANDLER_H_
+
+#include <memory>
+#include <vector>
+
+#include "connections/implementation/base_pcp_handler.h"
+#include "connections/implementation/ble_advertisement.h"
+#include "connections/implementation/bluetooth_device_name.h"
+#include "connections/implementation/bwu_manager.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/endpoint_channel_manager.h"
+#include "connections/implementation/endpoint_manager.h"
+#include "connections/implementation/injected_bluetooth_device_store.h"
+#include "connections/implementation/mediums/bluetooth_classic.h"
+#include "connections/implementation/mediums/mediums.h"
+#ifdef NO_WEBRTC
+#include "connections/implementation/mediums/webrtc_stub.h"
+#include "connections/implementation/mediums/webrtc_socket_stub.h"
+#else
+#include "connections/implementation/mediums/webrtc.h"
+#include "connections/implementation/mediums/webrtc_socket.h"
+#endif
+#include "connections/implementation/pcp.h"
+#include "connections/implementation/wifi_lan_service_info.h"
+#include "connections/strategy.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/bluetooth_classic.h"
+#include "internal/platform/wifi_lan.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Concrete implementation of the PCPHandler for the P2P_CLUSTER PCP. This PCP
+// is reserved for mediums that can connect to multiple devices simultaneously
+// and all devices are considered equal. For asymmetric mediums, where one
+// device is a server and the others are clients, use P2PStarPCPHandler instead.
+//
+// Currently, this implementation advertises/discovers over Bluetooth and
+// connects over Bluetooth.
+class P2pClusterPcpHandler : public BasePcpHandler {
+ public:
+ P2pClusterPcpHandler(
+ Mediums* mediums, EndpointManager* endpoint_manager,
+ EndpointChannelManager* channel_manager, BwuManager* bwu_manager,
+ InjectedBluetoothDeviceStore& injected_bluetooth_device_store,
+ Pcp pcp = Pcp::kP2pCluster);
+ ~P2pClusterPcpHandler() override = default;
+
+ protected:
+ std::vector<proto::connections::Medium> GetConnectionMediumsByPriority()
+ override;
+ proto::connections::Medium GetDefaultUpgradeMedium() override;
+
+ // @PCPHandlerThread
+ BasePcpHandler::StartOperationResult StartAdvertisingImpl(
+ ClientProxy* client, const std::string& service_id,
+ const std::string& local_endpoint_id,
+ const ByteArray& local_endpoint_info,
+ const AdvertisingOptions& advertising_options) override;
+
+ // @PCPHandlerThread
+ Status StopAdvertisingImpl(ClientProxy* client) override;
+
+ // @PCPHandlerThread
+ BasePcpHandler::StartOperationResult StartDiscoveryImpl(
+ ClientProxy* client, const std::string& service_id,
+ const DiscoveryOptions& discovery_options) override;
+
+ // @PCPHandlerThread
+ Status StopDiscoveryImpl(ClientProxy* client) override;
+
+ // @PCPHandlerThread
+ Status InjectEndpointImpl(
+ ClientProxy* client, const std::string& service_id,
+ const OutOfBandConnectionMetadata& metadata) override;
+
+ // @PCPHandlerThread
+ BasePcpHandler::ConnectImplResult ConnectImpl(
+ ClientProxy* client,
+ BasePcpHandler::DiscoveredEndpoint* endpoint) override;
+
+ private:
+ // Holds the state required to re-create a BleEndpoint we see on a
+ // BlePeripheral, so BlePeripheralLostHandler can call
+ // BasePcpHandler::OnEndpointLost() with the same information as was passed
+ // in to BasePCPHandler::onEndpointFound().
+ struct BleEndpointState {
+ public:
+ BleEndpointState(const string& endpoint_id, const ByteArray& endpoint_info)
+ : endpoint_id(endpoint_id), endpoint_info(endpoint_info) {}
+
+ std::string endpoint_id;
+ ByteArray endpoint_info;
+ };
+
+ using BluetoothDiscoveredDeviceCallback =
+ BluetoothClassic::DiscoveredDeviceCallback;
+ using BleDiscoveredPeripheralCallback = Ble::DiscoveredPeripheralCallback;
+ using WifiLanDiscoveredServiceCallback = WifiLan::DiscoveredServiceCallback;
+
+ static constexpr BluetoothDeviceName::Version kBluetoothDeviceNameVersion =
+ BluetoothDeviceName::Version::kV1;
+ static constexpr BleAdvertisement::Version kBleAdvertisementVersion =
+ BleAdvertisement::Version::kV1;
+ static constexpr WifiLanServiceInfo::Version kWifiLanServiceInfoVersion =
+ WifiLanServiceInfo::Version::kV1;
+
+ static ByteArray GenerateHash(const std::string& source, size_t size);
+ static bool ShouldAdvertiseBluetoothMacOverBle(PowerLevel power_level);
+ static bool ShouldAcceptBluetoothConnections(
+ const AdvertisingOptions& advertising_options);
+
+ // Bluetooth
+ bool IsRecognizedBluetoothEndpoint(const std::string& name_string,
+ const std::string& service_id,
+ const BluetoothDeviceName& name) const;
+ void BluetoothDeviceDiscoveredHandler(ClientProxy* client,
+ const std::string& service_id,
+ BluetoothDevice device);
+ void BluetoothNameChangedHandler(ClientProxy* client,
+ const std::string& service_id,
+ BluetoothDevice device);
+ void BluetoothDeviceLostHandler(ClientProxy* client,
+ const std::string& service_id,
+ BluetoothDevice& device);
+ proto::connections::Medium StartBluetoothAdvertising(
+ ClientProxy* client, const std::string& service_id,
+ const ByteArray& service_id_hash, const std::string& local_endpoint_id,
+ const ByteArray& local_endpoint_info, WebRtcState web_rtc_state);
+ proto::connections::Medium StartBluetoothDiscovery(
+ BluetoothDiscoveredDeviceCallback callback, ClientProxy* client,
+ const std::string& service_id);
+ BasePcpHandler::ConnectImplResult BluetoothConnectImpl(
+ ClientProxy* client, BluetoothEndpoint* endpoint);
+
+ // Ble
+ // Maps a BlePeripheral to its corresponding BleEndpointState.
+ absl::flat_hash_map<std::string, BleEndpointState> found_ble_endpoints_;
+ bool IsRecognizedBleEndpoint(const std::string& service_id,
+ const BleAdvertisement& advertisement) const;
+ void BlePeripheralDiscoveredHandler(ClientProxy* client,
+ BlePeripheral& peripheral,
+ const std::string& service_id,
+ const ByteArray& advertisement_bytes,
+ bool fast_advertisement);
+ void BlePeripheralLostHandler(ClientProxy* client, BlePeripheral& peripheral,
+ const std::string& service_id);
+ proto::connections::Medium StartBleAdvertising(
+ ClientProxy* client, const std::string& service_id,
+ const std::string& local_endpoint_id,
+ const ByteArray& local_endpoint_info,
+ const AdvertisingOptions& advertising_options, WebRtcState web_rtc_state);
+ proto::connections::Medium StartBleScanning(
+ BleDiscoveredPeripheralCallback callback, ClientProxy* client,
+ const std::string& service_id,
+ const std::string& fast_advertisement_service_uuid);
+ BasePcpHandler::ConnectImplResult BleConnectImpl(ClientProxy* client,
+ BleEndpoint* endpoint);
+
+ // WifiLan
+ bool IsRecognizedWifiLanEndpoint(
+ const std::string& service_id,
+ const WifiLanServiceInfo& wifi_lan_service_info) const;
+ void WifiLanServiceDiscoveredHandler(ClientProxy* client,
+ NsdServiceInfo service_info,
+ const std::string& service_id);
+ void WifiLanServiceLostHandler(ClientProxy* client,
+ NsdServiceInfo service_info,
+ const std::string& service_id);
+ proto::connections::Medium StartWifiLanAdvertising(
+ ClientProxy* client, const std::string& service_id,
+ const std::string& local_endpoint_id,
+ const ByteArray& local_endpoint_info, WebRtcState web_rtc_state);
+ proto::connections::Medium StartWifiLanDiscovery(
+ WifiLanDiscoveredServiceCallback callback, ClientProxy* client,
+ const std::string& service_id);
+ BasePcpHandler::ConnectImplResult WifiLanConnectImpl(
+ ClientProxy* client, WifiLanEndpoint* endpoint);
+
+ BluetoothRadio& bluetooth_radio_;
+ BluetoothClassic& bluetooth_medium_;
+ Ble& ble_medium_;
+ WifiLan& wifi_lan_medium_;
+ mediums::WebRtc& webrtc_medium_;
+ InjectedBluetoothDeviceStore& injected_bluetooth_device_store_;
+ std::int64_t bluetooth_classic_discoverer_client_id_{0};
+ std::int64_t bluetooth_classic_advertiser_client_id_{0};
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_P2P_CLUSTER_PCP_HANDLER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/p2p_cluster_pcp_handler_test.cc b/chromium/third_party/nearby/src/connections/implementation/p2p_cluster_pcp_handler_test.cc
new file mode 100644
index 00000000000..c4ba4738896
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/p2p_cluster_pcp_handler_test.cc
@@ -0,0 +1,273 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/p2p_cluster_pcp_handler.h"
+
+#include <memory>
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "absl/time/time.h"
+#include "connections/implementation/bwu_manager.h"
+#include "connections/implementation/injected_bluetooth_device_store.h"
+#include "internal/platform/medium_environment.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+
+constexpr BooleanMediumSelector kTestCases[] = {
+ BooleanMediumSelector{
+ .bluetooth = true,
+ },
+ BooleanMediumSelector{
+ .wifi_lan = true,
+ },
+ BooleanMediumSelector{
+ .bluetooth = true,
+ .wifi_lan = true,
+ },
+};
+
+class P2pClusterPcpHandlerTest
+ : public ::testing::TestWithParam<BooleanMediumSelector> {
+ protected:
+ void SetUp() override {
+ NEARBY_LOG(INFO, "SetUp: begin");
+ env_.Stop();
+ if (advertising_options_.allowed.bluetooth) {
+ NEARBY_LOG(INFO, "SetUp: BT enabled");
+ }
+ if (advertising_options_.allowed.wifi_lan) {
+ NEARBY_LOG(INFO, "SetUp: WifiLan enabled");
+ }
+ if (advertising_options_.allowed.web_rtc) {
+ NEARBY_LOG(INFO, "SetUp: WebRTC enabled");
+ }
+ NEARBY_LOG(INFO, "SetUp: end");
+ }
+
+ ClientProxy client_a_;
+ ClientProxy client_b_;
+ std::string service_id_{"service"};
+ ConnectionOptions connection_options_{
+ {
+ Strategy::kP2pCluster,
+ GetParam(),
+ },
+ };
+ AdvertisingOptions advertising_options_{
+ {
+ Strategy::kP2pCluster,
+ GetParam(),
+ },
+ };
+ DiscoveryOptions discovery_options_{
+ {
+ Strategy::kP2pCluster,
+ GetParam(),
+ },
+ };
+ MediumEnvironment& env_{MediumEnvironment::Instance()};
+};
+
+TEST_P(P2pClusterPcpHandlerTest, CanConstructOne) {
+ env_.Start();
+ Mediums mediums;
+ EndpointChannelManager ecm;
+ EndpointManager em(&ecm);
+ BwuManager bwu(mediums, em, ecm, {}, {});
+ InjectedBluetoothDeviceStore ibds;
+ P2pClusterPcpHandler handler(&mediums, &em, &ecm, &bwu, ibds);
+ env_.Stop();
+}
+
+TEST_P(P2pClusterPcpHandlerTest, CanConstructMultiple) {
+ env_.Start();
+ Mediums mediums_a;
+ Mediums mediums_b;
+ EndpointChannelManager ecm_a;
+ EndpointChannelManager ecm_b;
+ EndpointManager em_a(&ecm_a);
+ EndpointManager em_b(&ecm_b);
+ BwuManager bwu_a(mediums_a, em_a, ecm_a, {}, {});
+ BwuManager bwu_b(mediums_b, em_b, ecm_b, {}, {});
+ InjectedBluetoothDeviceStore ibds_a;
+ InjectedBluetoothDeviceStore ibds_b;
+ P2pClusterPcpHandler handler_a(&mediums_a, &em_a, &ecm_a, &bwu_a, ibds_a);
+ P2pClusterPcpHandler handler_b(&mediums_b, &em_b, &ecm_b, &bwu_b, ibds_b);
+ env_.Stop();
+}
+
+TEST_P(P2pClusterPcpHandlerTest, CanAdvertise) {
+ env_.Start();
+ std::string endpoint_name{"endpoint_name"};
+ Mediums mediums_a;
+ EndpointChannelManager ecm_a;
+ EndpointManager em_a(&ecm_a);
+ BwuManager bwu_a(mediums_a, em_a, ecm_a, {}, {});
+ InjectedBluetoothDeviceStore ibds_a;
+ P2pClusterPcpHandler handler_a(&mediums_a, &em_a, &ecm_a, &bwu_a, ibds_a);
+ EXPECT_EQ(
+ handler_a.StartAdvertising(&client_a_, service_id_, advertising_options_,
+ {.endpoint_info = ByteArray{endpoint_name}}),
+ Status{Status::kSuccess});
+ env_.Stop();
+}
+
+TEST_P(P2pClusterPcpHandlerTest, CanDiscover) {
+ env_.Start();
+ std::string endpoint_name{"endpoint_name"};
+ Mediums mediums_a;
+ Mediums mediums_b;
+ EndpointChannelManager ecm_a;
+ EndpointChannelManager ecm_b;
+ EndpointManager em_a(&ecm_a);
+ EndpointManager em_b(&ecm_b);
+ BwuManager bwu_a(mediums_a, em_a, ecm_a, {}, {});
+ BwuManager bwu_b(mediums_b, em_b, ecm_b, {}, {});
+ InjectedBluetoothDeviceStore ibds_a;
+ InjectedBluetoothDeviceStore ibds_b;
+ P2pClusterPcpHandler handler_a(&mediums_a, &em_a, &ecm_a, &bwu_a, ibds_a);
+ P2pClusterPcpHandler handler_b(&mediums_b, &em_b, &ecm_b, &bwu_b, ibds_b);
+ CountDownLatch latch(1);
+ EXPECT_EQ(
+ handler_a.StartAdvertising(&client_a_, service_id_, advertising_options_,
+ {.endpoint_info = ByteArray{endpoint_name}}),
+ Status{Status::kSuccess});
+ EXPECT_EQ(handler_b.StartDiscovery(
+ &client_b_, service_id_, discovery_options_,
+ {
+ .endpoint_found_cb =
+ [&latch](const std::string& endpoint_id,
+ const ByteArray& endpoint_info,
+ const std::string& service_id) {
+ NEARBY_LOG(INFO, "Device discovered: id=%s",
+ endpoint_id.c_str());
+ latch.CountDown();
+ },
+ }),
+ Status{Status::kSuccess});
+ EXPECT_TRUE(latch.Await(absl::Milliseconds(1000)).result());
+ // We discovered endpoint over one medium. Before we finish the test, we have
+ // to stop discovery for other mediums that may be still ongoing.
+ handler_b.StopDiscovery(&client_b_);
+ env_.Stop();
+}
+
+TEST_P(P2pClusterPcpHandlerTest, CanConnect) {
+ env_.Start();
+ std::string endpoint_name_a{"endpoint_name"};
+ Mediums mediums_a;
+ Mediums mediums_b;
+ BluetoothRadio& radio_a = mediums_a.GetBluetoothRadio();
+ BluetoothRadio& radio_b = mediums_b.GetBluetoothRadio();
+ radio_a.GetBluetoothAdapter().SetName("BT Device A");
+ radio_b.GetBluetoothAdapter().SetName("BT Device B");
+ EndpointChannelManager ecm_a;
+ EndpointChannelManager ecm_b;
+ EndpointManager em_a(&ecm_a);
+ EndpointManager em_b(&ecm_b);
+ BwuManager bwu_a(mediums_a, em_a, ecm_a, {},
+ {.allow_upgrade_to = {.bluetooth = true}});
+ BwuManager bwu_b(mediums_b, em_b, ecm_b, {},
+ {.allow_upgrade_to = {.bluetooth = true}});
+ InjectedBluetoothDeviceStore ibds_a;
+ InjectedBluetoothDeviceStore ibds_b;
+ P2pClusterPcpHandler handler_a(&mediums_a, &em_a, &ecm_a, &bwu_a, ibds_a);
+ P2pClusterPcpHandler handler_b(&mediums_b, &em_b, &ecm_b, &bwu_b, ibds_b);
+ CountDownLatch discover_latch(1);
+ CountDownLatch connect_latch(2);
+ struct DiscoveredInfo {
+ std::string endpoint_id;
+ ByteArray endpoint_info;
+ std::string service_id;
+ } discovered;
+ EXPECT_EQ(
+ handler_a.StartAdvertising(
+ &client_a_, service_id_, advertising_options_,
+ {
+ .endpoint_info = ByteArray{endpoint_name_a},
+ .listener =
+ {
+ .initiated_cb =
+ [&connect_latch](const std::string& endpoint_id,
+ const ConnectionResponseInfo& info) {
+ NEARBY_LOG(INFO,
+ "StartAdvertising: initiated_cb called");
+ connect_latch.CountDown();
+ },
+ },
+ }),
+ Status{Status::kSuccess});
+ EXPECT_EQ(handler_b.StartDiscovery(
+ &client_b_, service_id_, discovery_options_,
+ {
+ .endpoint_found_cb =
+ [&discover_latch, &discovered](
+ const std::string& endpoint_id,
+ const ByteArray& endpoint_info,
+ const std::string& service_id) {
+ NEARBY_LOG(
+ INFO,
+ "Device discovered: id=%s, endpoint_info=%s",
+ endpoint_id.c_str(),
+ std::string{endpoint_info}.c_str());
+ discovered = {
+ .endpoint_id = endpoint_id,
+ .endpoint_info = endpoint_info,
+ .service_id = service_id,
+ };
+ discover_latch.CountDown();
+ },
+ }),
+ Status{Status::kSuccess});
+
+ EXPECT_TRUE(discover_latch.Await(absl::Milliseconds(1000)).result());
+ EXPECT_EQ(endpoint_name_a, std::string{discovered.endpoint_info});
+
+ client_b_.AddCancellationFlag(discovered.endpoint_id);
+ handler_b.RequestConnection(
+ &client_b_, discovered.endpoint_id,
+ {
+ .endpoint_info = discovered.endpoint_info,
+ .listener =
+ {
+ .initiated_cb =
+ [&connect_latch](const std::string& endpoint_id,
+ const ConnectionResponseInfo& info) {
+ NEARBY_LOG(INFO,
+ "RequestConnection: initiated_cb called");
+ connect_latch.CountDown();
+ },
+ },
+ },
+ connection_options_);
+ EXPECT_TRUE(connect_latch.Await(absl::Milliseconds(1000)).result());
+ bwu_a.Shutdown();
+ bwu_b.Shutdown();
+ env_.Stop();
+}
+
+INSTANTIATE_TEST_SUITE_P(ParametrisedPcpHandlerTest, P2pClusterPcpHandlerTest,
+ ::testing::ValuesIn(kTestCases));
+
+} // namespace
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/p2p_point_to_point_pcp_handler.cc b/chromium/third_party/nearby/src/connections/implementation/p2p_point_to_point_pcp_handler.cc
new file mode 100644
index 00000000000..1ff1dd748d6
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/p2p_point_to_point_pcp_handler.cc
@@ -0,0 +1,64 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/p2p_point_to_point_pcp_handler.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+P2pPointToPointPcpHandler::P2pPointToPointPcpHandler(
+ Mediums& mediums, EndpointManager& endpoint_manager,
+ EndpointChannelManager& channel_manager, BwuManager& bwu_manager,
+ InjectedBluetoothDeviceStore& injected_bluetooth_device_store, Pcp pcp)
+ : P2pStarPcpHandler(mediums, endpoint_manager, channel_manager, bwu_manager,
+ injected_bluetooth_device_store, pcp) {}
+
+std::vector<proto::connections::Medium>
+P2pPointToPointPcpHandler::GetConnectionMediumsByPriority() {
+ std::vector<proto::connections::Medium> mediums;
+ if (mediums_->GetWifiLan().IsAvailable()) {
+ mediums.push_back(proto::connections::WIFI_LAN);
+ }
+ if (mediums_->GetWebRtc().IsAvailable()) {
+ mediums.push_back(proto::connections::WEB_RTC);
+ }
+ if (mediums_->GetBluetoothClassic().IsAvailable()) {
+ mediums.push_back(proto::connections::BLUETOOTH);
+ }
+ if (mediums_->GetBle().IsAvailable()) {
+ mediums.push_back(proto::connections::BLE);
+ }
+ return mediums;
+}
+
+bool P2pPointToPointPcpHandler::CanSendOutgoingConnection(
+ ClientProxy* client) const {
+ // For point to point, we can only send an outgoing connection while we have
+ // no other connections.
+ return !this->HasOutgoingConnections(client) &&
+ !this->HasIncomingConnections(client);
+}
+
+bool P2pPointToPointPcpHandler::CanReceiveIncomingConnection(
+ ClientProxy* client) const {
+ // For point to point, we can only receive an incoming connection while we
+ // have no other connections.
+ return !this->HasOutgoingConnections(client) &&
+ !this->HasIncomingConnections(client);
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/p2p_point_to_point_pcp_handler.h b/chromium/third_party/nearby/src/connections/implementation/p2p_point_to_point_pcp_handler.h
new file mode 100644
index 00000000000..fa1f74668b9
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/p2p_point_to_point_pcp_handler.h
@@ -0,0 +1,55 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_P2P_POINT_TO_POINT_PCP_HANDLER_H_
+#define CORE_INTERNAL_P2P_POINT_TO_POINT_PCP_HANDLER_H_
+
+#include "connections/implementation/endpoint_channel_manager.h"
+#include "connections/implementation/endpoint_manager.h"
+#include "connections/implementation/p2p_star_pcp_handler.h"
+#include "connections/implementation/pcp.h"
+#include "connections/strategy.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Concrete implementation of the PCPHandler for the P2P_POINT_TO_POINT. This
+// PCP is for mediums that have limitations on the number of simultaneous
+// connections; all mediums in P2P_STAR are valid for P2P_POINT_TO_POINT, but
+// not all mediums in P2P_POINT_TO_POINT are valid for P2P_STAR.
+//
+// Currently, this implementation advertises/discovers over Bluetooth
+// and connects over Bluetooth.
+class P2pPointToPointPcpHandler : public P2pStarPcpHandler {
+ public:
+ P2pPointToPointPcpHandler(
+ Mediums& mediums, EndpointManager& endpoint_manager,
+ EndpointChannelManager& channel_manager, BwuManager& bwu_manager,
+ InjectedBluetoothDeviceStore& injected_bluetooth_device_store,
+ Pcp pcp = Pcp::kP2pPointToPoint);
+
+ protected:
+ std::vector<proto::connections::Medium> GetConnectionMediumsByPriority()
+ override;
+
+ bool CanSendOutgoingConnection(ClientProxy* client) const override;
+ bool CanReceiveIncomingConnection(ClientProxy* client) const override;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_P2P_POINT_TO_POINT_PCP_HANDLER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/p2p_star_pcp_handler.cc b/chromium/third_party/nearby/src/connections/implementation/p2p_star_pcp_handler.cc
new file mode 100644
index 00000000000..53363313837
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/p2p_star_pcp_handler.cc
@@ -0,0 +1,69 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/p2p_star_pcp_handler.h"
+
+#include <vector>
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+P2pStarPcpHandler::P2pStarPcpHandler(
+ Mediums& mediums, EndpointManager& endpoint_manager,
+ EndpointChannelManager& channel_manager, BwuManager& bwu_manager,
+ InjectedBluetoothDeviceStore& injected_bluetooth_device_store, Pcp pcp)
+ : P2pClusterPcpHandler(&mediums, &endpoint_manager, &channel_manager,
+ &bwu_manager, injected_bluetooth_device_store, pcp) {
+}
+
+std::vector<proto::connections::Medium>
+P2pStarPcpHandler::GetConnectionMediumsByPriority() {
+ std::vector<proto::connections::Medium> mediums;
+ if (mediums_->GetWifiLan().IsAvailable()) {
+ mediums.push_back(proto::connections::WIFI_LAN);
+ }
+ if (mediums_->GetWebRtc().IsAvailable()) {
+ mediums.push_back(proto::connections::WEB_RTC);
+ }
+ if (mediums_->GetBluetoothClassic().IsAvailable()) {
+ mediums.push_back(proto::connections::BLUETOOTH);
+ }
+ if (mediums_->GetBle().IsAvailable()) {
+ mediums.push_back(proto::connections::BLE);
+ }
+ return mediums;
+}
+
+proto::connections::Medium P2pStarPcpHandler::GetDefaultUpgradeMedium() {
+ return proto::connections::Medium::WIFI_HOTSPOT;
+}
+
+bool P2pStarPcpHandler::CanSendOutgoingConnection(ClientProxy* client) const {
+ // For star, we can only send an outgoing connection while we have no other
+ // connections.
+ return !this->HasOutgoingConnections(client) &&
+ !this->HasIncomingConnections(client);
+}
+
+bool P2pStarPcpHandler::CanReceiveIncomingConnection(
+ ClientProxy* client) const {
+ // For star, we can only receive an incoming connection if we've sent no
+ // outgoing connections.
+ return !this->HasOutgoingConnections(client);
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/p2p_star_pcp_handler.h b/chromium/third_party/nearby/src/connections/implementation/p2p_star_pcp_handler.h
new file mode 100644
index 00000000000..83bd845f081
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/p2p_star_pcp_handler.h
@@ -0,0 +1,59 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_P2P_STAR_PCP_HANDLER_H_
+#define CORE_INTERNAL_P2P_STAR_PCP_HANDLER_H_
+
+#include <vector>
+
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/endpoint_channel_manager.h"
+#include "connections/implementation/endpoint_manager.h"
+#include "connections/implementation/p2p_cluster_pcp_handler.h"
+#include "connections/implementation/pcp.h"
+#include "connections/strategy.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Concrete implementation of the PcpHandler for the P2P_STAR PCP. This Pcp is
+// for mediums that have one server with (potentially) many clients; all mediums
+// in P2P_CLUSTER are valid for P2P_STAR, but not all mediums in P2P_STAR are
+// valid for P2P_CLUSTER.
+//
+// Currently, this implementation advertises/discovers over Bluetooth
+// and connects over Bluetooth.
+class P2pStarPcpHandler : public P2pClusterPcpHandler {
+ public:
+ P2pStarPcpHandler(
+ Mediums& mediums, EndpointManager& endpoint_manager,
+ EndpointChannelManager& channel_manager, BwuManager& bwu_manager,
+ InjectedBluetoothDeviceStore& injected_bluetooth_device_store,
+ Pcp pcp = Pcp::kP2pStar);
+
+ protected:
+ std::vector<proto::connections::Medium> GetConnectionMediumsByPriority()
+ override;
+ proto::connections::Medium GetDefaultUpgradeMedium() override;
+
+ bool CanSendOutgoingConnection(ClientProxy* client) const override;
+ bool CanReceiveIncomingConnection(ClientProxy* client) const override;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_P2P_STAR_PCP_HANDLER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/payload_manager.cc b/chromium/third_party/nearby/src/connections/implementation/payload_manager.cc
new file mode 100644
index 00000000000..7847df0d463
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/payload_manager.cc
@@ -0,0 +1,1318 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/payload_manager.h"
+
+#include <algorithm>
+#include <limits>
+#include <memory>
+#include <string>
+#include <utility>
+
+#include "absl/memory/memory.h"
+#include "absl/strings/str_cat.h"
+#include "absl/time/time.h"
+#include "connections/implementation/internal_payload_factory.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/mutex_lock.h"
+#include "internal/platform/single_thread_executor.h"
+#include "internal/platform/system_clock.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// C++14 requires to declare this.
+// TODO(apolyudov): remove when migration to c++17 is possible.
+constexpr const absl::Duration PayloadManager::kWaitCloseTimeout;
+
+bool PayloadManager::SendPayloadLoop(
+ ClientProxy* client, PendingPayload& pending_payload,
+ PayloadTransferFrame::PayloadHeader& payload_header,
+ std::int64_t& next_chunk_offset, size_t resume_offset) {
+ // in lieu of structured binding:
+ auto pair = GetAvailableAndUnavailableEndpoints(pending_payload);
+ const EndpointIds& available_endpoint_ids =
+ EndpointsToEndpointIds(pair.first);
+ const Endpoints& unavailable_endpoints = pair.second;
+
+ // First, handle any non-available endpoints.
+ for (const auto& endpoint : unavailable_endpoints) {
+ HandleFinishedOutgoingPayload(
+ client, {endpoint->id}, payload_header, next_chunk_offset,
+ EndpointInfoStatusToPayloadStatus(endpoint->status.Get()));
+ }
+
+ // Update the still-active recipients of this payload.
+ if (available_endpoint_ids.empty()) {
+ NEARBY_LOGS(INFO)
+ << "PayloadManager short-circuiting payload_id="
+ << pending_payload.GetInternalPayload()->GetId() << " after sending "
+ << next_chunk_offset
+ << " bytes because none of the endpoints are available anymore.";
+ return false;
+ }
+
+ // Check if the payload has been cancelled by the client and, if so,
+ // notify the remaining recipients.
+ if (pending_payload.IsLocallyCanceled()) {
+ NEARBY_LOGS(INFO) << "Aborting send of payload_id="
+ << pending_payload.GetInternalPayload()->GetId()
+ << " at offset " << next_chunk_offset
+ << " since it is marked canceled.";
+ HandleFinishedOutgoingPayload(
+ client, available_endpoint_ids, payload_header, next_chunk_offset,
+ proto::connections::PayloadStatus::LOCAL_CANCELLATION);
+ return false;
+ }
+
+ // Update the current offsets for all endpoints still active for this
+ // payload. For the sake of accuracy, we update the pending payload here
+ // because it's after all payload terminating events are handled, but
+ // right before we actually start detaching the next chunk.
+ if (next_chunk_offset == 0 && resume_offset > 0) {
+ ExceptionOr<size_t> real_offset =
+ pending_payload.GetInternalPayload()->SkipToOffset(resume_offset);
+ if (!real_offset.ok()) {
+ // Stop sending since it may cause remote file merging failed.
+ NEARBY_LOGS(WARNING) << "PayloadManager failed to skip offset "
+ << resume_offset << " on payload_id "
+ << pending_payload.GetInternalPayload()->GetId();
+ HandleFinishedOutgoingPayload(
+ client, available_endpoint_ids, payload_header, next_chunk_offset,
+ proto::connections::PayloadStatus::LOCAL_ERROR);
+ return false;
+ }
+ NEARBY_LOGS(VERBOSE) << "PayloadManager successfully skipped "
+ << real_offset.GetResult() << " bytes on payload_id "
+ << pending_payload.GetInternalPayload()->GetId();
+ next_chunk_offset = real_offset.GetResult();
+ }
+ for (const auto& endpoint_id : available_endpoint_ids) {
+ pending_payload.SetOffsetForEndpoint(endpoint_id, next_chunk_offset);
+ }
+
+ // This will block if there is no data to transfer.
+ // It will resume when new data arrives, or if Close() is called.
+ int chunk_size = GetOptimalChunkSize(available_endpoint_ids);
+ ByteArray next_chunk =
+ pending_payload.GetInternalPayload()->DetachNextChunk(chunk_size);
+ if (shutdown_.Get()) return false;
+ // Save chunk size. We'll need it after we move next_chunk.
+ auto next_chunk_size = next_chunk.size();
+ if (!next_chunk_size &&
+ pending_payload.GetInternalPayload()->GetTotalSize() > 0 &&
+ pending_payload.GetInternalPayload()->GetTotalSize() <
+ next_chunk_offset) {
+ NEARBY_LOGS(INFO) << "Payload xfer failed: payload_id="
+ << pending_payload.GetInternalPayload()->GetId();
+ HandleFinishedOutgoingPayload(
+ client, available_endpoint_ids, payload_header, next_chunk_offset,
+ proto::connections::PayloadStatus::LOCAL_ERROR);
+ return false;
+ }
+
+ // Only need to handle outgoing data chunk offset, because the offset will be
+ // used to decide if the received chunk is the initial payload chunk.
+ // In other cases, the offset should only be used in both side logs when error
+ // happened.
+ PayloadTransferFrame::PayloadChunk payload_chunk(CreatePayloadChunk(
+ next_chunk_offset - resume_offset, std::move(next_chunk)));
+ const EndpointIds& failed_endpoint_ids = endpoint_manager_->SendPayloadChunk(
+ payload_header, payload_chunk, available_endpoint_ids);
+ // Check whether at least one endpoint failed.
+ if (!failed_endpoint_ids.empty()) {
+ NEARBY_LOGS(INFO) << "Payload xfer: endpoints failed: payload_id="
+ << payload_header.id() << "; endpoint_ids={"
+ << ToString(failed_endpoint_ids) << "}",
+ HandleFinishedOutgoingPayload(
+ client, failed_endpoint_ids, payload_header, next_chunk_offset,
+ proto::connections::PayloadStatus::ENDPOINT_IO_ERROR);
+ }
+
+ // Check whether at least one endpoint succeeded -- if they all failed,
+ // we'll just go right back to the top of the loop and break out when
+ // availableEndpointIds is re-synced and found to be empty at that point.
+ if (failed_endpoint_ids.size() < available_endpoint_ids.size()) {
+ for (const auto& endpoint_id : available_endpoint_ids) {
+ if (std::find(failed_endpoint_ids.begin(), failed_endpoint_ids.end(),
+ endpoint_id) == failed_endpoint_ids.end()) {
+ HandleSuccessfulOutgoingChunk(
+ client, endpoint_id, payload_header, payload_chunk.flags(),
+ payload_chunk.offset(), payload_chunk.body().size());
+ }
+ }
+ NEARBY_LOGS(VERBOSE) << "PayloadManager done sending chunk at offset "
+ << next_chunk_offset << " of payload_id="
+ << pending_payload.GetInternalPayload()->GetId();
+ next_chunk_offset += next_chunk_size;
+
+ if (!next_chunk_size) {
+ // That was the last chunk, we're outta here.
+ NEARBY_LOGS(INFO) << "Payload xfer done: payload_id="
+ << pending_payload.GetInternalPayload()->GetId()
+ << "; size=" << next_chunk_offset;
+ return false;
+ }
+ }
+
+ return true;
+}
+
+std::pair<PayloadManager::Endpoints, PayloadManager::Endpoints>
+PayloadManager::GetAvailableAndUnavailableEndpoints(
+ const PendingPayload& pending_payload) {
+ Endpoints available;
+ Endpoints unavailable;
+ for (auto* endpoint_info : pending_payload.GetEndpoints()) {
+ if (endpoint_info->status.Get() ==
+ PayloadManager::EndpointInfo::Status::kAvailable) {
+ available.push_back(endpoint_info);
+ } else {
+ unavailable.push_back(endpoint_info);
+ }
+ }
+ return std::make_pair(std::move(available), std::move(unavailable));
+}
+
+PayloadManager::EndpointIds PayloadManager::EndpointsToEndpointIds(
+ const Endpoints& endpoints) {
+ EndpointIds endpoint_ids;
+ endpoint_ids.reserve(endpoints.size());
+ for (const auto& item : endpoints) {
+ if (item) {
+ endpoint_ids.emplace_back(item->id);
+ }
+ }
+ return endpoint_ids;
+}
+
+std::string PayloadManager::ToString(const Endpoints& endpoints) {
+ std::string endpoints_string = absl::StrCat(endpoints.size(), ": ");
+ bool first = true;
+ for (const auto& item : endpoints) {
+ if (first) {
+ absl::StrAppend(&endpoints_string, item->id);
+ first = false;
+ } else {
+ absl::StrAppend(&endpoints_string, ", ", item->id);
+ }
+ }
+ return endpoints_string;
+}
+
+std::string PayloadManager::ToString(const EndpointIds& endpoint_ids) {
+ std::string endpoints_string = absl::StrCat(endpoint_ids.size(), ": ");
+ bool first = true;
+ for (const auto& id : endpoint_ids) {
+ if (first) {
+ absl::StrAppend(&endpoints_string, id);
+ first = false;
+ } else {
+ absl::StrAppend(&endpoints_string, ", ", id);
+ }
+ }
+ return endpoints_string;
+}
+
+std::string PayloadManager::ToString(Payload::Type type) {
+ switch (type) {
+ case Payload::Type::kBytes:
+ return std::string("Bytes");
+ case Payload::Type::kStream:
+ return std::string("Stream");
+ case Payload::Type::kFile:
+ return std::string("File");
+ case Payload::Type::kUnknown:
+ return std::string("Unknown");
+ }
+}
+
+std::string PayloadManager::ToString(EndpointInfo::Status status) {
+ switch (status) {
+ case EndpointInfo::Status::kAvailable:
+ return std::string("Available");
+ case EndpointInfo::Status::kCanceled:
+ return std::string("Cancelled");
+ case EndpointInfo::Status::kError:
+ return std::string("Error");
+ case EndpointInfo::Status::kUnknown:
+ return std::string("Unknown");
+ }
+}
+
+// Creates and starts tracking a PendingPayload for this Payload.
+Payload::Id PayloadManager::CreateOutgoingPayload(
+ Payload payload, const EndpointIds& endpoint_ids) {
+ auto internal_payload{CreateOutgoingInternalPayload(std::move(payload))};
+ Payload::Id payload_id = internal_payload->GetId();
+ NEARBY_LOGS(INFO) << "CreateOutgoingPayload: payload_id=" << payload_id;
+ MutexLock lock(&mutex_);
+ pending_payloads_.StartTrackingPayload(
+ payload_id, absl::make_unique<PendingPayload>(std::move(internal_payload),
+ endpoint_ids,
+ /*is_incoming=*/false));
+
+ return payload_id;
+}
+
+PayloadManager::PayloadManager(EndpointManager& endpoint_manager)
+ : endpoint_manager_(&endpoint_manager) {
+ endpoint_manager_->RegisterFrameProcessor(V1Frame::PAYLOAD_TRANSFER, this);
+}
+
+void PayloadManager::CancelAllPayloads() {
+ NEARBY_LOG(INFO, "PayloadManager: canceling payloads; self=%p", this);
+ {
+ MutexLock lock(&mutex_);
+ int pending_outgoing_payloads = 0;
+ for (const auto& pending_id : pending_payloads_.GetAllPayloads()) {
+ auto* pending = pending_payloads_.GetPayload(pending_id);
+ if (!pending->IsIncoming()) pending_outgoing_payloads++;
+ pending->MarkLocallyCanceled();
+ pending->Close(); // To unblock the sender thread, if there is no data.
+ }
+ if (pending_outgoing_payloads) {
+ shutdown_barrier_ =
+ absl::make_unique<CountDownLatch>(pending_outgoing_payloads);
+ }
+ }
+
+ if (shutdown_barrier_) {
+ NEARBY_LOG(INFO,
+ "PayloadManager: waiting for pending outgoing payloads; self=%p",
+ this);
+ shutdown_barrier_->Await();
+ }
+}
+
+void PayloadManager::DisconnectFromEndpointManager() {
+ if (shutdown_.Set(true)) return;
+ // Unregister ourselves from the FrameProcessors.
+ endpoint_manager_->UnregisterFrameProcessor(V1Frame::PAYLOAD_TRANSFER, this);
+}
+
+PayloadManager::~PayloadManager() {
+ NEARBY_LOG(INFO, "PayloadManager: going down; self=%p", this);
+ DisconnectFromEndpointManager();
+ CancelAllPayloads();
+ NEARBY_LOG(INFO, "PayloadManager: turn down payload executors; self=%p",
+ this);
+ bytes_payload_executor_.Shutdown();
+ stream_payload_executor_.Shutdown();
+ file_payload_executor_.Shutdown();
+
+ CountDownLatch stop_latch(1);
+ // Clear our tracked pending payloads.
+ RunOnStatusUpdateThread(
+ "~payload-manager",
+ [this, &stop_latch]() RUN_ON_PAYLOAD_STATUS_UPDATE_THREAD() {
+ NEARBY_LOG(INFO, "PayloadManager: stop tracking payloads; self=%p",
+ this);
+ MutexLock lock(&mutex_);
+ for (const auto& pending_id : pending_payloads_.GetAllPayloads()) {
+ pending_payloads_.StopTrackingPayload(pending_id);
+ }
+ stop_latch.CountDown();
+ });
+ stop_latch.Await();
+
+ NEARBY_LOG(INFO, "PayloadManager: turn down notification executor; self=%p",
+ this);
+ // Stop all the ongoing Runnables (as gracefully as possible).
+ payload_status_update_executor_.Shutdown();
+
+ NEARBY_LOG(INFO, "PayloadManager: down; self=%p", this);
+}
+
+bool PayloadManager::NotifyShutdown() {
+ MutexLock lock(&mutex_);
+ if (!shutdown_.Get()) return false;
+ if (!shutdown_barrier_) return false;
+ NEARBY_LOG(INFO, "PayloadManager [shutdown mode]");
+ shutdown_barrier_->CountDown();
+ return true;
+}
+
+void PayloadManager::SendPayload(ClientProxy* client,
+ const EndpointIds& endpoint_ids,
+ Payload payload) {
+ if (shutdown_.Get()) return;
+ NEARBY_LOG(INFO, "SendPayload: endpoint_ids={%s}",
+ ToString(endpoint_ids).c_str());
+ // Before transfer to internal payload, retrieves the Payload size for
+ // analytics.
+ std::int64_t payload_total_size;
+ switch (payload.GetType()) {
+ case connections::Payload::Type::kBytes:
+ payload_total_size = payload.AsBytes().size();
+ break;
+ case connections::Payload::Type::kFile:
+ payload_total_size = payload.AsFile()->GetTotalSize();
+ break;
+ case connections::Payload::Type::kStream:
+ case connections::Payload::Type::kUnknown:
+ payload_total_size = -1;
+ break;
+ }
+
+ auto executor = GetOutgoingPayloadExecutor(payload.GetType());
+ // The |executor| will be null if the payload is of a type we cannot work
+ // with. This should never be reached since the ServiceControllerRouter has
+ // already checked whether or not we can work with this Payload type.
+ if (!executor) {
+ RecordInvalidPayloadAnalytics(client, endpoint_ids, payload.GetId(),
+ payload.GetType(), payload.GetOffset(),
+ payload_total_size);
+ NEARBY_LOGS(INFO)
+ << "PayloadManager failed to determine the right executor for "
+ "outgoing payload_id="
+ << payload.GetId() << ", payload_type=" << ToString(payload.GetType());
+ return;
+ }
+
+ // Each payload is sent in FCFS order within each Payload type, blocking any
+ // other payload of the same type from even starting until this one is
+ // completely done with. If we ever want to provide isolation across
+ // ClientProxy objects this will need to be significantly re-architected.
+ Payload::Type payload_type = payload.GetType();
+ size_t resume_offset =
+ FeatureFlags::GetInstance().GetFlags().enable_send_payload_offset
+ ? payload.GetOffset()
+ : 0;
+
+ Payload::Id payload_id =
+ CreateOutgoingPayload(std::move(payload), endpoint_ids);
+ executor->Execute(
+ "send-payload", [this, client, endpoint_ids, payload_id, payload_type,
+ resume_offset, payload_total_size]() {
+ if (shutdown_.Get()) return;
+ PendingPayload* pending_payload = GetPayload(payload_id);
+ if (!pending_payload) {
+ RecordInvalidPayloadAnalytics(client, endpoint_ids, payload_id,
+ payload_type, resume_offset,
+ payload_total_size);
+ NEARBY_LOGS(INFO)
+ << "PayloadManager failed to create InternalPayload for outgoing "
+ "payload_id="
+ << payload_id << ", payload_type=" << ToString(payload_type)
+ << ", aborting sendPayload().";
+ return;
+ }
+ auto* internal_payload = pending_payload->GetInternalPayload();
+ if (!internal_payload) return;
+
+ RecordPayloadStartedAnalytics(client, endpoint_ids, payload_id,
+ payload_type, resume_offset,
+ internal_payload->GetTotalSize());
+
+ PayloadTransferFrame::PayloadHeader payload_header{
+ CreatePayloadHeader(*internal_payload, resume_offset)};
+ bool should_continue = true;
+ std::int64_t next_chunk_offset = 0;
+ while (should_continue && !shutdown_.Get()) {
+ should_continue =
+ SendPayloadLoop(client, *pending_payload, payload_header,
+ next_chunk_offset, resume_offset);
+ }
+ RunOnStatusUpdateThread("destroy-payload",
+ [this, payload_id]()
+ RUN_ON_PAYLOAD_STATUS_UPDATE_THREAD() {
+ DestroyPendingPayload(payload_id);
+ });
+ });
+ NEARBY_LOGS(INFO) << "PayloadManager: xfer scheduled: self=" << this
+ << "; payload_id=" << payload_id
+ << ", payload_type=" << ToString(payload_type);
+}
+
+PayloadManager::PendingPayload* PayloadManager::GetPayload(
+ Payload::Id payload_id) const {
+ MutexLock lock(&mutex_);
+ return pending_payloads_.GetPayload(payload_id);
+}
+
+Status PayloadManager::CancelPayload(ClientProxy* client,
+ Payload::Id payload_id) {
+ PendingPayload* canceled_payload = GetPayload(payload_id);
+ if (!canceled_payload) {
+ NEARBY_LOGS(INFO) << "Client requested cancel for unknown payload_id="
+ << payload_id << ", ignoring.";
+ return {Status::kPayloadUnknown};
+ }
+
+ // Mark the payload as canceled.
+ canceled_payload->MarkLocallyCanceled();
+ NEARBY_LOGS(INFO) << "Cancelling "
+ << (canceled_payload->IsIncoming() ? "incoming"
+ : "outgoing")
+ << " payload_id=" << payload_id << " at request of client.";
+
+ // Return SUCCESS immediately. Remaining cleanup and updates will be sent
+ // in SendPayload() or OnIncomingFrame()
+ return {Status::kSuccess};
+}
+
+// @EndpointManagerDataPool
+void PayloadManager::OnIncomingFrame(
+ OfflineFrame& offline_frame, const std::string& from_endpoint_id,
+ ClientProxy* to_client, proto::connections::Medium current_medium) {
+ PayloadTransferFrame& frame =
+ *offline_frame.mutable_v1()->mutable_payload_transfer();
+
+ switch (frame.packet_type()) {
+ case PayloadTransferFrame::CONTROL:
+ NEARBY_LOGS(INFO) << "PayloadManager::OnIncomingFrame [CONTROL]: self="
+ << this << "; endpoint_id=" << from_endpoint_id;
+ ProcessControlPacket(to_client, from_endpoint_id, frame);
+ break;
+ case PayloadTransferFrame::DATA:
+ ProcessDataPacket(to_client, from_endpoint_id, frame);
+ break;
+ default:
+ NEARBY_LOGS(WARNING)
+ << "PayloadManager: invalid frame; remote endpoint: self=" << this
+ << "; endpoint_id=" << from_endpoint_id;
+ break;
+ }
+}
+
+void PayloadManager::OnEndpointDisconnect(ClientProxy* client,
+ const std::string& endpoint_id,
+ CountDownLatch barrier) {
+ if (shutdown_.Get()) {
+ barrier.CountDown();
+ return;
+ }
+ RunOnStatusUpdateThread(
+ "payload-manager-on-disconnect",
+ [this, client, endpoint_id, barrier]()
+ RUN_ON_PAYLOAD_STATUS_UPDATE_THREAD() mutable {
+ // Iterate through all our payloads and look for payloads associated
+ // with this endpoint.
+ MutexLock lock(&mutex_);
+ for (const auto& payload_id : pending_payloads_.GetAllPayloads()) {
+ auto* pending_payload = pending_payloads_.GetPayload(payload_id);
+ if (!pending_payload) continue;
+ auto endpoint_info = pending_payload->GetEndpoint(endpoint_id);
+ if (!endpoint_info) continue;
+ std::int64_t endpoint_offset = endpoint_info->offset;
+ // Stop tracking the endpoint for this payload.
+ pending_payload->RemoveEndpoints({endpoint_id});
+ // |endpoint_info| is longer valid after calling RemoveEndpoints.
+ endpoint_info = nullptr;
+
+ std::int64_t payload_total_size =
+ pending_payload->GetInternalPayload()->GetTotalSize();
+
+ // If no endpoints are left for this payload, close it.
+ if (pending_payload->GetEndpoints().empty()) {
+ pending_payload->Close();
+ }
+
+ // Create the payload transfer update.
+ PayloadProgressInfo update{payload_id,
+ PayloadProgressInfo::Status::kFailure,
+ payload_total_size, endpoint_offset};
+
+ // Send a client notification of a payload transfer failure.
+ client->OnPayloadProgress(endpoint_id, update);
+
+ if (pending_payload->IsIncoming()) {
+ client->GetAnalyticsRecorder().OnIncomingPayloadDone(
+ endpoint_id, pending_payload->GetId(),
+ proto::connections::ENDPOINT_IO_ERROR);
+ } else {
+ client->GetAnalyticsRecorder().OnOutgoingPayloadDone(
+ endpoint_id, pending_payload->GetId(),
+ proto::connections::ENDPOINT_IO_ERROR);
+ }
+ }
+
+ barrier.CountDown();
+ });
+}
+
+proto::connections::PayloadStatus
+PayloadManager::EndpointInfoStatusToPayloadStatus(EndpointInfo::Status status) {
+ switch (status) {
+ case EndpointInfo::Status::kCanceled:
+ return proto::connections::PayloadStatus::REMOTE_CANCELLATION;
+ case EndpointInfo::Status::kError:
+ return proto::connections::PayloadStatus::REMOTE_ERROR;
+ case EndpointInfo::Status::kAvailable:
+ return proto::connections::PayloadStatus::SUCCESS;
+ default:
+ NEARBY_LOGS(INFO) << "PayloadManager: Unknown PayloadStatus";
+ return proto::connections::PayloadStatus::UNKNOWN_PAYLOAD_STATUS;
+ }
+}
+
+proto::connections::PayloadStatus
+PayloadManager::ControlMessageEventToPayloadStatus(
+ PayloadTransferFrame::ControlMessage::EventType event) {
+ switch (event) {
+ case PayloadTransferFrame::ControlMessage::PAYLOAD_ERROR:
+ return proto::connections::PayloadStatus::REMOTE_ERROR;
+ case PayloadTransferFrame::ControlMessage::PAYLOAD_CANCELED:
+ return proto::connections::PayloadStatus::REMOTE_CANCELLATION;
+ default:
+ NEARBY_LOG(INFO, "PayloadManager: unknown event=%d", event);
+ return proto::connections::PayloadStatus::UNKNOWN_PAYLOAD_STATUS;
+ }
+}
+
+PayloadProgressInfo::Status PayloadManager::PayloadStatusToTransferUpdateStatus(
+ proto::connections::PayloadStatus status) {
+ switch (status) {
+ case proto::connections::LOCAL_CANCELLATION:
+ case proto::connections::REMOTE_CANCELLATION:
+ return PayloadProgressInfo::Status::kCanceled;
+ case proto::connections::SUCCESS:
+ return PayloadProgressInfo::Status::kSuccess;
+ default:
+ return PayloadProgressInfo::Status::kFailure;
+ }
+}
+
+SingleThreadExecutor* PayloadManager::GetOutgoingPayloadExecutor(
+ Payload::Type payload_type) {
+ switch (payload_type) {
+ case Payload::Type::kBytes:
+ return &bytes_payload_executor_;
+ case Payload::Type::kFile:
+ return &file_payload_executor_;
+ case Payload::Type::kStream:
+ return &stream_payload_executor_;
+ default:
+ return nullptr;
+ }
+}
+
+int PayloadManager::GetOptimalChunkSize(EndpointIds endpoint_ids) {
+ int minChunkSize = std::numeric_limits<int>::max();
+ for (const auto& endpoint_id : endpoint_ids) {
+ minChunkSize = std::min(
+ minChunkSize, endpoint_manager_->GetMaxTransmitPacketSize(endpoint_id));
+ }
+ return minChunkSize;
+}
+
+PayloadTransferFrame::PayloadHeader PayloadManager::CreatePayloadHeader(
+ const InternalPayload& internal_payload, size_t offset) {
+ PayloadTransferFrame::PayloadHeader payload_header;
+ size_t payload_size = internal_payload.GetTotalSize();
+
+ payload_header.set_id(internal_payload.GetId());
+ payload_header.set_type(internal_payload.GetType());
+ payload_header.set_total_size(payload_size ==
+ InternalPayload::kIndeterminateSize
+ ? InternalPayload::kIndeterminateSize
+ : payload_size - offset);
+
+ return payload_header;
+}
+
+PayloadTransferFrame::PayloadChunk PayloadManager::CreatePayloadChunk(
+ std::int64_t payload_chunk_offset, ByteArray payload_chunk_body) {
+ PayloadTransferFrame::PayloadChunk payload_chunk;
+
+ payload_chunk.set_offset(payload_chunk_offset);
+ payload_chunk.set_flags(0);
+ if (!payload_chunk_body.Empty()) {
+ payload_chunk.set_body(std::string(std::move(payload_chunk_body)));
+ } else {
+ payload_chunk.set_flags(payload_chunk.flags() |
+ PayloadTransferFrame::PayloadChunk::LAST_CHUNK);
+ }
+
+ return payload_chunk;
+}
+
+PayloadManager::PendingPayload* PayloadManager::CreateIncomingPayload(
+ const PayloadTransferFrame& frame, const std::string& endpoint_id) {
+ auto internal_payload = CreateIncomingInternalPayload(frame);
+ if (!internal_payload) {
+ return nullptr;
+ }
+
+ Payload::Id payload_id = internal_payload->GetId();
+ NEARBY_LOGS(INFO) << "CreateIncomingPayload: payload_id=" << payload_id;
+ MutexLock lock(&mutex_);
+ pending_payloads_.StartTrackingPayload(
+ payload_id,
+ absl::make_unique<PendingPayload>(std::move(internal_payload),
+ EndpointIds{endpoint_id}, true));
+
+ return pending_payloads_.GetPayload(payload_id);
+}
+
+void PayloadManager::SendClientCallbacksForFinishedOutgoingPayload(
+ ClientProxy* client, const EndpointIds& finished_endpoint_ids,
+ const PayloadTransferFrame::PayloadHeader& payload_header,
+ std::int64_t num_bytes_successfully_transferred,
+ proto::connections::PayloadStatus status) {
+ RunOnStatusUpdateThread(
+ "outgoing-payload-callbacks",
+ [this, client, finished_endpoint_ids, payload_header,
+ num_bytes_successfully_transferred,
+ status]() RUN_ON_PAYLOAD_STATUS_UPDATE_THREAD() {
+ // Make sure we're still tracking this payload.
+ PendingPayload* pending_payload = GetPayload(payload_header.id());
+ if (!pending_payload) {
+ return;
+ }
+
+ PayloadProgressInfo update{
+ payload_header.id(),
+ PayloadManager::PayloadStatusToTransferUpdateStatus(status),
+ payload_header.total_size(), num_bytes_successfully_transferred};
+ for (const auto& endpoint_id : finished_endpoint_ids) {
+ // Skip sending notifications if we have stopped tracking this
+ // endpoint.
+ if (!pending_payload->GetEndpoint(endpoint_id)) {
+ continue;
+ }
+
+ // Notify the client.
+ client->OnPayloadProgress(endpoint_id, update);
+
+ // Mark this payload as done for analytics.
+ client->GetAnalyticsRecorder().OnOutgoingPayloadDone(
+ endpoint_id, payload_header.id(), status);
+ }
+
+ // Remove these endpoints from our tracking list for this payload.
+ pending_payload->RemoveEndpoints(finished_endpoint_ids);
+
+ // Close the payload if no endpoints remain.
+ if (pending_payload->GetEndpoints().empty()) {
+ pending_payload->Close();
+ }
+ });
+}
+
+void PayloadManager::SendClientCallbacksForFinishedIncomingPayload(
+ ClientProxy* client, const std::string& endpoint_id,
+ const PayloadTransferFrame::PayloadHeader& payload_header,
+ std::int64_t offset_bytes, proto::connections::PayloadStatus status) {
+ RunOnStatusUpdateThread(
+ "incoming-payload-callbacks",
+ [this, client, endpoint_id, payload_header, offset_bytes,
+ status]() RUN_ON_PAYLOAD_STATUS_UPDATE_THREAD() {
+ // Make sure we're still tracking this payload.
+ PendingPayload* pending_payload = GetPayload(payload_header.id());
+ if (!pending_payload) {
+ return;
+ }
+
+ // Unless we never started tracking this payload (meaning we failed to
+ // even create the InternalPayload), notify the client (and close it).
+ PayloadProgressInfo update{
+ payload_header.id(),
+ PayloadManager::PayloadStatusToTransferUpdateStatus(status),
+ payload_header.total_size(), offset_bytes};
+ NotifyClientOfIncomingPayloadProgressInfo(client, endpoint_id, update);
+ DestroyPendingPayload(payload_header.id());
+
+ // Analyze
+ client->GetAnalyticsRecorder().OnIncomingPayloadDone(
+ endpoint_id, payload_header.id(), status);
+ });
+}
+
+void PayloadManager::SendControlMessage(
+ const EndpointIds& endpoint_ids,
+ const PayloadTransferFrame::PayloadHeader& payload_header,
+ std::int64_t num_bytes_successfully_transferred,
+ PayloadTransferFrame::ControlMessage::EventType event_type) {
+ PayloadTransferFrame::ControlMessage control_message;
+ control_message.set_event(event_type);
+ control_message.set_offset(num_bytes_successfully_transferred);
+
+ endpoint_manager_->SendControlMessage(payload_header, control_message,
+ endpoint_ids);
+}
+
+void PayloadManager::HandleFinishedOutgoingPayload(
+ ClientProxy* client, const EndpointIds& finished_endpoint_ids,
+ const PayloadTransferFrame::PayloadHeader& payload_header,
+ std::int64_t num_bytes_successfully_transferred,
+ proto::connections::PayloadStatus status) {
+ // This call will destroy a pending payload.
+ SendClientCallbacksForFinishedOutgoingPayload(
+ client, finished_endpoint_ids, payload_header,
+ num_bytes_successfully_transferred, status);
+
+ switch (status) {
+ case proto::connections::PayloadStatus::LOCAL_ERROR:
+ SendControlMessage(finished_endpoint_ids, payload_header,
+ num_bytes_successfully_transferred,
+ PayloadTransferFrame::ControlMessage::PAYLOAD_ERROR);
+ break;
+ case proto::connections::PayloadStatus::LOCAL_CANCELLATION:
+ NEARBY_LOGS(INFO)
+ << "Sending PAYLOAD_CANCEL to receiver side; payload_id="
+ << payload_header.id();
+ SendControlMessage(
+ finished_endpoint_ids, payload_header,
+ num_bytes_successfully_transferred,
+ PayloadTransferFrame::ControlMessage::PAYLOAD_CANCELED);
+ break;
+ case proto::connections::PayloadStatus::ENDPOINT_IO_ERROR:
+ // Unregister these endpoints, since we had an IO error on the physical
+ // connection.
+ for (const auto& endpoint_id : finished_endpoint_ids) {
+ endpoint_manager_->DiscardEndpoint(client, endpoint_id);
+ }
+ break;
+ case proto::connections::PayloadStatus::REMOTE_ERROR:
+ case proto::connections::PayloadStatus::REMOTE_CANCELLATION:
+ // No special handling needed for these.
+ break;
+ default:
+ NEARBY_LOGS(INFO)
+ << "PayloadManager: Unhandled finished outgoing payload with "
+ "payload_status="
+ << status;
+ break;
+ }
+}
+
+void PayloadManager::HandleFinishedIncomingPayload(
+ ClientProxy* client, const std::string& endpoint_id,
+ const PayloadTransferFrame::PayloadHeader& payload_header,
+ std::int64_t offset_bytes, proto::connections::PayloadStatus status) {
+ SendClientCallbacksForFinishedIncomingPayload(
+ client, endpoint_id, payload_header, offset_bytes, status);
+
+ switch (status) {
+ case proto::connections::PayloadStatus::LOCAL_ERROR:
+ SendControlMessage({endpoint_id}, payload_header, offset_bytes,
+ PayloadTransferFrame::ControlMessage::PAYLOAD_ERROR);
+ break;
+ case proto::connections::PayloadStatus::LOCAL_CANCELLATION:
+ SendControlMessage(
+ {endpoint_id}, payload_header, offset_bytes,
+ PayloadTransferFrame::ControlMessage::PAYLOAD_CANCELED);
+ break;
+ default:
+ NEARBY_LOGS(INFO) << "Unhandled finished incoming payload_id="
+ << payload_header.id()
+ << " with payload_status=" << status;
+ break;
+ }
+}
+
+void PayloadManager::HandleSuccessfulOutgoingChunk(
+ ClientProxy* client, const std::string& endpoint_id,
+ const PayloadTransferFrame::PayloadHeader& payload_header,
+ std::int32_t payload_chunk_flags, std::int64_t payload_chunk_offset,
+ std::int64_t payload_chunk_body_size) {
+ RunOnStatusUpdateThread(
+ "outgoing-chunk-success",
+ [this, client, endpoint_id, payload_header, payload_chunk_flags,
+ payload_chunk_offset,
+ payload_chunk_body_size]() RUN_ON_PAYLOAD_STATUS_UPDATE_THREAD() {
+ // Make sure we're still tracking this payload and its associated
+ // endpoint.
+ PendingPayload* pending_payload = GetPayload(payload_header.id());
+ if (!pending_payload || !pending_payload->GetEndpoint(endpoint_id)) {
+ NEARBY_LOGS(INFO)
+ << "HandleSuccessfulOutgoingChunk: endpoint not found: "
+ "endpoint_id="
+ << endpoint_id;
+ return;
+ }
+
+ bool is_last_chunk =
+ (payload_chunk_flags &
+ PayloadTransferFrame::PayloadChunk::LAST_CHUNK) != 0;
+ PayloadProgressInfo update{
+ payload_header.id(),
+ is_last_chunk ? PayloadProgressInfo::Status::kSuccess
+ : PayloadProgressInfo::Status::kInProgress,
+ payload_header.total_size(),
+ is_last_chunk ? payload_chunk_offset
+ : payload_chunk_offset + payload_chunk_body_size};
+
+ // Notify the client.
+ client->OnPayloadProgress(endpoint_id, update);
+
+ if (is_last_chunk) {
+ client->GetAnalyticsRecorder().OnOutgoingPayloadDone(
+ endpoint_id, payload_header.id(), proto::connections::SUCCESS);
+
+ // Stop tracking this endpoint.
+ pending_payload->RemoveEndpoints({endpoint_id});
+
+ // Close the payload if no endpoints remain.
+ if (pending_payload->GetEndpoints().empty()) {
+ pending_payload->Close();
+ }
+ } else {
+ client->GetAnalyticsRecorder().OnPayloadChunkSent(
+ endpoint_id, payload_header.id(), payload_chunk_body_size);
+ }
+ });
+}
+
+// @PayloadManagerStatusUpdateThread
+void PayloadManager::DestroyPendingPayload(Payload::Id payload_id) {
+ bool is_incoming = false;
+ {
+ MutexLock lock(&mutex_);
+ auto pending = pending_payloads_.StopTrackingPayload(payload_id);
+ if (!pending) return;
+ is_incoming = pending->IsIncoming();
+ const char* direction = is_incoming ? "incoming" : "outgoing";
+ NEARBY_LOGS(INFO) << "PayloadManager: destroying " << direction
+ << " pending payload: self=" << this
+ << "; payload_id=" << payload_id;
+ pending->Close();
+ pending.reset();
+ }
+ if (!is_incoming) NotifyShutdown();
+}
+
+void PayloadManager::HandleSuccessfulIncomingChunk(
+ ClientProxy* client, const std::string& endpoint_id,
+ const PayloadTransferFrame::PayloadHeader& payload_header,
+ std::int32_t payload_chunk_flags, std::int64_t payload_chunk_offset,
+ std::int64_t payload_chunk_body_size) {
+ RunOnStatusUpdateThread(
+ "incoming-chunk-success",
+ [this, client, endpoint_id, payload_header, payload_chunk_flags,
+ payload_chunk_offset,
+ payload_chunk_body_size]() RUN_ON_PAYLOAD_STATUS_UPDATE_THREAD() {
+ // Make sure we're still tracking this payload.
+ PendingPayload* pending_payload = GetPayload(payload_header.id());
+ if (!pending_payload) {
+ return;
+ }
+
+ bool is_last_chunk =
+ (payload_chunk_flags &
+ PayloadTransferFrame::PayloadChunk::LAST_CHUNK) != 0;
+ PayloadProgressInfo update{
+ payload_header.id(),
+ is_last_chunk ? PayloadProgressInfo::Status::kSuccess
+ : PayloadProgressInfo::Status::kInProgress,
+ payload_header.total_size(),
+ is_last_chunk ? payload_chunk_offset
+ : payload_chunk_offset + payload_chunk_body_size};
+
+ // Notify the client of this update.
+ NotifyClientOfIncomingPayloadProgressInfo(client, endpoint_id, update);
+
+ // Analyze the success.
+ if (is_last_chunk) {
+ client->GetAnalyticsRecorder().OnIncomingPayloadDone(
+ endpoint_id, payload_header.id(), proto::connections::SUCCESS);
+ } else {
+ client->GetAnalyticsRecorder().OnPayloadChunkReceived(
+ endpoint_id, payload_header.id(), payload_chunk_body_size);
+ }
+ });
+}
+
+// @EndpointManagerDataPool
+void PayloadManager::ProcessDataPacket(
+ ClientProxy* to_client, const std::string& from_endpoint_id,
+ PayloadTransferFrame& payload_transfer_frame) {
+ PayloadTransferFrame::PayloadHeader& payload_header =
+ *payload_transfer_frame.mutable_payload_header();
+ PayloadTransferFrame::PayloadChunk& payload_chunk =
+ *payload_transfer_frame.mutable_payload_chunk();
+ NEARBY_LOGS(VERBOSE) << "PayloadManager got data OfflineFrame for payload_id="
+ << payload_header.id()
+ << " from endpoint_id=" << from_endpoint_id
+ << " at offset " << payload_chunk.offset();
+
+ PendingPayload* pending_payload;
+ if (payload_chunk.offset() == 0) {
+ RunOnStatusUpdateThread(
+ "process-data-packet", [to_client, from_endpoint_id, payload_header,
+ this]() RUN_ON_PAYLOAD_STATUS_UPDATE_THREAD() {
+ // This is the first chunk of a new incoming
+ // payload. Start the analysis.
+ to_client->GetAnalyticsRecorder().OnIncomingPayloadStarted(
+ from_endpoint_id, payload_header.id(),
+ FramePayloadTypeToPayloadType(payload_header.type()),
+ payload_header.total_size());
+ });
+
+ pending_payload =
+ CreateIncomingPayload(payload_transfer_frame, from_endpoint_id);
+ if (!pending_payload) {
+ NEARBY_LOGS(WARNING)
+ << "PayloadManager failed to create InternalPayload from "
+ "PayloadTransferFrame with payload_id="
+ << payload_header.id() << " and type " << payload_header.type()
+ << ", aborting receipt.";
+ // Send the error to the remote endpoint.
+ SendControlMessage({from_endpoint_id}, payload_header,
+ payload_chunk.offset(),
+ PayloadTransferFrame::ControlMessage::PAYLOAD_ERROR);
+ return;
+ }
+
+ // Also, let the client know of this new incoming payload.
+ RunOnStatusUpdateThread(
+ "process-data-packet",
+ [to_client, from_endpoint_id, pending_payload]()
+ RUN_ON_PAYLOAD_STATUS_UPDATE_THREAD() {
+ NEARBY_LOGS(INFO)
+ << "PayloadManager received new payload_id="
+ << pending_payload->GetInternalPayload()->GetId()
+ << " from endpoint_id=" << from_endpoint_id;
+ to_client->OnPayload(
+ from_endpoint_id,
+ pending_payload->GetInternalPayload()->ReleasePayload());
+ });
+ } else {
+ pending_payload = GetPayload(payload_header.id());
+ if (!pending_payload) {
+ NEARBY_LOGS(WARNING) << "ProcessDataPacket: [missing] endpoint_id="
+ << from_endpoint_id
+ << "; payload_id=" << payload_header.id();
+ return;
+ }
+ }
+
+ if (pending_payload->IsLocallyCanceled()) {
+ // This incoming payload was canceled by the client. Drop this frame and do
+ // all the cleanup. See go/nc-cancel-payload
+ NEARBY_LOGS(INFO) << "ProcessDataPacket: [cancel] endpoint_id="
+ << from_endpoint_id
+ << "; payload_id=" << pending_payload->GetId();
+ HandleFinishedIncomingPayload(
+ to_client, from_endpoint_id, payload_header, payload_chunk.offset(),
+ proto::connections::PayloadStatus::LOCAL_CANCELLATION);
+ return;
+ }
+
+ // Update the offset for this payload. An endpoint disconnection might occur
+ // from another thread and we would need to know the current offset to report
+ // back to the client. For the sake of accuracy, we update the pending payload
+ // here because it's after all payload terminating events are handled, but
+ // right before we actually start attaching the next chunk.
+ pending_payload->SetOffsetForEndpoint(from_endpoint_id,
+ payload_chunk.offset());
+
+ // Save size of packet before we move it.
+ std::int64_t payload_body_size = payload_chunk.body().size();
+ if (pending_payload->GetInternalPayload()
+ ->AttachNextChunk(ByteArray(std::move(*payload_chunk.mutable_body())))
+ .Raised()) {
+ NEARBY_LOGS(ERROR) << "ProcessDataPacket: [data: error] endpoint_id="
+ << from_endpoint_id
+ << "; payload_id=" << pending_payload->GetId();
+ HandleFinishedIncomingPayload(
+ to_client, from_endpoint_id, payload_header, payload_chunk.offset(),
+ proto::connections::PayloadStatus::LOCAL_ERROR);
+ return;
+ }
+
+ HandleSuccessfulIncomingChunk(to_client, from_endpoint_id, payload_header,
+ payload_chunk.flags(), payload_chunk.offset(),
+ payload_body_size);
+}
+
+// @EndpointManagerDataPool
+void PayloadManager::ProcessControlPacket(
+ ClientProxy* to_client, const std::string& from_endpoint_id,
+ PayloadTransferFrame& payload_transfer_frame) {
+ const PayloadTransferFrame::PayloadHeader& payload_header =
+ payload_transfer_frame.payload_header();
+ const PayloadTransferFrame::ControlMessage& control_message =
+ payload_transfer_frame.control_message();
+ PendingPayload* pending_payload = GetPayload(payload_header.id());
+ if (!pending_payload) {
+ NEARBY_LOGS(INFO) << "Got ControlMessage for unknown payload_id="
+ << payload_header.id()
+ << ", ignoring: " << control_message.event();
+ return;
+ }
+
+ switch (control_message.event()) {
+ case PayloadTransferFrame::ControlMessage::PAYLOAD_CANCELED:
+ if (pending_payload->IsIncoming()) {
+ NEARBY_LOGS(INFO) << "Incoming PAYLOAD_CANCELED: from endpoint_id="
+ << from_endpoint_id << "; self=" << this;
+ // No need to mark the pending payload as cancelled, since this is a
+ // remote cancellation for an incoming payload -- we handle everything
+ // inline here.
+ HandleFinishedIncomingPayload(
+ to_client, from_endpoint_id, payload_header,
+ control_message.offset(),
+ ControlMessageEventToPayloadStatus(control_message.event()));
+ } else {
+ NEARBY_LOGS(INFO) << "Outgoing PAYLOAD_CANCELED: from endpoint_id="
+ << from_endpoint_id << "; self=" << this;
+ // Mark the payload as canceled *for this endpoint*.
+ pending_payload->SetEndpointStatusFromControlMessage(from_endpoint_id,
+ control_message);
+ }
+ NEARBY_LOGS(VERBOSE)
+ << "Marked "
+ << (pending_payload->IsIncoming() ? "incoming" : "outgoing")
+ << " payload_id=" << pending_payload->GetInternalPayload()->GetId()
+ << " as canceled at request of endpoint_id=" << from_endpoint_id;
+ break;
+ case PayloadTransferFrame::ControlMessage::PAYLOAD_ERROR:
+ if (pending_payload->IsIncoming()) {
+ HandleFinishedIncomingPayload(
+ to_client, from_endpoint_id, payload_header,
+ control_message.offset(),
+ ControlMessageEventToPayloadStatus(control_message.event()));
+ } else {
+ pending_payload->SetEndpointStatusFromControlMessage(from_endpoint_id,
+ control_message);
+ }
+ break;
+ default:
+ NEARBY_LOGS(INFO) << "Unhandled control message "
+ << control_message.event() << " for payload_id="
+ << pending_payload->GetInternalPayload()->GetId();
+ break;
+ }
+}
+
+// @PayloadManagerStatusUpdateThread
+void PayloadManager::NotifyClientOfIncomingPayloadProgressInfo(
+ ClientProxy* client, const std::string& endpoint_id,
+ const PayloadProgressInfo& payload_transfer_update) {
+ client->OnPayloadProgress(endpoint_id, payload_transfer_update);
+}
+
+void PayloadManager::RecordPayloadStartedAnalytics(
+ ClientProxy* client, const EndpointIds& endpoint_ids,
+ std::int64_t payload_id, Payload::Type payload_type, std::int64_t offset,
+ std::int64_t total_size) {
+ client->GetAnalyticsRecorder().OnOutgoingPayloadStarted(
+ endpoint_ids, payload_id, payload_type,
+ total_size == -1 ? -1 : total_size - offset);
+}
+
+void PayloadManager::RecordInvalidPayloadAnalytics(
+ ClientProxy* client, const EndpointIds& endpoint_ids,
+ std::int64_t payload_id, Payload::Type payload_type, std::int64_t offset,
+ std::int64_t total_size) {
+ RecordPayloadStartedAnalytics(client, endpoint_ids, payload_id, payload_type,
+ offset, total_size);
+
+ for (const auto& endpoint_id : endpoint_ids) {
+ client->GetAnalyticsRecorder().OnOutgoingPayloadDone(
+ endpoint_id, payload_id, proto::connections::LOCAL_ERROR);
+ }
+}
+
+Payload::Type PayloadManager::FramePayloadTypeToPayloadType(
+ PayloadTransferFrame::PayloadHeader::PayloadType type) {
+ switch (type) {
+ case PayloadTransferFrame_PayloadHeader_PayloadType_BYTES:
+ return connections::Payload::Type::kBytes;
+ case PayloadTransferFrame_PayloadHeader_PayloadType_FILE:
+ return connections::Payload::Type::kFile;
+ case PayloadTransferFrame_PayloadHeader_PayloadType_STREAM:
+ return connections::Payload::Type::kStream;
+ default:
+ return connections::Payload::Type::kUnknown;
+ }
+}
+
+///////////////////////////////// EndpointInfo /////////////////////////////////
+
+PayloadManager::EndpointInfo::Status
+PayloadManager::EndpointInfo::ControlMessageEventToEndpointInfoStatus(
+ PayloadTransferFrame::ControlMessage::EventType event) {
+ switch (event) {
+ case PayloadTransferFrame::ControlMessage::PAYLOAD_ERROR:
+ return Status::kError;
+ case PayloadTransferFrame::ControlMessage::PAYLOAD_CANCELED:
+ return Status::kCanceled;
+ default:
+ NEARBY_LOGS(INFO)
+ << "Unknown EndpointInfo.Status for ControlMessage.EventType "
+ << event;
+ return Status::kUnknown;
+ }
+}
+
+void PayloadManager::EndpointInfo::SetStatusFromControlMessage(
+ const PayloadTransferFrame::ControlMessage& control_message) {
+ status.Set(ControlMessageEventToEndpointInfoStatus(control_message.event()));
+ NEARBY_LOGS(VERBOSE) << "Marked endpoint " << id << " with status "
+ << ToString(status.Get())
+ << " based on OOB ControlMessage";
+}
+
+//////////////////////////////// PendingPayload ////////////////////////////////
+
+PayloadManager::PendingPayload::PendingPayload(
+ std::unique_ptr<InternalPayload> internal_payload,
+ const EndpointIds& endpoint_ids, bool is_incoming)
+ : is_incoming_(is_incoming),
+ internal_payload_(std::move(internal_payload)) {
+ // Initially we mark all endpoints as available.
+ // Later on some may become canceled, some may experience data transfer
+ // failures. Any of these situations will cause endpoint to be marked as
+ // unavailable.
+ for (const auto& id : endpoint_ids) {
+ EndpointInfo endpoint_info{};
+ endpoint_info.id = id;
+ endpoint_info.status.Set(EndpointInfo::Status::kAvailable);
+
+ endpoints_.emplace(id, std::move(endpoint_info));
+ }
+}
+
+Payload::Id PayloadManager::PendingPayload::GetId() const {
+ return internal_payload_->GetId();
+}
+
+InternalPayload* PayloadManager::PendingPayload::GetInternalPayload() {
+ return internal_payload_.get();
+}
+
+bool PayloadManager::PendingPayload::IsLocallyCanceled() const {
+ return is_locally_canceled_.Get();
+}
+
+void PayloadManager::PendingPayload::MarkLocallyCanceled() {
+ is_locally_canceled_.Set(true);
+}
+
+bool PayloadManager::PendingPayload::IsIncoming() const { return is_incoming_; }
+
+std::vector<const PayloadManager::EndpointInfo*>
+PayloadManager::PendingPayload::GetEndpoints() const {
+ MutexLock lock(&mutex_);
+
+ std::vector<const EndpointInfo*> result;
+ for (const auto& item : endpoints_) {
+ result.push_back(&item.second);
+ }
+ return result;
+}
+
+PayloadManager::EndpointInfo* PayloadManager::PendingPayload::GetEndpoint(
+ const std::string& endpoint_id) {
+ MutexLock lock(&mutex_);
+
+ auto it = endpoints_.find(endpoint_id);
+ if (it == endpoints_.end()) {
+ return {};
+ }
+
+ return &it->second;
+}
+
+void PayloadManager::PendingPayload::RemoveEndpoints(
+ const EndpointIds& endpoint_ids) {
+ MutexLock lock(&mutex_);
+
+ for (const auto& id : endpoint_ids) {
+ endpoints_.erase(id);
+ }
+}
+
+void PayloadManager::PendingPayload::SetEndpointStatusFromControlMessage(
+ const std::string& endpoint_id,
+ const PayloadTransferFrame::ControlMessage& control_message) {
+ MutexLock lock(&mutex_);
+
+ auto item = endpoints_.find(endpoint_id);
+ if (item != endpoints_.end()) {
+ item->second.SetStatusFromControlMessage(control_message);
+ }
+}
+
+void PayloadManager::PendingPayload::SetOffsetForEndpoint(
+ const std::string& endpoint_id, std::int64_t offset) {
+ MutexLock lock(&mutex_);
+
+ auto item = endpoints_.find(endpoint_id);
+ if (item != endpoints_.end()) {
+ item->second.offset = offset;
+ }
+}
+
+void PayloadManager::PendingPayload::Close() {
+ if (internal_payload_) internal_payload_->Close();
+ close_event_.CountDown();
+}
+
+bool PayloadManager::PendingPayload::WaitForClose() {
+ return close_event_.Await(kWaitCloseTimeout).result();
+}
+
+bool PayloadManager::PendingPayload::IsClosed() {
+ return close_event_.Await(absl::ZeroDuration()).result();
+}
+
+void PayloadManager::RunOnStatusUpdateThread(const std::string& name,
+ std::function<void()> runnable) {
+ payload_status_update_executor_.Execute(name, std::move(runnable));
+}
+
+/////////////////////////////// PendingPayloads ///////////////////////////////
+
+void PayloadManager::PendingPayloads::StartTrackingPayload(
+ Payload::Id payload_id, std::unique_ptr<PendingPayload> pending_payload) {
+ MutexLock lock(&mutex_);
+
+ // If the |payload_id| is being re-used, always prefer the newer payload.
+ auto it = pending_payloads_.find(payload_id);
+ if (it != pending_payloads_.end()) {
+ pending_payloads_.erase(payload_id);
+ }
+ auto pair = pending_payloads_.emplace(payload_id, std::move(pending_payload));
+ NEARBY_LOGS(INFO) << "StartTrackingPayload: payload_id=" << payload_id
+ << "; inserted=" << pair.second;
+}
+
+std::unique_ptr<PayloadManager::PendingPayload>
+PayloadManager::PendingPayloads::StopTrackingPayload(Payload::Id payload_id) {
+ MutexLock lock(&mutex_);
+
+ auto it = pending_payloads_.find(payload_id);
+ if (it == pending_payloads_.end()) return {};
+
+ auto item = pending_payloads_.extract(it);
+ return std::move(item.mapped());
+}
+
+PayloadManager::PendingPayload* PayloadManager::PendingPayloads::GetPayload(
+ Payload::Id payload_id) const {
+ MutexLock lock(&mutex_);
+
+ auto item = pending_payloads_.find(payload_id);
+ return item != pending_payloads_.end() ? item->second.get() : nullptr;
+}
+
+std::vector<Payload::Id> PayloadManager::PendingPayloads::GetAllPayloads() {
+ MutexLock lock(&mutex_);
+
+ std::vector<Payload::Id> result;
+ for (const auto& item : pending_payloads_) {
+ result.push_back(item.first);
+ }
+ return result;
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/payload_manager.h b/chromium/third_party/nearby/src/connections/implementation/payload_manager.h
new file mode 100644
index 00000000000..8b5994dad33
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/payload_manager.h
@@ -0,0 +1,322 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_PAYLOAD_MANAGER_H_
+#define CORE_INTERNAL_PAYLOAD_MANAGER_H_
+
+#include <cstdint>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "absl/container/flat_hash_map.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/endpoint_manager.h"
+#include "connections/implementation/internal_payload.h"
+#include "connections/listeners.h"
+#include "connections/payload.h"
+#include "connections/status.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/atomic_boolean.h"
+#include "internal/platform/atomic_reference.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/mutex.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Annotations for methods that need to run on PayloadStatusUpdateThread.
+// Use only in PayloadManager
+#define RUN_ON_PAYLOAD_STATUS_UPDATE_THREAD() \
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(payload_status_update_executor_)
+
+class PayloadManager : public EndpointManager::FrameProcessor {
+ public:
+ using EndpointIds = std::vector<std::string>;
+ constexpr static const absl::Duration kWaitCloseTimeout =
+ absl::Milliseconds(5000);
+
+ explicit PayloadManager(EndpointManager& endpoint_manager);
+ ~PayloadManager() override;
+
+ void SendPayload(ClientProxy* client, const EndpointIds& endpoint_ids,
+ Payload payload);
+ Status CancelPayload(ClientProxy* client, Payload::Id payload_id);
+
+ // @EndpointManagerReaderThread
+ void OnIncomingFrame(OfflineFrame& offline_frame,
+ const std::string& from_endpoint_id,
+ ClientProxy* to_client,
+ proto::connections::Medium current_medium) override;
+
+ // @EndpointManagerThread
+ void OnEndpointDisconnect(ClientProxy* client, const std::string& endpoint_id,
+ CountDownLatch barrier) override;
+
+ void DisconnectFromEndpointManager();
+
+ private:
+ // Information about an endpoint for a particular payload.
+ struct EndpointInfo {
+ // Status set for the endpoint out-of-band via a ControlMessage.
+ enum class Status {
+ kUnknown,
+ kAvailable,
+ kCanceled,
+ kError,
+ };
+
+ void SetStatusFromControlMessage(
+ const PayloadTransferFrame::ControlMessage& control_message);
+
+ static Status ControlMessageEventToEndpointInfoStatus(
+ PayloadTransferFrame::ControlMessage::EventType event);
+
+ std::string id;
+ AtomicReference<Status> status{Status::kUnknown};
+ std::int64_t offset = 0;
+ };
+
+ // Tracks state for an InternalPayload and the endpoints associated with it.
+ class PendingPayload {
+ public:
+ PendingPayload(std::unique_ptr<InternalPayload> internal_payload,
+ const EndpointIds& endpoint_ids, bool is_incoming);
+ PendingPayload(PendingPayload&&) = default;
+ PendingPayload& operator=(PendingPayload&&) = default;
+
+ ~PendingPayload() { Close(); }
+
+ Payload::Id GetId() const;
+
+ InternalPayload* GetInternalPayload();
+
+ bool IsLocallyCanceled() const;
+ void MarkLocallyCanceled();
+ bool IsIncoming() const;
+
+ // Gets the EndpointInfo objects for the endpoints (still) associated with
+ // this payload.
+ std::vector<const EndpointInfo*> GetEndpoints() const
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ // Returns the EndpointInfo for a given endpoint ID. Returns null if the
+ // endpoint is not associated with this payload.
+ EndpointInfo* GetEndpoint(const std::string& endpoint_id)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Removes the given endpoints, e.g. on error.
+ void RemoveEndpoints(const EndpointIds& endpoint_ids_to_remove)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Sets the status for a particular endpoint.
+ void SetEndpointStatusFromControlMessage(
+ const std::string& endpoint_id,
+ const PayloadTransferFrame::ControlMessage& control_message)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Sets the offset for a particular endpoint.
+ void SetOffsetForEndpoint(const std::string& endpoint_id,
+ std::int64_t offset) ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Closes internal_payload_ and triggers close_event_.
+ // Close is called when a pending peyload does not have associated
+ // endpoints.
+ void Close();
+
+ // Waits for close_event_ or for timeout to happen.
+ // Returns true, if event happened, false otherwise.
+ bool WaitForClose();
+ bool IsClosed();
+
+ private:
+ mutable Mutex mutex_;
+ bool is_incoming_;
+ AtomicBoolean is_locally_canceled_{false};
+ CountDownLatch close_event_{1};
+ std::unique_ptr<InternalPayload> internal_payload_;
+ absl::flat_hash_map<std::string, EndpointInfo> endpoints_
+ ABSL_GUARDED_BY(mutex_);
+ };
+
+ // Tracks and manages PendingPayload objects in a synchronized manner.
+ class PendingPayloads {
+ public:
+ PendingPayloads() = default;
+ ~PendingPayloads() = default;
+
+ void StartTrackingPayload(Payload::Id payload_id,
+ std::unique_ptr<PendingPayload> pending_payload)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ std::unique_ptr<PendingPayload> StopTrackingPayload(Payload::Id payload_id)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ PendingPayload* GetPayload(Payload::Id payload_id) const
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ std::vector<Payload::Id> GetAllPayloads() ABSL_LOCKS_EXCLUDED(mutex_);
+
+ private:
+ mutable Mutex mutex_;
+ absl::flat_hash_map<Payload::Id, std::unique_ptr<PendingPayload>>
+ pending_payloads_ ABSL_GUARDED_BY(mutex_);
+ };
+
+ using Endpoints = std::vector<const EndpointInfo*>;
+ static std::string ToString(const EndpointIds& endpoint_ids);
+ static std::string ToString(const Endpoints& endpoints);
+ static std::string ToString(Payload::Type type);
+ static std::string ToString(EndpointInfo::Status status);
+
+ // Splits the endpoints for this payload by availability.
+ // Returns a pair of lists of EndpointInfo*, with the first being the list of
+ // still-available endpoints, and the second for unavailable endpoints.
+ static std::pair<Endpoints, Endpoints> GetAvailableAndUnavailableEndpoints(
+ const PendingPayload& pending_payload);
+
+ // Converts list of EndpointInfo to list of Endpoint ids.
+ // Returns list of endpoint ids.
+ static EndpointIds EndpointsToEndpointIds(const Endpoints& endpoints);
+
+ bool SendPayloadLoop(ClientProxy* client, PendingPayload& pending_payload,
+ PayloadTransferFrame::PayloadHeader& payload_header,
+ std::int64_t& next_chunk_offset, size_t resume_offset);
+ void SendClientCallbacksForFinishedIncomingPayloadRunnable(
+ ClientProxy* client, const std::string& endpoint_id,
+ const PayloadTransferFrame::PayloadHeader& payload_header,
+ std::int64_t offset_bytes, proto::connections::PayloadStatus status);
+
+ // Converts the status of an endpoint that's been set out-of-band via a remote
+ // ControlMessage to the PayloadStatus for handling of that endpoint-payload
+ // pair.
+ static proto::connections::PayloadStatus EndpointInfoStatusToPayloadStatus(
+ EndpointInfo::Status status);
+ // Converts a ControlMessage::EventType for a particular payload to a
+ // PayloadStatus. Called when we've received a ControlMessage with this event
+ // from a remote endpoint; thus the PayloadStatuses are REMOTE_*.
+ static proto::connections::PayloadStatus ControlMessageEventToPayloadStatus(
+ PayloadTransferFrame::ControlMessage::EventType event);
+ static PayloadProgressInfo::Status PayloadStatusToTransferUpdateStatus(
+ proto::connections::PayloadStatus status);
+
+ int GetOptimalChunkSize(EndpointIds endpoint_ids);
+
+ PayloadTransferFrame::PayloadHeader CreatePayloadHeader(
+ const InternalPayload& payload, size_t offset);
+ PayloadTransferFrame::PayloadChunk CreatePayloadChunk(std::int64_t offset,
+ ByteArray body);
+
+ PendingPayload* CreateIncomingPayload(const PayloadTransferFrame& frame,
+ const std::string& endpoint_id)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ Payload::Id CreateOutgoingPayload(Payload payload,
+ const EndpointIds& endpoint_ids)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ void SendClientCallbacksForFinishedOutgoingPayload(
+ ClientProxy* client, const EndpointIds& finished_endpoint_ids,
+ const PayloadTransferFrame::PayloadHeader& payload_header,
+ std::int64_t num_bytes_successfully_transferred,
+ proto::connections::PayloadStatus status);
+ void SendClientCallbacksForFinishedIncomingPayload(
+ ClientProxy* client, const std::string& endpoint_id,
+ const PayloadTransferFrame::PayloadHeader& payload_header,
+ std::int64_t offset_bytes, proto::connections::PayloadStatus status);
+
+ void SendControlMessage(
+ const EndpointIds& endpoint_ids,
+ const PayloadTransferFrame::PayloadHeader& payload_header,
+ std::int64_t num_bytes_successfully_transferred,
+ PayloadTransferFrame::ControlMessage::EventType event_type);
+
+ // Handles a finished outgoing payload for the given endpointIds. All statuses
+ // except for SUCCESS are handled here.
+ void HandleFinishedOutgoingPayload(
+ ClientProxy* client, const EndpointIds& finished_endpoint_ids,
+ const PayloadTransferFrame::PayloadHeader& payload_header,
+ std::int64_t num_bytes_successfully_transferred,
+ proto::connections::PayloadStatus status =
+ proto::connections::PayloadStatus::UNKNOWN_PAYLOAD_STATUS);
+ void HandleFinishedIncomingPayload(
+ ClientProxy* client, const std::string& endpoint_id,
+ const PayloadTransferFrame::PayloadHeader& payload_header,
+ std::int64_t offset_bytes, proto::connections::PayloadStatus status);
+
+ void HandleSuccessfulOutgoingChunk(
+ ClientProxy* client, const std::string& endpoint_id,
+ const PayloadTransferFrame::PayloadHeader& payload_header,
+ std::int32_t payload_chunk_flags, std::int64_t payload_chunk_offset,
+ std::int64_t payload_chunk_body_size);
+ void HandleSuccessfulIncomingChunk(
+ ClientProxy* client, const std::string& endpoint_id,
+ const PayloadTransferFrame::PayloadHeader& payload_header,
+ std::int32_t payload_chunk_flags, std::int64_t payload_chunk_offset,
+ std::int64_t payload_chunk_body_size);
+
+ void ProcessDataPacket(ClientProxy* to_client,
+ const std::string& from_endpoint_id,
+ PayloadTransferFrame& payload_transfer_frame);
+ void ProcessControlPacket(ClientProxy* to_client,
+ const std::string& from_endpoint_id,
+ PayloadTransferFrame& payload_transfer_frame);
+
+ void NotifyClientOfIncomingPayloadProgressInfo(
+ ClientProxy* client, const std::string& endpoint_id,
+ const PayloadProgressInfo& payload_transfer_update)
+ RUN_ON_PAYLOAD_STATUS_UPDATE_THREAD();
+
+ SingleThreadExecutor* GetOutgoingPayloadExecutor(Payload::Type payload_type);
+
+ void RunOnStatusUpdateThread(const std::string& name,
+ std::function<void()> runnable);
+ bool NotifyShutdown() ABSL_LOCKS_EXCLUDED(mutex_);
+ void DestroyPendingPayload(Payload::Id payload_id)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ PendingPayload* GetPayload(Payload::Id payload_id) const
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ void CancelAllPayloads() ABSL_LOCKS_EXCLUDED(mutex_);
+
+ void RecordPayloadStartedAnalytics(ClientProxy* client,
+ const EndpointIds& endpoint_ids,
+ std::int64_t payload_id,
+ Payload::Type payload_type,
+ std::int64_t offset,
+ std::int64_t total_size);
+ void RecordInvalidPayloadAnalytics(ClientProxy* client,
+ const EndpointIds& endpoint_ids,
+ std::int64_t payload_id,
+ Payload::Type payload_type,
+ std::int64_t offset,
+ std::int64_t total_size);
+
+ Payload::Type FramePayloadTypeToPayloadType(
+ PayloadTransferFrame::PayloadHeader::PayloadType type);
+
+ mutable Mutex mutex_;
+ AtomicBoolean shutdown_{false};
+ std::unique_ptr<CountDownLatch> shutdown_barrier_;
+ int send_payload_count_ = 0;
+ PendingPayloads pending_payloads_ ABSL_GUARDED_BY(mutex_);
+ SingleThreadExecutor bytes_payload_executor_;
+ SingleThreadExecutor file_payload_executor_;
+ SingleThreadExecutor stream_payload_executor_;
+ SingleThreadExecutor payload_status_update_executor_;
+
+ EndpointManager* endpoint_manager_;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_PAYLOAD_MANAGER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/payload_manager_test.cc b/chromium/third_party/nearby/src/connections/implementation/payload_manager_test.cc
new file mode 100644
index 00000000000..c7b6c3fb5f9
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/payload_manager_test.cc
@@ -0,0 +1,374 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/payload_manager.h"
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "absl/strings/string_view.h"
+#include "connections/implementation/simulation_user.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/pipe.h"
+#include "internal/platform/system_clock.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+
+constexpr absl::string_view kServiceId = "service-id";
+constexpr absl::string_view kDeviceA = "device-a";
+constexpr absl::string_view kDeviceB = "device-b";
+constexpr absl::string_view kMessage = "message";
+constexpr absl::Duration kProgressTimeout = absl::Milliseconds(1000);
+constexpr absl::Duration kDefaultTimeout = absl::Milliseconds(1000);
+
+constexpr BooleanMediumSelector kTestCases[] = {
+ BooleanMediumSelector{
+ .bluetooth = true,
+ },
+ BooleanMediumSelector{
+ .wifi_lan = true,
+ },
+ BooleanMediumSelector{
+ .bluetooth = true,
+ .wifi_lan = true,
+ },
+};
+
+class PayloadSimulationUser : public SimulationUser {
+ public:
+ explicit PayloadSimulationUser(
+ absl::string_view name,
+ BooleanMediumSelector allowed = BooleanMediumSelector())
+ : SimulationUser(std::string(name), allowed) {}
+ ~PayloadSimulationUser() override {
+ NEARBY_LOGS(INFO) << "PayloadSimulationUser: [down] name=" << info_.data();
+ // SystemClock::Sleep(kDefaultTimeout);
+ }
+
+ Payload& GetPayload() { return payload_; }
+ void SendPayload(Payload payload) {
+ sender_payload_id_ = payload.GetId();
+ pm_.SendPayload(&client_, {discovered_.endpoint_id}, std::move(payload));
+ }
+
+ Status CancelPayload() {
+ if (sender_payload_id_) {
+ return pm_.CancelPayload(&client_, sender_payload_id_);
+ } else {
+ return pm_.CancelPayload(&client_, payload_.GetId());
+ }
+ }
+
+ bool IsConnected() const {
+ return client_.IsConnectedToEndpoint(discovered_.endpoint_id);
+ }
+
+ protected:
+ Payload::Id sender_payload_id_ = 0;
+};
+
+class PayloadManagerTest
+ : public ::testing::TestWithParam<BooleanMediumSelector> {
+ protected:
+ PayloadManagerTest() { env_.Stop(); }
+
+ bool SetupConnection(PayloadSimulationUser& user_a,
+ PayloadSimulationUser& user_b) {
+ user_a.StartAdvertising(std::string(kServiceId), &connection_latch_);
+ user_b.StartDiscovery(std::string(kServiceId), &discovery_latch_);
+ EXPECT_TRUE(discovery_latch_.Await(kDefaultTimeout).result());
+ EXPECT_EQ(user_b.GetDiscovered().service_id, kServiceId);
+ EXPECT_EQ(user_b.GetDiscovered().endpoint_info, user_a.GetInfo());
+ EXPECT_FALSE(user_b.GetDiscovered().endpoint_id.empty());
+ NEARBY_LOG(INFO, "EP-B: [discovered] %s",
+ user_b.GetDiscovered().endpoint_id.c_str());
+ user_b.RequestConnection(&connection_latch_);
+ EXPECT_TRUE(connection_latch_.Await(kDefaultTimeout).result());
+ EXPECT_FALSE(user_a.GetDiscovered().endpoint_id.empty());
+ NEARBY_LOG(INFO, "EP-A: [discovered] %s",
+ user_a.GetDiscovered().endpoint_id.c_str());
+ NEARBY_LOG(INFO, "Both users discovered their peers.");
+ user_a.AcceptConnection(&accept_latch_);
+ user_b.AcceptConnection(&accept_latch_);
+ EXPECT_TRUE(accept_latch_.Await(kDefaultTimeout).result());
+ NEARBY_LOG(INFO, "Both users reached connected state.");
+ return user_a.IsConnected() && user_b.IsConnected();
+ }
+
+ CountDownLatch discovery_latch_{1};
+ CountDownLatch connection_latch_{2};
+ CountDownLatch accept_latch_{2};
+ CountDownLatch payload_latch_{1};
+ MediumEnvironment& env_{MediumEnvironment::Instance()};
+};
+
+TEST_P(PayloadManagerTest, CanCreateOne) {
+ env_.Start();
+ PayloadSimulationUser user_a(kDeviceA, GetParam());
+ env_.Stop();
+}
+
+TEST_P(PayloadManagerTest, CanCreateMultiple) {
+ env_.Start();
+ PayloadSimulationUser user_a(kDeviceA, GetParam());
+ PayloadSimulationUser user_b(kDeviceB, GetParam());
+ env_.Stop();
+}
+
+TEST_P(PayloadManagerTest, CanSendBytePayload) {
+ env_.Start();
+ PayloadSimulationUser user_a(kDeviceA, GetParam());
+ PayloadSimulationUser user_b(kDeviceB, GetParam());
+ ASSERT_TRUE(SetupConnection(user_a, user_b));
+
+ user_a.ExpectPayload(payload_latch_);
+ user_b.SendPayload(Payload(ByteArray{std::string(kMessage)}));
+ EXPECT_TRUE(payload_latch_.Await(kDefaultTimeout).result());
+ EXPECT_EQ(user_a.GetPayload().AsBytes(), ByteArray(std::string(kMessage)));
+ NEARBY_LOG(INFO, "Test completed.");
+
+ user_a.Stop();
+ user_b.Stop();
+ env_.Stop();
+}
+
+TEST_P(PayloadManagerTest, CanSendStreamPayload) {
+ env_.Start();
+ PayloadSimulationUser user_a(kDeviceA, GetParam());
+ PayloadSimulationUser user_b(kDeviceB, GetParam());
+ ASSERT_TRUE(SetupConnection(user_a, user_b));
+
+ auto pipe = std::make_shared<Pipe>();
+ OutputStream& tx = pipe->GetOutputStream();
+
+ user_a.ExpectPayload(payload_latch_);
+ const ByteArray message{std::string(kMessage)};
+ // The first write to the output stream will send the first PAYLOAD_TRANSFER
+ // packet with payload info and message data.
+ tx.Write(message);
+
+ user_b.SendPayload(Payload([pipe]() -> InputStream& {
+ return pipe->GetInputStream(); // NOLINT
+ }));
+ ASSERT_TRUE(payload_latch_.Await(kDefaultTimeout).result());
+ ASSERT_NE(user_a.GetPayload().AsStream(), nullptr);
+ InputStream& rx = *user_a.GetPayload().AsStream();
+ NEARBY_LOG(INFO, "Stream extracted.");
+
+ EXPECT_TRUE(user_a.WaitForProgress(
+ [&message](const PayloadProgressInfo& info) {
+ return info.bytes_transferred >= message.size();
+ },
+ kProgressTimeout));
+ ByteArray result = rx.Read(Pipe::kChunkSize).result();
+ EXPECT_EQ(result, message);
+ NEARBY_LOG(INFO, "Packet 1 handled.");
+
+ tx.Write(message);
+ EXPECT_TRUE(user_a.WaitForProgress(
+ [&message](const PayloadProgressInfo& info) {
+ return info.bytes_transferred >= 2 * message.size();
+ },
+ kProgressTimeout));
+ ByteArray result2 = rx.Read(Pipe::kChunkSize).result();
+ EXPECT_EQ(result2, message);
+ NEARBY_LOG(INFO, "Packet 2 handled.");
+
+ rx.Close();
+ tx.Close();
+ NEARBY_LOG(INFO, "Test completed.");
+ user_a.Stop();
+ user_b.Stop();
+ env_.Stop();
+}
+
+TEST_P(PayloadManagerTest, CanCancelPayloadOnReceiverSide) {
+ env_.Start();
+ PayloadSimulationUser user_a(kDeviceA, GetParam());
+ PayloadSimulationUser user_b(kDeviceB, GetParam());
+ ASSERT_TRUE(SetupConnection(user_a, user_b));
+
+ auto pipe = std::make_shared<Pipe>();
+ OutputStream& tx = pipe->GetOutputStream();
+
+ user_a.ExpectPayload(payload_latch_);
+ const ByteArray message{std::string(kMessage)};
+ tx.Write(message);
+
+ user_b.SendPayload(Payload([pipe]() -> InputStream& {
+ return pipe->GetInputStream(); // NOLINT
+ }));
+ ASSERT_TRUE(payload_latch_.Await(kDefaultTimeout).result());
+ ASSERT_NE(user_a.GetPayload().AsStream(), nullptr);
+ InputStream& rx = *user_a.GetPayload().AsStream();
+ NEARBY_LOG(INFO, "Stream extracted.");
+
+ EXPECT_TRUE(user_a.WaitForProgress(
+ [&message](const PayloadProgressInfo& info) {
+ return info.bytes_transferred >= message.size();
+ },
+ kProgressTimeout));
+ ByteArray result = rx.Read(Pipe::kChunkSize).result();
+ EXPECT_EQ(result, message);
+ NEARBY_LOG(INFO, "Packet 1 handled.");
+
+ EXPECT_EQ(user_a.CancelPayload(), Status{Status::kSuccess});
+ NEARBY_LOG(INFO, "Stream canceled on receiver side.");
+
+ // Sender will only handle cancel event if it is sending.
+ // Once cancel is handled, write will fail.
+ int count = 0;
+ while (true) {
+ if (!tx.Write(message).Ok()) break;
+ SystemClock::Sleep(kDefaultTimeout);
+ count++;
+ }
+ ASSERT_LE(count, 10);
+
+ EXPECT_TRUE(user_a.WaitForProgress(
+ [status = PayloadProgressInfo::Status::kCanceled](
+ const PayloadProgressInfo& info) { return info.status == status; },
+ kProgressTimeout));
+ NEARBY_LOG(INFO, "Stream cancelation received.");
+
+ tx.Close();
+ rx.Close();
+
+ NEARBY_LOG(INFO, "Test completed.");
+ user_a.Stop();
+ user_b.Stop();
+ env_.Stop();
+}
+
+TEST_P(PayloadManagerTest, CanCancelPayloadOnSenderSide) {
+ env_.Start();
+ PayloadSimulationUser user_a(kDeviceA, GetParam());
+ PayloadSimulationUser user_b(kDeviceB, GetParam());
+ ASSERT_TRUE(SetupConnection(user_a, user_b));
+
+ auto pipe = std::make_shared<Pipe>();
+ OutputStream& tx = pipe->GetOutputStream();
+
+ user_a.ExpectPayload(payload_latch_);
+ const ByteArray message{std::string(kMessage)};
+ tx.Write(message);
+
+ user_b.SendPayload(Payload([pipe]() -> InputStream& {
+ return pipe->GetInputStream(); // NOLINT
+ }));
+ ASSERT_TRUE(payload_latch_.Await(kDefaultTimeout).result());
+ ASSERT_NE(user_a.GetPayload().AsStream(), nullptr);
+ InputStream& rx = *user_a.GetPayload().AsStream();
+ NEARBY_LOG(INFO, "Stream extracted.");
+
+ EXPECT_TRUE(user_a.WaitForProgress(
+ [&message](const PayloadProgressInfo& info) {
+ return info.bytes_transferred >= message.size();
+ },
+ kProgressTimeout));
+ ByteArray result = rx.Read(Pipe::kChunkSize).result();
+ EXPECT_EQ(result, message);
+ NEARBY_LOG(INFO, "Packet 1 handled.");
+
+ EXPECT_EQ(user_b.CancelPayload(), Status{Status::kSuccess});
+ NEARBY_LOG(INFO, "Stream canceled on sender side.");
+
+ // Sender will only handle cancel event if it is sending.
+ // Once cancel is handled, write will fail.
+ int count = 0;
+ while (true) {
+ if (!tx.Write(message).Ok()) break;
+ SystemClock::Sleep(kDefaultTimeout);
+ count++;
+ }
+ ASSERT_LE(count, 10);
+
+ EXPECT_TRUE(user_a.WaitForProgress(
+ [status = PayloadProgressInfo::Status::kCanceled](
+ const PayloadProgressInfo& info) { return info.status == status; },
+ kProgressTimeout));
+ NEARBY_LOG(INFO, "Stream cancelation received.");
+
+ tx.Close();
+ rx.Close();
+
+ NEARBY_LOG(INFO, "Test completed.");
+ user_a.Stop();
+ user_b.Stop();
+ env_.Stop();
+}
+
+TEST_P(PayloadManagerTest, SendPayloadWithSkip_StreamPayload) {
+ constexpr size_t kOffset = 3;
+ env_.Start();
+ PayloadSimulationUser user_a(kDeviceA, GetParam());
+ PayloadSimulationUser user_b(kDeviceB, GetParam());
+ ASSERT_TRUE(SetupConnection(user_a, user_b));
+
+ auto pipe = std::make_shared<Pipe>();
+ OutputStream& tx = pipe->GetOutputStream();
+
+ user_a.ExpectPayload(payload_latch_);
+ const ByteArray message{std::string(kMessage)};
+ // The first write to the output stream will send the first PAYLOAD_TRANSFER
+ // packet with payload info and message data.
+ tx.Write(message);
+
+ Payload payload([pipe]() -> InputStream& {
+ return pipe->GetInputStream(); // NOLINT
+ });
+ payload.SetOffset(kOffset);
+ user_b.SendPayload(std::move(payload));
+ ASSERT_TRUE(payload_latch_.Await(kDefaultTimeout).result());
+ ASSERT_NE(user_a.GetPayload().AsStream(), nullptr);
+ InputStream& rx = *user_a.GetPayload().AsStream();
+ NEARBY_LOG(INFO, "Stream extracted.");
+
+ EXPECT_TRUE(user_a.WaitForProgress(
+ [&message](const PayloadProgressInfo& info) {
+ return info.bytes_transferred >= message.size() - kOffset;
+ },
+ kProgressTimeout));
+ ByteArray result = rx.Read(Pipe::kChunkSize).result();
+ EXPECT_EQ(result, ByteArray("sage"));
+ NEARBY_LOG(INFO, "Packet 1 handled.");
+
+ tx.Write(message);
+ EXPECT_TRUE(user_a.WaitForProgress(
+ [&message](const PayloadProgressInfo& info) {
+ return info.bytes_transferred >= 2 * message.size() - kOffset;
+ },
+ kProgressTimeout));
+ ByteArray result2 = rx.Read(Pipe::kChunkSize).result();
+ EXPECT_EQ(result2, message);
+ NEARBY_LOG(INFO, "Packet 2 handled.");
+
+ rx.Close();
+ tx.Close();
+ NEARBY_LOG(INFO, "Test completed.");
+ user_a.Stop();
+ user_b.Stop();
+ env_.Stop();
+}
+
+INSTANTIATE_TEST_SUITE_P(ParametrisedPayloadManagerTest, PayloadManagerTest,
+ ::testing::ValuesIn(kTestCases));
+
+} // namespace
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/pcp.h b/chromium/third_party/nearby/src/connections/implementation/pcp.h
index 657db612e30..657db612e30 100644
--- a/chromium/third_party/nearby/src/cpp/core/internal/pcp.h
+++ b/chromium/third_party/nearby/src/connections/implementation/pcp.h
diff --git a/chromium/third_party/nearby/src/connections/implementation/pcp_handler.h b/chromium/third_party/nearby/src/connections/implementation/pcp_handler.h
new file mode 100644
index 00000000000..fda4cb6e79d
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/pcp_handler.h
@@ -0,0 +1,122 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_PCP_HANDLER_H_
+#define CORE_INTERNAL_PCP_HANDLER_H_
+
+#include <vector>
+
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/pcp.h"
+#include "connections/listeners.h"
+#include "connections/out_of_band_connection_metadata.h"
+#include "connections/params.h"
+#include "connections/status.h"
+#include "connections/strategy.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+inline Pcp StrategyToPcp(Strategy strategy) {
+ if (strategy == Strategy::kP2pCluster) return Pcp::kP2pCluster;
+ if (strategy == Strategy::kP2pStar) return Pcp::kP2pStar;
+ if (strategy == Strategy::kP2pPointToPoint) return Pcp::kP2pPointToPoint;
+ return Pcp::kUnknown;
+}
+
+inline Strategy PcpToStrategy(Pcp pcp) {
+ if (pcp == Pcp::kP2pCluster) return Strategy::kP2pCluster;
+ if (pcp == Pcp::kP2pStar) return Strategy::kP2pStar;
+ if (pcp == Pcp::kP2pPointToPoint) return Strategy::kP2pPointToPoint;
+ return Strategy::kNone;
+}
+
+// Defines the set of methods that need to be implemented to handle the
+// per-PCP-specific operations in the OfflineServiceController.
+//
+// These methods are all meant to be synchronous, and should return only after
+// knowing they've done what they were supposed to do (or unequivocally failed
+// to do so).
+//
+// See details here:
+// cpp/core/core.h
+class PcpHandler {
+ public:
+ virtual ~PcpHandler() = default;
+
+ // Return strategy supported by this protocol.
+ virtual Strategy GetStrategy() const = 0;
+
+ // Return concrete variant of protocol.
+ virtual Pcp GetPcp() const = 0;
+
+ // We have been asked by the client to start advertising. Once we successfully
+ // start advertising, we'll change the ClientProxy's state.
+ // ConnectionListener (info.listener) will be notified in case of any event.
+ // See
+ // cpp/core/listeners.h
+ virtual Status StartAdvertising(ClientProxy* client,
+ const std::string& service_id,
+ const AdvertisingOptions& advertising_options,
+ const ConnectionRequestInfo& info) = 0;
+
+ // If Advertising is active, stop it, and change CLientProxy state,
+ // otherwise do nothing.
+ virtual void StopAdvertising(ClientProxy* client) = 0;
+
+ // Start discovery of endpoints that may be advertising.
+ // Update ClientProxy state once discovery started.
+ // DiscoveryListener will get called in case of any event.
+ virtual Status StartDiscovery(ClientProxy* client,
+ const std::string& service_id,
+ const DiscoveryOptions& discovery_options,
+ const DiscoveryListener& listener) = 0;
+
+ // If Discovery is active, stop it, and change CLientProxy state,
+ // otherwise do nothing.
+ virtual void StopDiscovery(ClientProxy* client) = 0;
+
+ // If Discovery is active with is_out_of_band_connection == true, invoke the
+ // callback with the provided endpoint info.
+ virtual void InjectEndpoint(ClientProxy* client,
+ const std::string& service_id,
+ const OutOfBandConnectionMetadata& metadata) = 0;
+
+ // If remote endpoint has been successfully discovered, request it to form a
+ // connection, update state on ClientProxy.
+ virtual Status RequestConnection(
+ ClientProxy* client, const std::string& endpoint_id,
+ const ConnectionRequestInfo& info,
+ const ConnectionOptions& connection_options) = 0;
+
+ // Either party may call this to accept connection on their part.
+ // Until both parties call it, connection will not reach a data phase.
+ // Update state in ClientProxy.
+ virtual Status AcceptConnection(ClientProxy* client,
+ const std::string& endpoint_id,
+ const PayloadListener& payload_listener) = 0;
+
+ // Either party may call this to reject connection on their part before
+ // connection reaches data phase. If either party does call it, connection
+ // will terminate. Update state in ClientProxy.
+ virtual Status RejectConnection(ClientProxy* client,
+ const std::string& endpoint_id) = 0;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_PCP_HANDLER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/pcp_manager.cc b/chromium/third_party/nearby/src/connections/implementation/pcp_manager.cc
new file mode 100644
index 00000000000..d26fb212537
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/pcp_manager.cc
@@ -0,0 +1,148 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/pcp_manager.h"
+
+#include "connections/implementation/p2p_cluster_pcp_handler.h"
+#include "connections/implementation/p2p_point_to_point_pcp_handler.h"
+#include "connections/implementation/p2p_star_pcp_handler.h"
+#include "connections/implementation/pcp_handler.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+PcpManager::PcpManager(
+ Mediums& mediums, EndpointChannelManager& channel_manager,
+ EndpointManager& endpoint_manager, BwuManager& bwu_manager,
+ InjectedBluetoothDeviceStore& injected_bluetooth_device_store) {
+ handlers_[Pcp::kP2pCluster] = std::make_unique<P2pClusterPcpHandler>(
+ &mediums, &endpoint_manager, &channel_manager, &bwu_manager,
+ injected_bluetooth_device_store);
+ handlers_[Pcp::kP2pStar] = std::make_unique<P2pStarPcpHandler>(
+ mediums, endpoint_manager, channel_manager, bwu_manager,
+ injected_bluetooth_device_store);
+ handlers_[Pcp::kP2pPointToPoint] =
+ std::make_unique<P2pPointToPointPcpHandler>(
+ mediums, endpoint_manager, channel_manager, bwu_manager,
+ injected_bluetooth_device_store);
+}
+
+void PcpManager::DisconnectFromEndpointManager() {
+ if (shutdown_.Set(true)) return;
+ for (auto& item : handlers_) {
+ if (!item.second) continue;
+ item.second->DisconnectFromEndpointManager();
+ }
+}
+
+PcpManager::~PcpManager() {
+ NEARBY_LOGS(INFO) << "Initiating shutdown of PcpManager.";
+ DisconnectFromEndpointManager();
+ NEARBY_LOGS(INFO) << "PcpManager has shut down.";
+}
+
+Status PcpManager::StartAdvertising(
+ ClientProxy* client, const string& service_id,
+ const AdvertisingOptions& advertising_options,
+ const ConnectionRequestInfo& info) {
+ if (!SetCurrentPcpHandler(advertising_options.strategy)) {
+ return {Status::kError};
+ }
+
+ return current_->StartAdvertising(client, service_id, advertising_options,
+ info);
+}
+
+void PcpManager::StopAdvertising(ClientProxy* client) {
+ if (current_) {
+ current_->StopAdvertising(client);
+ }
+}
+
+Status PcpManager::StartDiscovery(ClientProxy* client, const string& service_id,
+ const DiscoveryOptions& discovery_options,
+ DiscoveryListener listener) {
+ if (!SetCurrentPcpHandler(discovery_options.strategy)) {
+ return {Status::kError};
+ }
+
+ return current_->StartDiscovery(client, service_id, discovery_options,
+ std::move(listener));
+}
+
+void PcpManager::StopDiscovery(ClientProxy* client) {
+ if (current_) {
+ current_->StopDiscovery(client);
+ }
+}
+
+void PcpManager::InjectEndpoint(ClientProxy* client,
+ const std::string& service_id,
+ const OutOfBandConnectionMetadata& metadata) {
+ if (current_) {
+ current_->InjectEndpoint(client, service_id, metadata);
+ }
+}
+
+Status PcpManager::RequestConnection(
+ ClientProxy* client, const string& endpoint_id,
+ const ConnectionRequestInfo& info,
+ const ConnectionOptions& connection_options) {
+ if (!current_) {
+ return {Status::kOutOfOrderApiCall};
+ }
+
+ return current_->RequestConnection(client, endpoint_id, info,
+ connection_options);
+}
+
+Status PcpManager::AcceptConnection(ClientProxy* client,
+ const string& endpoint_id,
+ const PayloadListener& payload_listener) {
+ if (!current_) {
+ return {Status::kOutOfOrderApiCall};
+ }
+
+ return current_->AcceptConnection(client, endpoint_id, payload_listener);
+}
+
+Status PcpManager::RejectConnection(ClientProxy* client,
+ const string& endpoint_id) {
+ if (!current_) {
+ return {Status::kOutOfOrderApiCall};
+ }
+
+ return current_->RejectConnection(client, endpoint_id);
+}
+
+bool PcpManager::SetCurrentPcpHandler(Strategy strategy) {
+ current_ = GetPcpHandler(StrategyToPcp(strategy));
+
+ if (!current_) {
+ NEARBY_LOG(ERROR, "Failed to set current PCP handler: strategy=%s",
+ strategy.GetName().c_str());
+ }
+
+ return current_;
+}
+
+PcpHandler* PcpManager::GetPcpHandler(Pcp pcp) const {
+ auto item = handlers_.find(pcp);
+ return item != handlers_.end() ? item->second.get() : nullptr;
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/pcp_manager.h b/chromium/third_party/nearby/src/connections/implementation/pcp_manager.h
new file mode 100644
index 00000000000..41a574e6a34
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/pcp_manager.h
@@ -0,0 +1,87 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_PCP_MANAGER_H_
+#define CORE_INTERNAL_PCP_MANAGER_H_
+
+#include <string>
+
+#include "absl/container/flat_hash_map.h"
+#include "connections/implementation/base_pcp_handler.h"
+#include "connections/implementation/bwu_manager.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/endpoint_channel_manager.h"
+#include "connections/implementation/endpoint_manager.h"
+#include "connections/implementation/injected_bluetooth_device_store.h"
+#include "connections/implementation/mediums/mediums.h"
+#include "connections/listeners.h"
+#include "connections/status.h"
+#include "connections/strategy.h"
+#include "internal/platform/atomic_boolean.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Manages all known PcpHandler implementations, delegating operations to the
+// appropriate one as per the parameters passed in.
+//
+// This will only ever be used by the OfflineServiceController, which has all
+// of its entrypoints invoked serially, so there's no synchronization needed.
+// Public method semantics matches definition in the
+// cpp/core/internal/service_controller.h
+class PcpManager {
+ public:
+ PcpManager(Mediums& mediums, EndpointChannelManager& channel_manager,
+ EndpointManager& endpoint_manager, BwuManager& bwu_manager,
+ InjectedBluetoothDeviceStore& injected_bluetooth_device_store);
+ ~PcpManager();
+
+ Status StartAdvertising(ClientProxy* client, const string& service_id,
+ const AdvertisingOptions& advertising_options,
+ const ConnectionRequestInfo& info);
+ void StopAdvertising(ClientProxy* client);
+
+ Status StartDiscovery(ClientProxy* client, const string& service_id,
+ const DiscoveryOptions& discovery_options,
+ DiscoveryListener listener);
+ void StopDiscovery(ClientProxy* client);
+
+ void InjectEndpoint(ClientProxy* client, const std::string& service_id,
+ const OutOfBandConnectionMetadata& metadata);
+
+ Status RequestConnection(ClientProxy* client, const string& endpoint_id,
+ const ConnectionRequestInfo& info,
+ const ConnectionOptions& connection_options);
+ Status AcceptConnection(ClientProxy* client, const string& endpoint_id,
+ const PayloadListener& payload_listener);
+ Status RejectConnection(ClientProxy* client, const string& endpoint_id);
+
+ proto::connections::Medium GetBandwidthUpgradeMedium();
+ void DisconnectFromEndpointManager();
+
+ private:
+ bool SetCurrentPcpHandler(Strategy strategy);
+ PcpHandler* GetPcpHandler(Pcp pcp) const;
+
+ AtomicBoolean shutdown_{false};
+ absl::flat_hash_map<Pcp, std::unique_ptr<BasePcpHandler>> handlers_;
+ PcpHandler* current_ = nullptr;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_PCP_MANAGER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/pcp_manager_test.cc b/chromium/third_party/nearby/src/connections/implementation/pcp_manager_test.cc
new file mode 100644
index 00000000000..be023ec2297
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/pcp_manager_test.cc
@@ -0,0 +1,177 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/pcp_manager.h"
+
+#include <array>
+#include <string>
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "absl/time/time.h"
+#include "connections/implementation/endpoint_channel_manager.h"
+#include "connections/implementation/simulation_user.h"
+#include "internal/platform/medium_environment.h"
+#include "internal/platform/count_down_latch.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+
+constexpr std::array<char, 6> kFakeMacAddress = {'a', 'b', 'c', 'd', 'e', 'f'};
+constexpr char kServiceId[] = "service-id";
+constexpr char kDeviceA[] = "device-A";
+constexpr char kDeviceB[] = "device-B";
+
+constexpr BooleanMediumSelector kTestCases[] = {
+ BooleanMediumSelector{
+ .bluetooth = true,
+ },
+ BooleanMediumSelector{
+ .wifi_lan = true,
+ },
+ BooleanMediumSelector{
+ .bluetooth = true,
+ .wifi_lan = true,
+ },
+};
+
+class PcpManagerTest : public ::testing::TestWithParam<BooleanMediumSelector> {
+ protected:
+ PcpManagerTest() { env_.Stop(); }
+
+ MediumEnvironment& env_{MediumEnvironment::Instance()};
+};
+
+TEST_P(PcpManagerTest, CanCreateOne) {
+ env_.Start();
+ SimulationUser user(kDeviceA, GetParam());
+ env_.Stop();
+}
+
+TEST_P(PcpManagerTest, CanCreateMany) {
+ env_.Start();
+ SimulationUser user_a(kDeviceA, GetParam());
+ SimulationUser user_b(kDeviceB, GetParam());
+ env_.Stop();
+}
+
+TEST_P(PcpManagerTest, CanAdvertise) {
+ env_.Start();
+ SimulationUser user_a(kDeviceA, GetParam());
+ SimulationUser user_b(kDeviceB, GetParam());
+ user_a.StartAdvertising(kServiceId, nullptr);
+ env_.Stop();
+}
+
+TEST_P(PcpManagerTest, CanDiscover) {
+ env_.Start();
+ SimulationUser user_a("device-a", GetParam());
+ SimulationUser user_b("device-b", GetParam());
+ user_a.StartAdvertising(kServiceId, nullptr);
+ CountDownLatch latch(1);
+ user_b.StartDiscovery(kServiceId, &latch);
+ EXPECT_TRUE(latch.Await(absl::Milliseconds(1000)).result());
+ EXPECT_EQ(user_b.GetDiscovered().service_id, kServiceId);
+ EXPECT_EQ(user_b.GetDiscovered().endpoint_info, user_a.GetInfo());
+ env_.Stop();
+}
+
+TEST_P(PcpManagerTest, CanConnect) {
+ env_.Start();
+ SimulationUser user_a("device-a", GetParam());
+ SimulationUser user_b("device-b", GetParam());
+ CountDownLatch discovery_latch(1);
+ CountDownLatch connection_latch(2);
+ user_a.StartAdvertising(kServiceId, &connection_latch);
+ user_b.StartDiscovery(kServiceId, &discovery_latch);
+ EXPECT_TRUE(discovery_latch.Await(absl::Milliseconds(1000)).result());
+ EXPECT_EQ(user_b.GetDiscovered().service_id, kServiceId);
+ EXPECT_EQ(user_b.GetDiscovered().endpoint_info, user_a.GetInfo());
+ user_b.RequestConnection(&connection_latch);
+ EXPECT_TRUE(connection_latch.Await(absl::Milliseconds(1000)).result());
+ user_a.Stop();
+ user_b.Stop();
+ env_.Stop();
+}
+
+TEST_P(PcpManagerTest, CanAccept) {
+ env_.Start();
+ SimulationUser user_a("device-a", GetParam());
+ SimulationUser user_b("device-b", GetParam());
+ CountDownLatch discovery_latch(1);
+ CountDownLatch connection_latch(2);
+ CountDownLatch accept_latch(2);
+ user_a.StartAdvertising(kServiceId, &connection_latch);
+ user_b.StartDiscovery(kServiceId, &discovery_latch);
+ EXPECT_TRUE(discovery_latch.Await(absl::Milliseconds(1000)).result());
+ EXPECT_EQ(user_b.GetDiscovered().service_id, kServiceId);
+ EXPECT_EQ(user_b.GetDiscovered().endpoint_info, user_a.GetInfo());
+ user_b.RequestConnection(&connection_latch);
+ EXPECT_TRUE(connection_latch.Await(absl::Milliseconds(1000)).result());
+ user_a.AcceptConnection(&accept_latch);
+ user_b.AcceptConnection(&accept_latch);
+ EXPECT_TRUE(accept_latch.Await(absl::Milliseconds(1000)).result());
+ user_a.Stop();
+ user_b.Stop();
+ env_.Stop();
+}
+
+TEST_P(PcpManagerTest, CanReject) {
+ env_.Start();
+ SimulationUser user_a("device-a", GetParam());
+ SimulationUser user_b("device-b", GetParam());
+ CountDownLatch discovery_latch(1);
+ CountDownLatch connection_latch(2);
+ CountDownLatch reject_latch(1);
+ user_a.StartAdvertising(kServiceId, &connection_latch);
+ user_b.StartDiscovery(kServiceId, &discovery_latch);
+ EXPECT_TRUE(discovery_latch.Await(absl::Milliseconds(1000)).result());
+ EXPECT_EQ(user_b.GetDiscovered().service_id, kServiceId);
+ EXPECT_EQ(user_b.GetDiscovered().endpoint_info, user_a.GetInfo());
+ user_b.RequestConnection(&connection_latch);
+ EXPECT_TRUE(connection_latch.Await(absl::Milliseconds(1000)).result());
+ user_b.ExpectRejectedConnection(reject_latch);
+ user_a.RejectConnection(nullptr);
+ EXPECT_TRUE(reject_latch.Await(absl::Milliseconds(1000)).result());
+ user_a.Stop();
+ user_b.Stop();
+ env_.Stop();
+}
+
+INSTANTIATE_TEST_SUITE_P(ParametrisedPcpManagerTest, PcpManagerTest,
+ ::testing::ValuesIn(kTestCases));
+
+// Verifies that InjectEndpoint() can be run successfully; does not test the
+// full connection flow given that normal discovery/advertisement is skipped.
+// Note: Not parameterized because InjectEndpoint only works over Bluetooth.
+TEST_F(PcpManagerTest, InjectEndpoint) {
+ env_.Start();
+ SimulationUser user_a(kDeviceA, BooleanMediumSelector{.bluetooth = true});
+ user_a.StartDiscovery(kServiceId, /*latch=*/nullptr);
+ user_a.InjectEndpoint(kServiceId, OutOfBandConnectionMetadata{
+ .medium = Medium::BLUETOOTH,
+ .remote_bluetooth_mac_address =
+ ByteArray(kFakeMacAddress),
+ });
+ user_a.Stop();
+ env_.Stop();
+}
+
+} // namespace
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/proto/BUILD b/chromium/third_party/nearby/src/connections/implementation/proto/BUILD
new file mode 100644
index 00000000000..a01a2fdd601
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/proto/BUILD
@@ -0,0 +1,48 @@
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+load("//tools/build_defs/proto/cpp:cc_proto_library.bzl", "cc_proto_library")
+
+licenses(["notice"])
+
+proto_library(
+ name = "offline_wire_formats_proto",
+ srcs = [
+ "offline_wire_formats.proto",
+ ],
+ visibility = [
+ "//internal/platform/implementation/ios:__subpackages__",
+ ],
+)
+
+java_lite_proto_library(
+ name = "offline_wire_formats_java_proto_lite",
+ visibility = [
+ "//java/com/google/android/gmscore/integ/modules/nearby:__subpackages__",
+ "//javatests/com/google/android/gmscore/integ/modules/nearby:__subpackages__",
+ ],
+ deps = [":offline_wire_formats_proto"],
+)
+
+cc_proto_library(
+ name = "offline_wire_formats_cc_proto",
+ deps = [
+ ":offline_wire_formats_proto",
+ ],
+)
+
+filegroup(
+ name = "offline_wire_formats_proto_config",
+ srcs = ["offline_wire_formats_proto_config.asciipb"],
+)
diff --git a/chromium/third_party/nearby/src/proto/connections/CMakeLists.txt b/chromium/third_party/nearby/src/connections/implementation/proto/CMakeLists.txt
index 9195a301033..9195a301033 100644
--- a/chromium/third_party/nearby/src/proto/connections/CMakeLists.txt
+++ b/chromium/third_party/nearby/src/connections/implementation/proto/CMakeLists.txt
diff --git a/chromium/third_party/nearby/src/connections/implementation/proto/offline_wire_formats.proto b/chromium/third_party/nearby/src/connections/implementation/proto/offline_wire_formats.proto
new file mode 100644
index 00000000000..a86c53d6ea6
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/proto/offline_wire_formats.proto
@@ -0,0 +1,364 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+syntax = "proto2";
+
+package location.nearby.connections;
+
+option optimize_for = LITE_RUNTIME;
+option java_outer_classname = "OfflineWireFormatsProto";
+option java_package = "com.google.location.nearby.connections.proto";
+option objc_class_prefix = "GNCP";
+
+message OfflineFrame {
+ enum Version {
+ UNKNOWN_VERSION = 0;
+ V1 = 1;
+ }
+ optional Version version = 1;
+
+ // Right now there's only 1 version, but if there are more, exactly one of
+ // the following fields will be set.
+ optional V1Frame v1 = 2;
+}
+
+message V1Frame {
+ enum FrameType {
+ UNKNOWN_FRAME_TYPE = 0;
+ CONNECTION_REQUEST = 1;
+ CONNECTION_RESPONSE = 2;
+ PAYLOAD_TRANSFER = 3;
+ BANDWIDTH_UPGRADE_NEGOTIATION = 4;
+ KEEP_ALIVE = 5;
+ DISCONNECTION = 6;
+ PAIRED_KEY_ENCRYPTION = 7;
+ }
+ optional FrameType type = 1;
+
+ // Exactly one of the following fields will be set.
+ optional ConnectionRequestFrame connection_request = 2;
+ optional ConnectionResponseFrame connection_response = 3;
+ optional PayloadTransferFrame payload_transfer = 4;
+ optional BandwidthUpgradeNegotiationFrame bandwidth_upgrade_negotiation = 5;
+ optional KeepAliveFrame keep_alive = 6;
+ optional DisconnectionFrame disconnection = 7;
+ optional PairedKeyEncryptionFrame paired_key_encryption = 8;
+}
+
+message ConnectionRequestFrame {
+ // Should always match cs/symbol:location.nearby.proto.connections.Medium
+ // LINT.IfChange
+ enum Medium {
+ UNKNOWN_MEDIUM = 0;
+ MDNS = 1 [deprecated = true];
+ BLUETOOTH = 2;
+ WIFI_HOTSPOT = 3;
+ BLE = 4;
+ WIFI_LAN = 5;
+ WIFI_AWARE = 6;
+ NFC = 7;
+ WIFI_DIRECT = 8;
+ WEB_RTC = 9;
+ BLE_L2CAP = 10;
+ }
+ // LINT.ThenChange(//depot/google3/third_party/nearby/proto/connections_enums.proto)
+
+ optional string endpoint_id = 1;
+ optional string endpoint_name = 2;
+ optional bytes handshake_data = 3;
+ // A random number generated for each outgoing connection that is presently
+ // used to act as a tiebreaker when 2 devices connect to each other
+ // simultaneously; this can also be used for other initialization-scoped
+ // things in the future.
+ optional int32 nonce = 4;
+ // The mediums this device supports upgrading to. This list should be filtered
+ // by both the strategy and this device's individual limitations.
+ repeated Medium mediums = 5;
+ optional bytes endpoint_info = 6;
+ optional MediumMetadata medium_metadata = 7;
+ optional int32 keep_alive_interval_millis = 8;
+ optional int32 keep_alive_timeout_millis = 9;
+}
+
+message ConnectionResponseFrame {
+ // This doesn't need to send back endpoint_id and endpoint_name (like
+ // the ConnectionRequestFrame does) because those have already been
+ // transmitted out-of-band, at the time this endpoint was discovered.
+
+ // One of:
+ //
+ // - ConnectionsStatusCodes.STATUS_OK
+ // - ConnectionsStatusCodes.STATUS_CONNECTION_REJECTED.
+ optional int32 status = 1 [deprecated = true];
+ optional bytes handshake_data = 2;
+
+ // Used to replace the status integer parameter with a meaningful enum item.
+ // Map ConnectionsStatusCodes.STATUS_OK to ACCEPT and
+ // ConnectionsStatusCodes.STATUS_CONNECTION_REJECTED to REJECT.
+ // Flag: connection_replace_status_with_response_connectionResponseFrame
+ enum ResponseStatus {
+ UNKNOWN_RESPONSE_STATUS = 0;
+ ACCEPT = 1;
+ REJECT = 2;
+ }
+ optional ResponseStatus response = 3;
+}
+
+message PayloadTransferFrame {
+ enum PacketType {
+ UNKNOWN_PACKET_TYPE = 0;
+ DATA = 1;
+ CONTROL = 2;
+ }
+
+ message PayloadHeader {
+ enum PayloadType {
+ UNKNOWN_PAYLOAD_TYPE = 0;
+ BYTES = 1;
+ FILE = 2;
+ STREAM = 3;
+ }
+ optional int64 id = 1;
+ optional PayloadType type = 2;
+ optional int64 total_size = 3;
+ optional bool is_sensitive = 4;
+ optional string file_name = 5;
+ optional string parent_folder = 6;
+ }
+
+ // Accompanies DATA packets.
+ message PayloadChunk {
+ enum Flags { LAST_CHUNK = 0x1; }
+ optional int32 flags = 1;
+ optional int64 offset = 2;
+ optional bytes body = 3;
+ }
+
+ // Accompanies CONTROL packets.
+ message ControlMessage {
+ enum EventType {
+ UNKNOWN_EVENT_TYPE = 0;
+ PAYLOAD_ERROR = 1;
+ PAYLOAD_CANCELED = 2;
+ }
+
+ optional EventType event = 1;
+ optional int64 offset = 2;
+ }
+
+ optional PacketType packet_type = 1;
+ optional PayloadHeader payload_header = 2;
+
+ // Exactly one of the following fields will be set, depending on the type.
+ optional PayloadChunk payload_chunk = 3;
+ optional ControlMessage control_message = 4;
+}
+
+message BandwidthUpgradeNegotiationFrame {
+ enum EventType {
+ UNKNOWN_EVENT_TYPE = 0;
+ UPGRADE_PATH_AVAILABLE = 1;
+ LAST_WRITE_TO_PRIOR_CHANNEL = 2;
+ SAFE_TO_CLOSE_PRIOR_CHANNEL = 3;
+ CLIENT_INTRODUCTION = 4;
+ UPGRADE_FAILURE = 5;
+ CLIENT_INTRODUCTION_ACK = 6;
+ }
+
+ // Accompanies UPGRADE_PATH_AVAILABLE and UPGRADE_FAILURE events.
+ message UpgradePathInfo {
+ // Should always match cs/symbol:location.nearby.proto.connections.Medium
+ enum Medium {
+ UNKNOWN_MEDIUM = 0;
+ MDNS = 1 [deprecated = true];
+ BLUETOOTH = 2;
+ WIFI_HOTSPOT = 3;
+ BLE = 4;
+ WIFI_LAN = 5;
+ WIFI_AWARE = 6;
+ NFC = 7;
+ WIFI_DIRECT = 8;
+ WEB_RTC = 9;
+ }
+
+ // Accompanies Medium.WIFI_HOTSPOT.
+ message WifiHotspotCredentials {
+ optional string ssid = 1;
+ optional string password = 2;
+ optional int32 port = 3;
+ optional string gateway = 4 [default = "0.0.0.0"];
+ // This field can be a band or frequency
+ optional int32 frequency = 5 [default = -1];
+ }
+
+ // Accompanies Medium.WIFI_LAN.
+ message WifiLanSocket {
+ optional bytes ip_address = 1;
+ optional int32 wifi_port = 2;
+ }
+
+ // Accompanies Medium.BLUETOOTH.
+ message BluetoothCredentials {
+ optional string service_name = 1;
+ optional string mac_address = 2;
+ }
+
+ // Accompanies Medium.WIFI_AWARE.
+ message WifiAwareCredentials {
+ optional string service_id = 1;
+ optional bytes service_info = 2;
+ optional string password = 3;
+ }
+
+ // Accompanies Medium.WIFI_DIRECT.
+ message WifiDirectCredentials {
+ optional string ssid = 1;
+ optional string password = 2;
+ optional int32 port = 3;
+ optional int32 frequency = 4;
+ }
+
+ // Accompanies Medium.WEB_RTC
+ message WebRtcCredentials {
+ optional string peer_id = 1;
+ optional LocationHint location_hint = 2;
+ }
+
+ optional Medium medium = 1;
+
+ // Exactly one of the following fields will be set.
+ optional WifiHotspotCredentials wifi_hotspot_credentials = 2;
+ optional WifiLanSocket wifi_lan_socket = 3;
+ optional BluetoothCredentials bluetooth_credentials = 4;
+ optional WifiAwareCredentials wifi_aware_credentials = 5;
+ optional WifiDirectCredentials wifi_direct_credentials = 6;
+ optional WebRtcCredentials web_rtc_credentials = 8;
+
+ // Disable Encryption for this upgrade medium to improve throughput.
+ optional bool supports_disabling_encryption = 7;
+
+ // An ack will be sent after the CLIENT_INTRODUCTION frame.
+ optional bool supports_client_introduction_ack = 9;
+ }
+
+ // Accompanies CLIENT_INTRODUCTION events.
+ message ClientIntroduction {
+ optional string endpoint_id = 1;
+ optional bool supports_disabling_encryption = 2;
+ }
+
+ // Accompanies CLIENT_INTRODUCTION_ACK events.
+ message ClientIntroductionAck {}
+
+ optional EventType event_type = 1;
+
+ // Exactly one of the following fields will be set.
+ optional UpgradePathInfo upgrade_path_info = 2;
+ optional ClientIntroduction client_introduction = 3;
+ optional ClientIntroductionAck client_introduction_ack = 4;
+}
+
+message KeepAliveFrame {
+ // And ack will be sent after receiving KEEP_ALIVE frame.
+ optional bool ack = 1;
+}
+
+// Informs the remote side to immediately severe the socket connection.
+// Used in bandwidth upgrades to get around a race condition, but may be used
+// in other situations to trigger a faster disconnection event than waiting for
+// socket closed on the remote side.
+message DisconnectionFrame {
+ // Empty on purpose.
+}
+
+// A paired key encryption packet sent between devices, contains signed data.
+message PairedKeyEncryptionFrame {
+ // The encrypted data (raw authentication token for the established
+ // connection) in byte array format.
+ optional bytes signed_data = 1;
+}
+
+message MediumMetadata {
+ // True if local device supports 5GHz.
+ optional bool supports_5_ghz = 1;
+ // WiFi LAN BSSID
+ optional string bssid = 2;
+ // IP address
+ optional bytes ip_address = 3;
+ // True if local device supports 6GHz.
+ optional bool supports_6_ghz = 4;
+ // True if local device has mobile radio.
+ optional bool mobile_radio = 5;
+ // The frequency of the WiFi LAN AP (or -1 is not associated to an AP over
+ // WiFi).
+ optional int32 ap_frequency = 6 [default = -1];
+ // Available channels on the local device.
+ optional AvailableChannels available_channels = 7;
+ // Usable WiFi Direct client channels on the local device.
+ optional WifiDirectCliUsableChannels wifi_direct_cli_usable_channels = 8;
+ // Usable WiFi LAN channels on the local device.
+ optional WifiLanUsableChannels wifi_lan_usable_channels = 9;
+ // Usable WiFi Aware channels on the local device.
+ optional WifiAwareUsableChannels wifi_aware_usable_channels = 10;
+ // Usable WiFi Hotspot STA channels on the local device.
+ optional WifiHotspotStaUsableChannels wifi_hotspot_sta_usable_channels = 11;
+}
+
+// Available channels on the local device.
+message AvailableChannels {
+ repeated int32 channels = 1 [packed = true];
+}
+
+// Usable WiFi Direct client channels on the local device.
+message WifiDirectCliUsableChannels {
+ repeated int32 channels = 1 [packed = true];
+}
+
+// Usable WiFi LAN channels on the local device.
+message WifiLanUsableChannels {
+ repeated int32 channels = 1 [packed = true];
+}
+
+// Usable WiFi Aware channels on the local device.
+message WifiAwareUsableChannels {
+ repeated int32 channels = 1 [packed = true];
+}
+
+// Usable WiFi Hotspot STA channels on the local device.
+message WifiHotspotStaUsableChannels {
+ repeated int32 channels = 1 [packed = true];
+}
+
+// LocationHint is used to specify a location as well as format.
+message LocationHint {
+ // Location is the location, provided in the format specified by format.
+ optional string location = 1;
+
+ // the format of location.
+ optional LocationStandard.Format format = 2;
+}
+
+message LocationStandard {
+ enum Format {
+ UNKNOWN = 0;
+ // E164 country codes:
+ // https://en.wikipedia.org/wiki/List_of_country_calling_codes
+ // e.g. +1 for USA
+ E164_CALLING = 1;
+
+ // ISO 3166-1 alpha-2 country codes:
+ // https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
+ ISO_3166_1_ALPHA_2 = 2;
+ }
+}
diff --git a/chromium/third_party/nearby/src/proto/connections/offline_wire_formats_proto_config.asciipb b/chromium/third_party/nearby/src/connections/implementation/proto/offline_wire_formats_proto_config.asciipb
index 06e3dd55f24..06e3dd55f24 100644
--- a/chromium/third_party/nearby/src/proto/connections/offline_wire_formats_proto_config.asciipb
+++ b/chromium/third_party/nearby/src/connections/implementation/proto/offline_wire_formats_proto_config.asciipb
diff --git a/chromium/third_party/nearby/src/connections/implementation/service_controller.h b/chromium/third_party/nearby/src/connections/implementation/service_controller.h
new file mode 100644
index 00000000000..11e87a6d7a3
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/service_controller.h
@@ -0,0 +1,104 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_SERVICE_CONTROLLER_H_
+#define CORE_INTERNAL_SERVICE_CONTROLLER_H_
+
+#include <cstdint>
+#include <string>
+#include <vector>
+
+#include "connections/advertising_options.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/listeners.h"
+#include "connections/out_of_band_connection_metadata.h"
+#include "connections/params.h"
+#include "connections/payload.h"
+#include "connections/status.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Interface defines the core functionality of Nearby Connections Service.
+//
+// In every method, ClientProxy* represents the client app which receives
+// notifications from Nearby Connections service and forwards them to the app.
+// ResultCallback arguments are not provided for this class, because all methods
+// are called synchronously.
+// The rest of arguments have the same meaning as the corresponding
+// methods in the definition of location::nearby::Core API.
+//
+// See details here:
+// cpp/core/core.h
+class ServiceController {
+ public:
+ virtual ~ServiceController() = default;
+ ServiceController() = default;
+ ServiceController(const ServiceController&) = delete;
+ ServiceController& operator=(const ServiceController&) = delete;
+
+ // Stops and disables service controller.
+ //
+ // When service controller is stopped all API call fail early.
+ // Note that all Core, ClientProxy objects referencing this service
+ // controller are affected.
+ virtual void Stop() = 0;
+
+ // Starts advertising an endpoint for a local app.
+ virtual Status StartAdvertising(ClientProxy* client,
+ const std::string& service_id,
+ const AdvertisingOptions& advertising_options,
+ const ConnectionRequestInfo& info) = 0;
+
+ virtual void StopAdvertising(ClientProxy* client) = 0;
+
+ virtual Status StartDiscovery(ClientProxy* client,
+ const std::string& service_id,
+ const DiscoveryOptions& discovery_options,
+ const DiscoveryListener& listener) = 0;
+ virtual void StopDiscovery(ClientProxy* client) = 0;
+
+ virtual void InjectEndpoint(ClientProxy* client,
+ const std::string& service_id,
+ const OutOfBandConnectionMetadata& metadata) = 0;
+
+ virtual Status RequestConnection(
+ ClientProxy* client, const std::string& endpoint_id,
+ const ConnectionRequestInfo& info,
+ const ConnectionOptions& connection_options) = 0;
+ virtual Status AcceptConnection(ClientProxy* client,
+ const std::string& endpoint_id,
+ const PayloadListener& listener) = 0;
+ virtual Status RejectConnection(ClientProxy* client,
+ const std::string& endpoint_id) = 0;
+
+ virtual void InitiateBandwidthUpgrade(ClientProxy* client,
+ const std::string& endpoint_id) = 0;
+
+ virtual void SendPayload(ClientProxy* client,
+ const std::vector<std::string>& endpoint_ids,
+ Payload payload) = 0;
+
+ virtual Status CancelPayload(ClientProxy* client, Payload::Id payload_id) = 0;
+
+ virtual void DisconnectFromEndpoint(ClientProxy* client,
+ const std::string& endpoint_id) = 0;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_SERVICE_CONTROLLER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/service_controller_router.cc b/chromium/third_party/nearby/src/connections/implementation/service_controller_router.cc
new file mode 100644
index 00000000000..60b2377e905
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/service_controller_router.cc
@@ -0,0 +1,383 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/service_controller_router.h"
+
+#include <cstddef>
+#include <memory>
+#include <string>
+#include <utility>
+
+#include "absl/memory/memory.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/offline_service_controller.h"
+#include "connections/listeners.h"
+#include "connections/params.h"
+#include "connections/payload.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+// Length of a MAC address, which consists of 6 bytes uniquely identifying a
+// hardware interface.
+const std::size_t kMacAddressLength = 6u;
+
+// Length used for an endpoint ID, which identifies a device discovery and
+// associated connection request.
+const std::size_t kEndpointIdLength = 4u;
+
+// Maximum length for information describing an endpoint; this information is
+// advertised by one device and can be used by the other device to identify the
+// advertiser.
+const std::size_t kMaxEndpointInfoLength = 131u;
+
+bool ClientHasConnectionToAtLeastOneEndpoint(
+ ClientProxy* client, const std::vector<std::string>& remote_endpoint_ids) {
+ for (auto& endpoint_id : remote_endpoint_ids) {
+ if (client->IsConnectedToEndpoint(endpoint_id)) {
+ return true;
+ }
+ }
+ return false;
+}
+} // namespace
+
+ServiceControllerRouter::ServiceControllerRouter() {
+ NEARBY_LOGS(INFO) << "ServiceControllerRouter going up.";
+}
+
+ServiceControllerRouter::~ServiceControllerRouter() {
+ NEARBY_LOGS(INFO) << "ServiceControllerRouter going down.";
+
+ if (service_controller_) {
+ service_controller_->Stop();
+ }
+ // And make sure that cleanup is the last thing we do.
+ serializer_.Shutdown();
+}
+
+void ServiceControllerRouter::StartAdvertising(
+ ClientProxy* client, absl::string_view service_id,
+ const AdvertisingOptions& advertising_options,
+ const ConnectionRequestInfo& info, const ResultCallback& callback) {
+ RouteToServiceController(
+ "scr-start-advertising",
+ [this, client, service_id = std::string(service_id), advertising_options,
+ info, callback]() {
+ if (client->IsAdvertising()) {
+ callback.result_cb({Status::kAlreadyAdvertising});
+ return;
+ }
+
+ callback.result_cb(GetServiceController()->StartAdvertising(
+ client, service_id, advertising_options, info));
+ });
+}
+
+void ServiceControllerRouter::StopAdvertising(ClientProxy* client,
+ const ResultCallback& callback) {
+ RouteToServiceController("scr-stop-advertising", [this, client, callback]() {
+ if (client->IsAdvertising()) {
+ GetServiceController()->StopAdvertising(client);
+ }
+ callback.result_cb({Status::kSuccess});
+ });
+}
+
+void ServiceControllerRouter::StartDiscovery(
+ ClientProxy* client, absl::string_view service_id,
+ const DiscoveryOptions& discovery_options,
+ const DiscoveryListener& listener, const ResultCallback& callback) {
+ RouteToServiceController(
+ "scr-start-discovery",
+ [this, client, service_id = std::string(service_id), discovery_options,
+ listener, callback]() {
+ if (client->IsDiscovering()) {
+ callback.result_cb({Status::kAlreadyDiscovering});
+ return;
+ }
+
+ callback.result_cb(GetServiceController()->StartDiscovery(
+ client, service_id, discovery_options, listener));
+ });
+}
+
+void ServiceControllerRouter::StopDiscovery(ClientProxy* client,
+ const ResultCallback& callback) {
+ RouteToServiceController("scr-stop-discovery", [this, client, callback]() {
+ if (client->IsDiscovering()) {
+ GetServiceController()->StopDiscovery(client);
+ }
+ callback.result_cb({Status::kSuccess});
+ });
+}
+
+void ServiceControllerRouter::InjectEndpoint(
+ ClientProxy* client, absl::string_view service_id,
+ const OutOfBandConnectionMetadata& metadata,
+ const ResultCallback& callback) {
+ RouteToServiceController(
+ "scr-inject-endpoint",
+ [this, client, service_id = std::string(service_id), metadata,
+ callback]() {
+ // Currently, Bluetooth is the only supported medium for endpoint
+ // injection.
+ if (metadata.medium != Medium::BLUETOOTH ||
+ metadata.remote_bluetooth_mac_address.size() != kMacAddressLength) {
+ callback.result_cb({Status::kError});
+ return;
+ }
+
+ if (metadata.endpoint_id.size() != kEndpointIdLength) {
+ callback.result_cb({Status::kError});
+ return;
+ }
+
+ if (metadata.endpoint_info.Empty() ||
+ metadata.endpoint_info.size() > kMaxEndpointInfoLength) {
+ callback.result_cb({Status::kError});
+ return;
+ }
+
+ if (!client->IsDiscovering()) {
+ callback.result_cb({Status::kOutOfOrderApiCall});
+ return;
+ }
+
+ GetServiceController()->InjectEndpoint(client, service_id, metadata);
+ callback.result_cb({Status::kSuccess});
+ });
+}
+
+void ServiceControllerRouter::RequestConnection(
+ ClientProxy* client, absl::string_view endpoint_id,
+ const ConnectionRequestInfo& info,
+ const ConnectionOptions& connection_options,
+ const ResultCallback& callback) {
+ // Cancellations can be fired from clients anytime, need to add the
+ // CancellationListener as soon as possible.
+ client->AddCancellationFlag(std::string(endpoint_id));
+
+ RouteToServiceController(
+ "scr-request-connection",
+ [this, client, endpoint_id = std::string(endpoint_id), info,
+ connection_options, callback]() {
+ if (client->HasPendingConnectionToEndpoint(endpoint_id) ||
+ client->IsConnectedToEndpoint(endpoint_id)) {
+ callback.result_cb({Status::kAlreadyConnectedToEndpoint});
+ return;
+ }
+
+ Status status = GetServiceController()->RequestConnection(
+ client, endpoint_id, info, connection_options);
+ if (!status.Ok()) {
+ client->CancelEndpoint(endpoint_id);
+ }
+ callback.result_cb(status);
+ });
+}
+
+void ServiceControllerRouter::AcceptConnection(ClientProxy* client,
+ absl::string_view endpoint_id,
+ const PayloadListener& listener,
+ const ResultCallback& callback) {
+ RouteToServiceController(
+ "scr-accept-connection",
+ [this, client, endpoint_id = std::string(endpoint_id), listener,
+ callback]() {
+ if (client->IsConnectedToEndpoint(endpoint_id)) {
+ callback.result_cb({Status::kAlreadyConnectedToEndpoint});
+ return;
+ }
+
+ if (client->HasLocalEndpointResponded(endpoint_id)) {
+ NEARBY_LOGS(WARNING)
+ << "Client " << client->GetClientId()
+ << " invoked acceptConnectionRequest() after having already "
+ "accepted/rejected the connection to endpoint(id="
+ << endpoint_id << ")";
+ callback.result_cb({Status::kOutOfOrderApiCall});
+ return;
+ }
+
+ callback.result_cb(GetServiceController()->AcceptConnection(
+ client, endpoint_id, listener));
+ });
+}
+
+void ServiceControllerRouter::RejectConnection(ClientProxy* client,
+ absl::string_view endpoint_id,
+ const ResultCallback& callback) {
+ client->CancelEndpoint(std::string(endpoint_id));
+
+ RouteToServiceController(
+ "scr-reject-connection",
+ [this, client, endpoint_id = std::string(endpoint_id), callback]() {
+ if (client->IsConnectedToEndpoint(endpoint_id)) {
+ callback.result_cb({Status::kAlreadyConnectedToEndpoint});
+ return;
+ }
+
+ if (client->HasLocalEndpointResponded(endpoint_id)) {
+ NEARBY_LOGS(WARNING)
+ << "Client " << client->GetClientId()
+ << " invoked rejectConnectionRequest() after having already "
+ "accepted/rejected the connection to endpoint(id="
+ << endpoint_id << ")";
+ callback.result_cb({Status::kOutOfOrderApiCall});
+ return;
+ }
+
+ callback.result_cb(
+ GetServiceController()->RejectConnection(client, endpoint_id));
+ });
+}
+
+void ServiceControllerRouter::InitiateBandwidthUpgrade(
+ ClientProxy* client, absl::string_view endpoint_id,
+ const ResultCallback& callback) {
+ RouteToServiceController(
+ "scr-init-bwu",
+ [this, client, endpoint_id = std::string(endpoint_id), callback]() {
+ if (!client->IsConnectedToEndpoint(endpoint_id)) {
+ callback.result_cb({Status::kOutOfOrderApiCall});
+ return;
+ }
+
+ GetServiceController()->InitiateBandwidthUpgrade(client, endpoint_id);
+
+ // Operation is triggered; the caller can listen to
+ // ConnectionListener::OnBandwidthChanged() to determine its success.
+ callback.result_cb({Status::kSuccess});
+ });
+}
+
+void ServiceControllerRouter::SendPayload(
+ ClientProxy* client, absl::Span<const std::string> endpoint_ids,
+ Payload payload, const ResultCallback& callback) {
+ // Payload is a move-only type.
+ // We have to capture it by value inside the lambda, and pass it over to
+ // the executor as an std::function<void()> instance.
+ // Lambda must be copyable, in order ot satisfy std::function<> requirements.
+ // To make it so, we need Payload wrapped by a copyable wrapper.
+ // std::shared_ptr<> is used, because it is copyable.
+ auto shared_payload = std::make_shared<Payload>(std::move(payload));
+ const std::vector<std::string> endpoints =
+ std::vector<std::string>(endpoint_ids.begin(), endpoint_ids.end());
+
+ RouteToServiceController("scr-send-payload", [this, client, shared_payload,
+ endpoints, callback]() {
+ if (!ClientHasConnectionToAtLeastOneEndpoint(client, endpoints)) {
+ callback.result_cb({Status::kEndpointUnknown});
+ return;
+ }
+
+ GetServiceController()->SendPayload(client, endpoints,
+ std::move(*shared_payload));
+
+ // At this point, we've queued up the send Payload request with the
+ // ServiceController; any further failures (e.g. one of the endpoints is
+ // unknown, goes away, or otherwise fails) will be returned to the
+ // client as a PayloadTransferUpdate.
+ callback.result_cb({Status::kSuccess});
+ });
+}
+
+void ServiceControllerRouter::CancelPayload(ClientProxy* client,
+ std::uint64_t payload_id,
+ const ResultCallback& callback) {
+ RouteToServiceController(
+ "scr-cancel-payload", [this, client, payload_id, callback]() {
+ callback.result_cb(
+ GetServiceController()->CancelPayload(client, payload_id));
+ });
+}
+
+void ServiceControllerRouter::DisconnectFromEndpoint(
+ ClientProxy* client, absl::string_view endpoint_id,
+ const ResultCallback& callback) {
+ // Client can emit the cancellation at anytime, we need to execute the request
+ // without further posting it.
+ client->CancelEndpoint(std::string(endpoint_id));
+
+ RouteToServiceController(
+ "scr-disconnect-endpoint",
+ [this, client, endpoint_id = std::string(endpoint_id), callback]() {
+ if (!client->IsConnectedToEndpoint(endpoint_id) &&
+ !client->HasPendingConnectionToEndpoint(endpoint_id)) {
+ callback.result_cb({Status::kOutOfOrderApiCall});
+ return;
+ }
+
+ GetServiceController()->DisconnectFromEndpoint(client, endpoint_id);
+ callback.result_cb({Status::kSuccess});
+ });
+}
+
+void ServiceControllerRouter::StopAllEndpoints(ClientProxy* client,
+ const ResultCallback& callback) {
+ // Client can emit the cancellation at anytime, we need to execute the request
+ // without further posting it.
+ client->CancelAllEndpoints();
+
+ RouteToServiceController(
+ "scr-stop-all-endpoints", [this, client, callback]() {
+ NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
+ << " has requested us to stop all endpoints. We will "
+ "now reset the client.";
+ FinishClientSession(client);
+ callback.result_cb({Status::kSuccess});
+ });
+}
+
+void ServiceControllerRouter::SetServiceControllerForTesting(
+ std::unique_ptr<ServiceController> service_controller) {
+ service_controller_ = std::move(service_controller);
+}
+
+ServiceController* ServiceControllerRouter::GetServiceController() {
+ if (!service_controller_) {
+ service_controller_ = std::make_unique<OfflineServiceController>();
+ }
+ return service_controller_.get();
+}
+
+void ServiceControllerRouter::FinishClientSession(ClientProxy* client) {
+ // Disconnect from all the connected endpoints tied to this clientProxy.
+ for (auto& endpoint_id : client->GetPendingConnectedEndpoints()) {
+ GetServiceController()->DisconnectFromEndpoint(client, endpoint_id);
+ }
+
+ for (auto& endpoint_id : client->GetConnectedEndpoints()) {
+ GetServiceController()->DisconnectFromEndpoint(client, endpoint_id);
+ }
+
+ // Stop any advertising and discovery that may be underway due to this client.
+ GetServiceController()->StopAdvertising(client);
+ GetServiceController()->StopDiscovery(client);
+
+ // Finally, clear all state maintained by this client.
+ client->Reset();
+}
+
+void ServiceControllerRouter::RouteToServiceController(const std::string& name,
+ Runnable runnable) {
+ serializer_.Execute(name, std::move(runnable));
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/service_controller_router.h b/chromium/third_party/nearby/src/connections/implementation/service_controller_router.h
new file mode 100644
index 00000000000..be665bceddf
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/service_controller_router.h
@@ -0,0 +1,129 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_SERVICE_CONTROLLER_ROUTER_H_
+#define CORE_INTERNAL_SERVICE_CONTROLLER_ROUTER_H_
+
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "absl/container/flat_hash_set.h"
+#include "absl/strings/string_view.h"
+#include "absl/types/span.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/service_controller.h"
+#include "connections/params.h"
+#include "internal/platform/runnable.h"
+#include "internal/platform/single_thread_executor.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// ServiceControllerRouter: this class is an implementation detail of a
+// location::nearby::Core class. The latter delegates all of its activities to
+// the former.
+//
+// All the activities are documented in the public API class:
+// cpp/core_v2/core.h
+//
+// In every method, ClientProxy* represents the client app which receives
+// notifications from Nearby Connections service and forwards them to the app.
+// The rest of arguments have the same meaning as the corresponding
+// methods in the definition of location::nearby::Core API.
+//
+// Every activity is handled the same way:
+// 1) all the arguments to the call are captured by value;
+// 2) the actual processing is scheduled on a private single-threaded executor,
+// which makes locking unnecessary, when internal data is being manipulated.
+// 3) activity handlers are delegating much of their work to an implementation
+// of a ServiceController interface, which does the actual job.
+class ServiceControllerRouter {
+ public:
+ ServiceControllerRouter();
+ virtual ~ServiceControllerRouter();
+ // Not copyable or movable
+ ServiceControllerRouter(const ServiceControllerRouter&) = delete;
+ ServiceControllerRouter& operator=(const ServiceControllerRouter&) = delete;
+ ServiceControllerRouter(ServiceControllerRouter&&) = delete;
+ ServiceControllerRouter& operator=(ServiceControllerRouter&&) = delete;
+
+ virtual void StartAdvertising(ClientProxy* client,
+ absl::string_view service_id,
+ const AdvertisingOptions& advertising_options,
+ const ConnectionRequestInfo& info,
+ const ResultCallback& callback);
+ virtual void StopAdvertising(ClientProxy* client,
+ const ResultCallback& callback);
+
+ virtual void StartDiscovery(ClientProxy* client, absl::string_view service_id,
+ const DiscoveryOptions& discovery_options,
+ const DiscoveryListener& listener,
+ const ResultCallback& callback);
+ virtual void StopDiscovery(ClientProxy* client,
+ const ResultCallback& callback);
+
+ virtual void InjectEndpoint(ClientProxy* client, absl::string_view service_id,
+ const OutOfBandConnectionMetadata& metadata,
+ const ResultCallback& callback);
+
+ virtual void RequestConnection(ClientProxy* client,
+ absl::string_view endpoint_id,
+ const ConnectionRequestInfo& info,
+ const ConnectionOptions& connection_options,
+ const ResultCallback& callback);
+ virtual void AcceptConnection(ClientProxy* client,
+ absl::string_view endpoint_id,
+ const PayloadListener& listener,
+ const ResultCallback& callback);
+ virtual void RejectConnection(ClientProxy* client,
+ absl::string_view endpoint_id,
+ const ResultCallback& callback);
+
+ virtual void InitiateBandwidthUpgrade(ClientProxy* client,
+ absl::string_view endpoint_id,
+ const ResultCallback& callback);
+
+ virtual void SendPayload(ClientProxy* client,
+ absl::Span<const std::string> endpoint_ids,
+ Payload payload, const ResultCallback& callback);
+ virtual void CancelPayload(ClientProxy* client, std::uint64_t payload_id,
+ const ResultCallback& callback);
+
+ virtual void DisconnectFromEndpoint(ClientProxy* client,
+ absl::string_view endpoint_id,
+ const ResultCallback& callback);
+ virtual void StopAllEndpoints(ClientProxy* client,
+ const ResultCallback& callback);
+
+ void SetServiceControllerForTesting(
+ std::unique_ptr<ServiceController> service_controller);
+
+ private:
+ // Lazily create ServiceController.
+ ServiceController* GetServiceController();
+
+ void RouteToServiceController(const std::string& name, Runnable runnable);
+ void FinishClientSession(ClientProxy* client);
+
+ std::unique_ptr<ServiceController> service_controller_;
+ SingleThreadExecutor serializer_;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_SERVICE_CONTROLLER_ROUTER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/service_controller_router_test.cc b/chromium/third_party/nearby/src/connections/implementation/service_controller_router_test.cc
new file mode 100644
index 00000000000..8b5ce78b5a8
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/service_controller_router_test.cc
@@ -0,0 +1,450 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/service_controller_router.h"
+
+#include <array>
+#include <cinttypes>
+#include <memory>
+#include <string>
+#include <utility>
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "absl/container/flat_hash_set.h"
+#include "absl/time/clock.h"
+#include "absl/types/span.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/mock_service_controller.h"
+#include "connections/implementation/service_controller.h"
+#include "connections/listeners.h"
+#include "connections/params.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/condition_variable.h"
+#include "internal/platform/mutex.h"
+#include "internal/platform/mutex_lock.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Feature On/Off switch for mediums.
+using BooleanMediumSelector = MediumSelector<bool>;
+
+namespace {
+using ::testing::Return;
+constexpr std::array<char, 6> kFakeMacAddress = {'a', 'b', 'c', 'd', 'e', 'f'};
+constexpr std::array<char, 6> kFakeInjectedEndpointInfo = {'g', 'h', 'i'};
+const char kFakeInejctedEndpointId[] = "abcd";
+} // namespace
+
+// This class must be in the same namespace as ServiceControllerRouter for
+// friend class to work.
+class ServiceControllerRouterTest : public testing::Test {
+ public:
+ void SetUp() override {
+ auto mock = std::make_unique<MockServiceController>();
+ mock_ = mock.get();
+ router_.SetServiceControllerForTesting(std::move(mock));
+ }
+
+ void StartAdvertising(ClientProxy* client, std::string service_id,
+ AdvertisingOptions advertising_options,
+ ConnectionRequestInfo info, ResultCallback callback) {
+ EXPECT_CALL(*mock_, StartAdvertising)
+ .WillOnce(Return(Status{Status::kSuccess}));
+ {
+ MutexLock lock(&mutex_);
+ complete_ = false;
+ router_.StartAdvertising(client, service_id, advertising_options, info,
+ callback);
+ while (!complete_) cond_.Wait();
+ EXPECT_EQ(result_, Status{Status::kSuccess});
+ }
+ client->StartedAdvertising(kServiceId, advertising_options.strategy,
+ info.listener, absl::MakeSpan(mediums_));
+ EXPECT_TRUE(client->IsAdvertising());
+ }
+
+ void StopAdvertising(ClientProxy* client, ResultCallback callback) {
+ EXPECT_CALL(*mock_, StopAdvertising).Times(1);
+ {
+ MutexLock lock(&mutex_);
+ complete_ = false;
+ router_.StopAdvertising(client, callback);
+ while (!complete_) cond_.Wait();
+ }
+ client->StoppedAdvertising();
+ EXPECT_FALSE(client->IsAdvertising());
+ }
+
+ void StartDiscovery(ClientProxy* client, std::string service_id,
+ DiscoveryOptions discovery_options,
+ const DiscoveryListener& listener,
+ const ResultCallback& callback) {
+ EXPECT_CALL(*mock_, StartDiscovery)
+ .WillOnce(Return(Status{Status::kSuccess}));
+ {
+ MutexLock lock(&mutex_);
+ complete_ = false;
+ router_.StartDiscovery(client, kServiceId, discovery_options, listener,
+ callback);
+ while (!complete_) cond_.Wait();
+ EXPECT_EQ(result_, Status{Status::kSuccess});
+ }
+ client->StartedDiscovery(service_id, discovery_options.strategy, listener,
+ absl::MakeSpan(mediums_));
+ EXPECT_TRUE(client->IsDiscovering());
+ }
+
+ void StopDiscovery(ClientProxy* client, ResultCallback callback) {
+ EXPECT_CALL(*mock_, StopDiscovery).Times(1);
+ {
+ MutexLock lock(&mutex_);
+ complete_ = false;
+ router_.StopDiscovery(client, callback);
+ while (!complete_) cond_.Wait();
+ }
+ client->StoppedDiscovery();
+ EXPECT_FALSE(client->IsDiscovering());
+ }
+
+ void InjectEndpoint(ClientProxy* client, std::string service_id,
+ const OutOfBandConnectionMetadata& metadata,
+ ResultCallback callback) {
+ EXPECT_CALL(*mock_, InjectEndpoint).Times(1);
+ {
+ MutexLock lock(&mutex_);
+ complete_ = false;
+ router_.InjectEndpoint(client, service_id, metadata, callback);
+ while (!complete_) cond_.Wait();
+ }
+ }
+
+ void RequestConnection(ClientProxy* client, const std::string& endpoint_id,
+ const ConnectionRequestInfo& request_info,
+ ResultCallback callback) {
+ EXPECT_CALL(*mock_, RequestConnection)
+ .WillOnce(Return(Status{Status::kSuccess}));
+ ConnectionOptions connection_options;
+ {
+ MutexLock lock(&mutex_);
+ complete_ = false;
+ router_.RequestConnection(client, endpoint_id, request_info,
+ connection_options, callback);
+ while (!complete_) cond_.Wait();
+ EXPECT_EQ(result_, Status{Status::kSuccess});
+ }
+ ConnectionResponseInfo response_info{
+ .remote_endpoint_info = ByteArray{"endpoint_name"},
+ .authentication_token = "auth_token",
+ .raw_authentication_token = ByteArray{"auth_token"},
+ .is_incoming_connection = true,
+ };
+ std::string connection_token{"conntokn"};
+ client->OnConnectionInitiated(endpoint_id, response_info,
+ connection_options, request_info.listener,
+ connection_token);
+ EXPECT_TRUE(client->HasPendingConnectionToEndpoint(endpoint_id));
+ }
+
+ void AcceptConnection(ClientProxy* client, const std::string endpoint_id,
+ const PayloadListener& listener,
+ const ResultCallback& callback) {
+ EXPECT_CALL(*mock_, AcceptConnection)
+ .WillOnce(Return(Status{Status::kSuccess}));
+ // Pre-condition for successful Accept is: connection must exist.
+ EXPECT_TRUE(client->HasPendingConnectionToEndpoint(endpoint_id));
+ {
+ MutexLock lock(&mutex_);
+ complete_ = false;
+ router_.AcceptConnection(client, endpoint_id, listener, callback);
+ while (!complete_) cond_.Wait();
+ EXPECT_EQ(result_, Status{Status::kSuccess});
+ }
+ client->LocalEndpointAcceptedConnection(endpoint_id, listener);
+ client->RemoteEndpointAcceptedConnection(endpoint_id);
+ EXPECT_TRUE(client->IsConnectionAccepted(endpoint_id));
+ client->OnConnectionAccepted(endpoint_id);
+ EXPECT_TRUE(client->IsConnectedToEndpoint(endpoint_id));
+ }
+
+ void RejectConnection(ClientProxy* client, const std::string endpoint_id,
+ ResultCallback callback) {
+ EXPECT_CALL(*mock_, RejectConnection)
+ .WillOnce(Return(Status{Status::kSuccess}));
+ // Pre-condition for successful Accept is: connection must exist.
+ EXPECT_TRUE(client->HasPendingConnectionToEndpoint(endpoint_id));
+ {
+ MutexLock lock(&mutex_);
+ complete_ = false;
+ router_.RejectConnection(client, endpoint_id, callback);
+ while (!complete_) cond_.Wait();
+ EXPECT_EQ(result_, Status{Status::kSuccess});
+ }
+ client->LocalEndpointRejectedConnection(endpoint_id);
+ EXPECT_TRUE(client->IsConnectionRejected(endpoint_id));
+ }
+
+ void InitiateBandwidthUpgrade(ClientProxy* client,
+ const std::string endpoint_id,
+ ResultCallback callback) {
+ EXPECT_CALL(*mock_, InitiateBandwidthUpgrade).Times(1);
+ EXPECT_TRUE(client->IsConnectedToEndpoint(endpoint_id));
+ {
+ MutexLock lock(&mutex_);
+ complete_ = false;
+ router_.InitiateBandwidthUpgrade(client, endpoint_id, callback);
+ while (!complete_) cond_.Wait();
+ EXPECT_EQ(result_, Status{Status::kSuccess});
+ }
+ }
+
+ void SendPayload(ClientProxy* client,
+ const std::vector<std::string>& endpoint_ids,
+ Payload payload, ResultCallback callback) {
+ EXPECT_CALL(*mock_, SendPayload).Times(1);
+
+ bool connected = false;
+ for (const auto& endpoint_id : endpoint_ids) {
+ connected = connected || client->IsConnectedToEndpoint(endpoint_id);
+ }
+ EXPECT_TRUE(connected);
+ {
+ MutexLock lock(&mutex_);
+ complete_ = false;
+ router_.SendPayload(client, absl::MakeSpan(endpoint_ids),
+ std::move(payload), callback);
+ while (!complete_) cond_.Wait();
+ EXPECT_EQ(result_, Status{Status::kSuccess});
+ }
+ }
+
+ void CancelPayload(ClientProxy* client, std::int64_t payload_id,
+ ResultCallback callback) {
+ EXPECT_CALL(*mock_, CancelPayload)
+ .WillOnce(Return(Status{Status::kSuccess}));
+ {
+ MutexLock lock(&mutex_);
+ complete_ = false;
+ router_.CancelPayload(client, payload_id, callback);
+ while (!complete_) cond_.Wait();
+ EXPECT_EQ(result_, Status{Status::kSuccess});
+ }
+ }
+
+ void DisconnectFromEndpoint(ClientProxy* client,
+ const std::string endpoint_id,
+ ResultCallback callback) {
+ EXPECT_CALL(*mock_, DisconnectFromEndpoint).Times(1);
+ EXPECT_TRUE(client->IsConnectedToEndpoint(endpoint_id));
+ {
+ MutexLock lock(&mutex_);
+ complete_ = false;
+ router_.DisconnectFromEndpoint(client, endpoint_id, callback);
+ while (!complete_) cond_.Wait();
+ }
+ client->OnDisconnected(endpoint_id, false);
+ EXPECT_FALSE(client->IsConnectedToEndpoint(endpoint_id));
+ }
+
+ protected:
+ const ResultCallback kCallback{
+ .result_cb =
+ [this](Status status) {
+ MutexLock lock(&mutex_);
+ result_ = status;
+ complete_ = true;
+ cond_.Notify();
+ },
+ };
+ const std::string kServiceId = "service id";
+ const std::string kRequestorName = "requestor name";
+ const std::string kRemoteEndpointId = "remote endpoint id";
+ const std::int64_t kPayloadId = UINT64_C(0x123456789ABCDEF0);
+ const ConnectionOptions kConnectionOptions{
+ {
+ Strategy::kP2pPointToPoint,
+ BooleanMediumSelector(),
+ },
+ true,
+ true,
+ };
+ const AdvertisingOptions kAdvertisingOptions{
+ {
+ Strategy::kP2pPointToPoint,
+ BooleanMediumSelector(),
+ },
+ true, // auto_upgrade_bandwidth
+ true, // enforce_topology_constraints
+ false, // low_power
+ false, // enable_bluetooth_listening
+ false, // enable_webrtc_listening
+ };
+ const DiscoveryOptions kDiscoveryOptions{
+ {
+ Strategy::kP2pPointToPoint,
+ BooleanMediumSelector(),
+ },
+ true,
+ true,
+ };
+
+ const OutOfBandConnectionMetadata kOutOfBandConnectionMetadata{
+ .medium = Medium::BLUETOOTH,
+ .endpoint_id = kFakeInejctedEndpointId,
+ .endpoint_info = ByteArray(kFakeInjectedEndpointInfo),
+ .remote_bluetooth_mac_address = ByteArray(kFakeMacAddress),
+ };
+
+ std::vector<proto::connections::Medium> mediums_{
+ proto::connections::Medium::BLUETOOTH};
+ const ConnectionRequestInfo kConnectionRequestInfo{
+ .endpoint_info = ByteArray{kRequestorName},
+ .listener = ConnectionListener(),
+ };
+
+ DiscoveryListener discovery_listener_;
+ PayloadListener payload_listener_;
+
+ Mutex mutex_;
+ ConditionVariable cond_{&mutex_};
+ Status result_ ABSL_GUARDED_BY(mutex_) = {Status::kError};
+ bool complete_ ABSL_GUARDED_BY(mutex_) = false;
+ MockServiceController* mock_;
+ ClientProxy client_;
+
+ ServiceControllerRouter router_;
+};
+
+namespace {
+TEST_F(ServiceControllerRouterTest, StartAdvertisingCalled) {
+ StartAdvertising(&client_, kServiceId, kAdvertisingOptions,
+ kConnectionRequestInfo, kCallback);
+}
+
+TEST_F(ServiceControllerRouterTest, StopAdvertisingCalled) {
+ StartAdvertising(&client_, kServiceId, kAdvertisingOptions,
+ kConnectionRequestInfo, kCallback);
+ StopAdvertising(&client_, kCallback);
+}
+
+TEST_F(ServiceControllerRouterTest, StartDiscoveryCalled) {
+ StartDiscovery(&client_, kServiceId, kDiscoveryOptions, discovery_listener_,
+ kCallback);
+}
+
+TEST_F(ServiceControllerRouterTest, StopDiscoveryCalled) {
+ StartDiscovery(&client_, kServiceId, kDiscoveryOptions, discovery_listener_,
+ kCallback);
+ StopDiscovery(&client_, kCallback);
+}
+
+TEST_F(ServiceControllerRouterTest, InjectEndpointCalled) {
+ StartDiscovery(&client_, kServiceId, kDiscoveryOptions, discovery_listener_,
+ kCallback);
+ InjectEndpoint(&client_, kServiceId, kOutOfBandConnectionMetadata, kCallback);
+ StopDiscovery(&client_, kCallback);
+}
+
+TEST_F(ServiceControllerRouterTest, RequestConnectionCalled) {
+ // Either Advertising, or Discovery should be ongoing.
+ StartDiscovery(&client_, kServiceId, kDiscoveryOptions, discovery_listener_,
+ kCallback);
+ RequestConnection(&client_, kRemoteEndpointId, kConnectionRequestInfo,
+ kCallback);
+}
+
+TEST_F(ServiceControllerRouterTest, AcceptConnectionCalled) {
+ // Either Adviertisng, or Discovery should be ongoing.
+ StartDiscovery(&client_, kServiceId, kDiscoveryOptions, discovery_listener_,
+ kCallback);
+ // Establish connection.
+ RequestConnection(&client_, kRemoteEndpointId, kConnectionRequestInfo,
+ kCallback);
+ // Now, we can accept connection.
+ AcceptConnection(&client_, kRemoteEndpointId, payload_listener_, kCallback);
+}
+
+TEST_F(ServiceControllerRouterTest, RejectConnectionCalled) {
+ // Either Adviertisng, or Discovery should be ongoing.
+ StartDiscovery(&client_, kServiceId, kDiscoveryOptions, discovery_listener_,
+ kCallback);
+ // Establish connection.
+ RequestConnection(&client_, kRemoteEndpointId, kConnectionRequestInfo,
+ kCallback);
+ // Now, we can reject connection.
+ RejectConnection(&client_, kRemoteEndpointId, kCallback);
+}
+
+TEST_F(ServiceControllerRouterTest, InitiateBandwidthUpgradeCalled) {
+ // Either Adviertisng, or Discovery should be ongoing.
+ StartDiscovery(&client_, kServiceId, kDiscoveryOptions, discovery_listener_,
+ kCallback);
+ // Establish connection.
+ RequestConnection(&client_, kRemoteEndpointId, kConnectionRequestInfo,
+ kCallback);
+ // Now, we can accept connection.
+ AcceptConnection(&client_, kRemoteEndpointId, payload_listener_, kCallback);
+ // Now we can change connection bandwidth.
+ InitiateBandwidthUpgrade(&client_, kRemoteEndpointId, kCallback);
+}
+
+TEST_F(ServiceControllerRouterTest, SendPayloadCalled) {
+ // Either Adviertisng, or Discovery should be ongoing.
+ StartDiscovery(&client_, kServiceId, kDiscoveryOptions, discovery_listener_,
+ kCallback);
+ // Establish connection.
+ RequestConnection(&client_, kRemoteEndpointId, kConnectionRequestInfo,
+ kCallback);
+ // Now, we can accept connection.
+ AcceptConnection(&client_, kRemoteEndpointId, payload_listener_, kCallback);
+ // Now we can send payload.
+ SendPayload(&client_, std::vector<std::string>{kRemoteEndpointId},
+ Payload{ByteArray("data")}, kCallback);
+}
+
+TEST_F(ServiceControllerRouterTest, CancelPayloadCalled) {
+ // Either Adviertisng, or Discovery should be ongoing.
+ StartDiscovery(&client_, kServiceId, kDiscoveryOptions, discovery_listener_,
+ kCallback);
+ // Establish connection.
+ RequestConnection(&client_, kRemoteEndpointId, kConnectionRequestInfo,
+ kCallback);
+ // Now, we can accept connection.
+ AcceptConnection(&client_, kRemoteEndpointId, payload_listener_, kCallback);
+ // We have to know payload id, before we can cancel payload transfer.
+ // It is either after a call to SendPayload, or after receiving
+ // PayloadProgress callback. Let's assume we have it, and proceed.
+ CancelPayload(&client_, kPayloadId, kCallback);
+}
+
+TEST_F(ServiceControllerRouterTest, DisconnectFromEndpointCalled) {
+ // Either Adviertisng, or Discovery should be ongoing.
+ StartDiscovery(&client_, kServiceId, kDiscoveryOptions, discovery_listener_,
+ kCallback);
+ // Establish connection.
+ RequestConnection(&client_, kRemoteEndpointId, kConnectionRequestInfo,
+ kCallback);
+ // Now, we can accept connection.
+ AcceptConnection(&client_, kRemoteEndpointId, payload_listener_, kCallback);
+ // We can disconnect at any time after RequestConnection.
+ DisconnectFromEndpoint(&client_, kRemoteEndpointId, kCallback);
+}
+
+} // namespace
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/simulation_user.cc b/chromium/third_party/nearby/src/connections/implementation/simulation_user.cc
new file mode 100644
index 00000000000..01cd11f7222
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/simulation_user.cc
@@ -0,0 +1,181 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/simulation_user.h"
+
+#include "absl/functional/bind_front.h"
+#include "connections/listeners.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/system_clock.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+void SimulationUser::OnConnectionInitiated(const std::string& endpoint_id,
+ const ConnectionResponseInfo& info,
+ bool is_outgoing) {
+ if (is_outgoing) {
+ NEARBY_LOG(INFO, "RequestConnection: initiated_cb called");
+ } else {
+ NEARBY_LOG(INFO, "StartAdvertising: initiated_cb called");
+ discovered_ = DiscoveredInfo{
+ .endpoint_id = endpoint_id,
+ .endpoint_info = GetInfo(),
+ .service_id = service_id_,
+ };
+ }
+ if (initiated_latch_) initiated_latch_->CountDown();
+}
+
+void SimulationUser::OnConnectionAccepted(const std::string& endpoint_id) {
+ if (accept_latch_) accept_latch_->CountDown();
+}
+
+void SimulationUser::OnConnectionRejected(const std::string& endpoint_id,
+ Status status) {
+ if (reject_latch_) reject_latch_->CountDown();
+}
+
+void SimulationUser::OnEndpointFound(const std::string& endpoint_id,
+ const ByteArray& endpoint_info,
+ const std::string& service_id) {
+ NEARBY_LOG(INFO, "Device discovered: id=%s", endpoint_id.c_str());
+ discovered_ = DiscoveredInfo{
+ .endpoint_id = endpoint_id,
+ .endpoint_info = endpoint_info,
+ .service_id = service_id,
+ };
+ if (found_latch_) found_latch_->CountDown();
+}
+
+void SimulationUser::OnEndpointLost(const std::string& endpoint_id) {
+ if (lost_latch_) lost_latch_->CountDown();
+}
+
+void SimulationUser::OnPayload(const std::string& endpoint_id,
+ Payload payload) {
+ payload_ = std::move(payload);
+ if (payload_latch_) payload_latch_->CountDown();
+}
+
+void SimulationUser::OnPayloadProgress(const std::string& endpoint_id,
+ const PayloadProgressInfo& info) {
+ MutexLock lock(&progress_mutex_);
+ progress_info_ = info;
+ if (future_ && predicate_ && predicate_(info)) future_->Set(true);
+}
+
+bool SimulationUser::WaitForProgress(
+ std::function<bool(const PayloadProgressInfo&)> predicate,
+ absl::Duration timeout) {
+ Future<bool> future;
+ {
+ MutexLock lock(&progress_mutex_);
+ if (predicate(progress_info_)) return true;
+ future_ = &future;
+ predicate_ = std::move(predicate);
+ }
+ auto response = future.Get(timeout);
+ {
+ MutexLock lock(&progress_mutex_);
+ future_ = nullptr;
+ predicate_ = nullptr;
+ }
+ return response.ok() && response.result();
+}
+
+void SimulationUser::StartAdvertising(const std::string& service_id,
+ CountDownLatch* latch) {
+ initiated_latch_ = latch;
+ service_id_ = service_id;
+ ConnectionListener listener = {
+ .initiated_cb =
+ std::bind(&SimulationUser::OnConnectionInitiated, this,
+ std::placeholders::_1, std::placeholders::_2, false),
+ .accepted_cb =
+ absl::bind_front(&SimulationUser::OnConnectionAccepted, this),
+ .rejected_cb =
+ absl::bind_front(&SimulationUser::OnConnectionRejected, this),
+ };
+ EXPECT_TRUE(mgr_.StartAdvertising(&client_, service_id_, advertising_options_,
+ {
+ .endpoint_info = info_,
+ .listener = std::move(listener),
+ })
+ .Ok());
+}
+
+void SimulationUser::StartDiscovery(const std::string& service_id,
+ CountDownLatch* latch) {
+ found_latch_ = latch;
+ EXPECT_TRUE(
+ mgr_.StartDiscovery(&client_, service_id, discovery_options_,
+ {
+ .endpoint_found_cb = absl::bind_front(
+ &SimulationUser::OnEndpointFound, this),
+ .endpoint_lost_cb = absl::bind_front(
+ &SimulationUser::OnEndpointLost, this),
+ })
+ .Ok());
+}
+
+void SimulationUser::InjectEndpoint(
+ const std::string& service_id,
+ const OutOfBandConnectionMetadata& metadata) {
+ mgr_.InjectEndpoint(&client_, service_id, metadata);
+}
+
+void SimulationUser::RequestConnection(CountDownLatch* latch) {
+ initiated_latch_ = latch;
+ ConnectionListener listener = {
+ .initiated_cb =
+ std::bind(&SimulationUser::OnConnectionInitiated, this,
+ std::placeholders::_1, std::placeholders::_2, true),
+ .accepted_cb =
+ absl::bind_front(&SimulationUser::OnConnectionAccepted, this),
+ .rejected_cb =
+ absl::bind_front(&SimulationUser::OnConnectionRejected, this),
+ };
+ client_.AddCancellationFlag(discovered_.endpoint_id);
+ EXPECT_TRUE(
+ mgr_.RequestConnection(&client_, discovered_.endpoint_id,
+ {
+ .endpoint_info = discovered_.endpoint_info,
+ .listener = std::move(listener),
+ },
+ connection_options_)
+ .Ok());
+}
+
+void SimulationUser::AcceptConnection(CountDownLatch* latch) {
+ accept_latch_ = latch;
+ PayloadListener listener = {
+ .payload_cb = absl::bind_front(&SimulationUser::OnPayload, this),
+ .payload_progress_cb =
+ absl::bind_front(&SimulationUser::OnPayloadProgress, this),
+ };
+ EXPECT_TRUE(mgr_.AcceptConnection(&client_, discovered_.endpoint_id,
+ std::move(listener))
+ .Ok());
+}
+
+void SimulationUser::RejectConnection(CountDownLatch* latch) {
+ reject_latch_ = latch;
+ EXPECT_TRUE(mgr_.RejectConnection(&client_, discovered_.endpoint_id).Ok());
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/simulation_user.h b/chromium/third_party/nearby/src/connections/implementation/simulation_user.h
new file mode 100644
index 00000000000..03ba0c81f43
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/simulation_user.h
@@ -0,0 +1,180 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_SIMULATION_USER_H_
+#define CORE_INTERNAL_SIMULATION_USER_H_
+
+#include <string>
+
+#include "gtest/gtest.h"
+#include "connections/implementation/bwu_manager.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/endpoint_channel_manager.h"
+#include "connections/implementation/endpoint_manager.h"
+#include "connections/implementation/injected_bluetooth_device_store.h"
+#include "connections/implementation/payload_manager.h"
+#include "connections/implementation/pcp_manager.h"
+#include "internal/platform/medium_environment.h"
+#include "internal/platform/condition_variable.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/future.h"
+
+// Test-only class to help run end-to-end simulations for nearby connections
+// protocol.
+//
+// This is a "standalone" version of PcpManager. It can run independently,
+// provided MediumEnvironment has adequate support for all medium types in use.
+namespace location {
+namespace nearby {
+namespace connections {
+
+class SimulationUser {
+ public:
+ struct DiscoveredInfo {
+ std::string endpoint_id;
+ ByteArray endpoint_info;
+ std::string service_id;
+
+ bool Empty() const { return endpoint_id.empty(); }
+ void Clear() { endpoint_id.clear(); }
+ };
+
+ explicit SimulationUser(
+ const std::string& device_name,
+ BooleanMediumSelector allowed = BooleanMediumSelector())
+ : info_{ByteArray{device_name}},
+ advertising_options_{
+ {
+ Strategy::kP2pCluster,
+ allowed,
+ },
+ },
+ connection_options_{
+ .keep_alive_interval_millis = FeatureFlags::GetInstance()
+ .GetFlags()
+ .keep_alive_interval_millis,
+ .keep_alive_timeout_millis = FeatureFlags::GetInstance()
+ .GetFlags()
+ .keep_alive_timeout_millis,
+ },
+ discovery_options_{
+ {
+ Strategy::kP2pCluster,
+ allowed,
+ },
+ } {}
+ virtual ~SimulationUser() { Stop(); }
+ void Stop() {
+ pm_.DisconnectFromEndpointManager();
+ mgr_.DisconnectFromEndpointManager();
+ bwu_.Shutdown();
+ }
+
+ // Calls PcpManager::StartAdvertising.
+ // If latch is provided, will call latch->CountDown() in the initiated_cb
+ // callback.
+ void StartAdvertising(const std::string& service_id, CountDownLatch* latch);
+
+ // Calls PcpManager::StartDiscovery.
+ // If latch is provided, will call latch->CountDown() in the endpoint_found_cb
+ // callback.
+ void StartDiscovery(const std::string& service_id, CountDownLatch* latch);
+
+ // Calls PcpManager::InjectEndpoint.
+ void InjectEndpoint(const std::string& service_id,
+ const OutOfBandConnectionMetadata& metadata);
+
+ // Calls PcpManager::RequestConnection.
+ // If latch is provided, latch->CountDown() will be called in the initiated_cb
+ // callback.
+ void RequestConnection(CountDownLatch* latch);
+
+ // Calls PcpManager::AcceptConnection.
+ // If latch is provided, latch->CountDown() will be called in the accepted_cb
+ // callback.
+ void AcceptConnection(CountDownLatch* latch);
+
+ // Calls PcpManager::RejectConnection.
+ // If latch is provided, latch->CountDown() will be called in the rejected_cb
+ // callback.
+ void RejectConnection(CountDownLatch* latch);
+
+ // Unlike acceptance, rejection does not have to be mutual, in order to work.
+ // This method will allow to synchronize on the remote rejection, without
+ // performing a local rejection.
+ // latch.CountDown() will be called in the rejected_cb callback.
+ void ExpectRejectedConnection(CountDownLatch& latch) {
+ reject_latch_ = &latch;
+ }
+
+ void ExpectPayload(CountDownLatch& latch) { payload_latch_ = &latch; }
+
+ const DiscoveredInfo& GetDiscovered() const { return discovered_; }
+ ByteArray GetInfo() const { return info_; }
+
+ bool WaitForProgress(std::function<bool(const PayloadProgressInfo&)> pred,
+ absl::Duration timeout);
+
+ protected:
+ // ConnectionListener callbacks
+ void OnConnectionInitiated(const std::string& endpoint_id,
+ const ConnectionResponseInfo& info,
+ bool is_outgoing);
+ void OnConnectionAccepted(const std::string& endpoint_id);
+ void OnConnectionRejected(const std::string& endpoint_id, Status status);
+
+ // DiscoveryListener callbacks
+ void OnEndpointFound(const std::string& endpoint_id,
+ const ByteArray& endpoint_info,
+ const std::string& service_id);
+ void OnEndpointLost(const std::string& endpoint_id);
+
+ // PayloadListener callbacks
+ void OnPayload(const std::string& endpoint_id, Payload payload);
+ void OnPayloadProgress(const std::string& endpoint_id,
+ const PayloadProgressInfo& info);
+
+ std::string service_id_;
+ DiscoveredInfo discovered_;
+ Mutex progress_mutex_;
+ ConditionVariable progress_sync_{&progress_mutex_};
+ PayloadProgressInfo progress_info_;
+ Payload payload_;
+ CountDownLatch* initiated_latch_ = nullptr;
+ CountDownLatch* accept_latch_ = nullptr;
+ CountDownLatch* reject_latch_ = nullptr;
+ CountDownLatch* found_latch_ = nullptr;
+ CountDownLatch* lost_latch_ = nullptr;
+ CountDownLatch* payload_latch_ = nullptr;
+ Future<bool>* future_ = nullptr;
+ std::function<bool(const PayloadProgressInfo&)> predicate_;
+ ByteArray info_;
+ Mediums mediums_;
+ AdvertisingOptions advertising_options_;
+ ConnectionOptions connection_options_;
+ DiscoveryOptions discovery_options_;
+ ClientProxy client_;
+ EndpointChannelManager ecm_;
+ EndpointManager em_{&ecm_};
+ BwuManager bwu_{mediums_, em_, ecm_, {}, {}};
+ InjectedBluetoothDeviceStore injected_bluetooth_device_store_;
+ PcpManager mgr_{mediums_, ecm_, em_, bwu_, injected_bluetooth_device_store_};
+ PayloadManager pm_{em_};
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_SIMULATION_USER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/webrtc_bwu_handler.cc b/chromium/third_party/nearby/src/connections/implementation/webrtc_bwu_handler.cc
new file mode 100644
index 00000000000..a1d0732410c
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/webrtc_bwu_handler.cc
@@ -0,0 +1,166 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/webrtc_bwu_handler.h"
+
+#include <string>
+
+#include "absl/functional/bind_front.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/mediums/utils.h"
+#include "connections/implementation/mediums/webrtc_peer_id.h"
+#include "connections/implementation/offline_frames.h"
+#include "connections/implementation/webrtc_endpoint_channel.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+WebrtcBwuHandler::WebrtcBwuHandler(Mediums& mediums,
+ EndpointChannelManager& channel_manager,
+ BwuNotifications notifications)
+ : BaseBwuHandler(channel_manager, std::move(notifications)),
+ mediums_(mediums) {}
+
+void WebrtcBwuHandler::Revert() {
+ for (const auto& service_id : active_service_ids_) {
+ webrtc_.StopAcceptingConnections(service_id);
+ }
+ active_service_ids_.clear();
+
+ NEARBY_LOG(INFO, "WebrtcBwuHandler successfully reverted state.");
+}
+
+// Accept Connection Callback.
+// Notifies that the remote party called WebRtc::Connect()
+// for this socket.
+void WebrtcBwuHandler::OnIncomingWebrtcConnection(
+ ClientProxy* client, const std::string& upgrade_service_id,
+ mediums::WebRtcSocketWrapper socket) {
+ std::string service_id = Utils::UnwrapUpgradeServiceId(upgrade_service_id);
+ auto channel = std::make_unique<WebRtcEndpointChannel>(service_id, socket);
+ auto webrtc_socket =
+ std::make_unique<WebrtcIncomingSocket>(service_id, socket);
+ std::unique_ptr<IncomingSocketConnection> connection(
+ new IncomingSocketConnection{std::move(webrtc_socket),
+ std::move(channel)});
+
+ bwu_notifications_.incoming_connection_cb(client, std::move(connection));
+}
+
+// Called by BWU initiator. Set up WebRTC upgraded medium for this endpoint,
+// and returns a upgrade path info (PeerId, LocationHint) for remote party to
+// perform discovery.
+ByteArray WebrtcBwuHandler::InitializeUpgradedMediumForEndpoint(
+ ClientProxy* client, const std::string& service_id,
+ const std::string& endpoint_id) {
+ // Use wrapped service ID to avoid have the same ID with the one for
+ // startAdvertising. Otherwise, the listening request would be ignored because
+ // the medium already start accepting the connection because the client not
+ // stop the advertising yet.
+ std::string upgrade_service_id = Utils::WrapUpgradeServiceId(service_id);
+
+ LocationHint location_hint =
+ Utils::BuildLocationHint(webrtc_.GetDefaultCountryCode());
+
+ mediums::WebrtcPeerId self_id{mediums::WebrtcPeerId::FromRandom()};
+ if (!webrtc_.IsAcceptingConnections(service_id)) {
+ if (!webrtc_.StartAcceptingConnections(
+ upgrade_service_id, self_id, location_hint,
+ {
+ .accepted_cb = absl::bind_front(
+ &WebrtcBwuHandler::OnIncomingWebrtcConnection, this, client,
+ upgrade_service_id),
+ })) {
+ NEARBY_LOG(ERROR,
+ "WebRtcBwuHandler couldn't initiate the WEB_RTC upgrade for "
+ "endpoint %s because it failed to start listening for "
+ "incoming WebRTC connections.",
+ endpoint_id.c_str());
+ return {};
+ }
+ NEARBY_LOG(INFO,
+ "WebRtcBwuHandler successfully started listening for incoming "
+ "WebRTC connections while upgrading endpoint %s",
+ endpoint_id.c_str());
+ }
+
+ // cache service ID to revert
+ active_service_ids_.emplace(upgrade_service_id);
+
+ return parser::ForBwuWebrtcPathAvailable(self_id.GetId(), location_hint);
+}
+
+// Called by BWU target. Retrieves a new medium info from incoming message,
+// and establishes connection over WebRTC using this info.
+std::unique_ptr<EndpointChannel>
+WebrtcBwuHandler::CreateUpgradedEndpointChannel(
+ ClientProxy* client, const std::string& service_id,
+ const std::string& endpoint_id, const UpgradePathInfo& upgrade_path_info) {
+ const UpgradePathInfo::WebRtcCredentials& web_rtc_credentials =
+ upgrade_path_info.web_rtc_credentials();
+ mediums::WebrtcPeerId peer_id(web_rtc_credentials.peer_id());
+
+ LocationHint location_hint;
+ location_hint.set_format(LocationStandard::UNKNOWN);
+ if (web_rtc_credentials.has_location_hint()) {
+ location_hint = web_rtc_credentials.location_hint();
+ }
+ NEARBY_LOG(INFO,
+ "WebRtcBwuHandler is attempting to connect to remote peer %s, "
+ "location hint %s",
+ peer_id.GetId().c_str(), location_hint.DebugString().c_str());
+
+ mediums::WebRtcSocketWrapper socket =
+ webrtc_.Connect(service_id, peer_id, location_hint,
+ client->GetCancellationFlag(endpoint_id));
+ if (!socket.IsValid()) {
+ NEARBY_LOG(ERROR,
+ "WebRtcBwuHandler failed to connect to remote peer (%s) on "
+ "endpoint %s, aborting upgrade.",
+ peer_id.GetId().c_str(), endpoint_id.c_str());
+ return nullptr;
+ }
+
+ NEARBY_LOG(INFO,
+ "WebRtcBwuHandler successfully connected to remote "
+ "peer (%s) while upgrading endpoint %s.",
+ peer_id.GetId().c_str(), endpoint_id.c_str());
+
+ // Create a new WebRtcEndpointChannel.
+ auto channel = std::make_unique<WebRtcEndpointChannel>(service_id, socket);
+ if (channel == nullptr) {
+ socket.Close();
+ NEARBY_LOG(ERROR,
+ "WebRtcBwuHandler failed to create new EndpointChannel for "
+ "outgoing socket, aborting upgrade.");
+ }
+
+ return channel;
+}
+
+void WebrtcBwuHandler::OnEndpointDisconnect(ClientProxy* client,
+ const std::string& endpoint_id) {}
+
+WebrtcBwuHandler::WebrtcIncomingSocket::WebrtcIncomingSocket(
+ const std::string& name, mediums::WebRtcSocketWrapper socket)
+ : name_(name), socket_(socket) {}
+
+void WebrtcBwuHandler::WebrtcIncomingSocket::Close() { socket_.Close(); }
+
+std::string WebrtcBwuHandler::WebrtcIncomingSocket::ToString() { return name_; }
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/webrtc_bwu_handler.h b/chromium/third_party/nearby/src/connections/implementation/webrtc_bwu_handler.h
new file mode 100644
index 00000000000..dc1ffe09395
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/webrtc_bwu_handler.h
@@ -0,0 +1,99 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_WEBRTC_BWU_HANDLER_H_
+#define CORE_INTERNAL_WEBRTC_BWU_HANDLER_H_
+
+#include "connections/implementation/base_bwu_handler.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/endpoint_channel_manager.h"
+#include "connections/implementation/mediums/mediums.h"
+#ifdef NO_WEBRTC
+#include "connections/implementation/mediums/webrtc_socket_stub.h"
+#else
+#include "connections/implementation/mediums/webrtc_socket.h"
+#endif
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+using BwuNegotiationFrame = BandwidthUpgradeNegotiationFrame;
+
+// Defines the set of methods that need to be implemented to handle the
+// per-Medium-specific operations needed to upgrade an EndpointChannel.
+class WebrtcBwuHandler : public BaseBwuHandler {
+ public:
+ WebrtcBwuHandler(Mediums& mediums, EndpointChannelManager& channel_manager,
+ BwuNotifications notifications);
+ ~WebrtcBwuHandler() override = default;
+
+ private:
+ // Called by the Initiator to setup the upgraded medium for this endpoint (if
+ // that hasn't already been done), and returns a serialized UpgradePathInfo
+ // that can be sent to the Responder.
+ // @BwuHandlerThread
+ ByteArray InitializeUpgradedMediumForEndpoint(
+ ClientProxy* client, const std::string& service_id,
+ const std::string& endpoint_id) override;
+ // Called to revert any state changed by the Initiator to setup the upgraded
+ // medium for an endpoint.
+ // @BwuHandlerThread
+ void Revert() override;
+
+ // Called by the Responder to setup the upgraded medium for this endpoint (if
+ // that hasn't already been done) using the UpgradePathInfo sent by the
+ // Initiator, and returns a new EndpointChannel for the upgraded medium.
+ // @BwuHandlerThread
+ std::unique_ptr<EndpointChannel> CreateUpgradedEndpointChannel(
+ ClientProxy* client, const std::string& service_id,
+ const std::string& endpoint_id,
+ const UpgradePathInfo& upgrade_path_info) override;
+ // Returns the upgrade medium of the BwuHandler.
+ // @BwuHandlerThread
+ Medium GetUpgradeMedium() const override { return Medium::WEB_RTC; }
+
+ void OnIncomingWebrtcConnection(ClientProxy* client,
+ const std::string& service_id,
+ mediums::WebRtcSocketWrapper socket);
+
+ void OnEndpointDisconnect(ClientProxy* client,
+ const std::string& endpoint_id) override;
+
+ std::string GetCountryCode();
+
+ class WebrtcIncomingSocket : public BwuHandler::IncomingSocket {
+ public:
+ explicit WebrtcIncomingSocket(const std::string& name,
+ mediums::WebRtcSocketWrapper socket);
+ ~WebrtcIncomingSocket() override = default;
+
+ std::string ToString() override;
+ void Close() override;
+
+ private:
+ std::string name_;
+ mediums::WebRtcSocketWrapper socket_;
+ };
+
+ Mediums& mediums_;
+ mediums::WebRtc& webrtc_{mediums_.GetWebRtc()};
+ absl::flat_hash_set<std::string> active_service_ids_;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_WEBRTC_BWU_HANDLER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/webrtc_endpoint_channel.cc b/chromium/third_party/nearby/src/connections/implementation/webrtc_endpoint_channel.cc
new file mode 100644
index 00000000000..e798482cfc0
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/webrtc_endpoint_channel.cc
@@ -0,0 +1,35 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/webrtc_endpoint_channel.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+WebRtcEndpointChannel::WebRtcEndpointChannel(
+ const std::string& channel_name, mediums::WebRtcSocketWrapper socket)
+ : BaseEndpointChannel(channel_name, &socket.GetInputStream(),
+ &socket.GetOutputStream()),
+ webrtc_socket_(std::move(socket)) {}
+
+proto::connections::Medium WebRtcEndpointChannel::GetMedium() const {
+ return proto::connections::Medium::WEB_RTC;
+}
+
+void WebRtcEndpointChannel::CloseImpl() { webrtc_socket_.Close(); }
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/webrtc_endpoint_channel.h b/chromium/third_party/nearby/src/connections/implementation/webrtc_endpoint_channel.h
new file mode 100644
index 00000000000..692e1b81a26
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/webrtc_endpoint_channel.h
@@ -0,0 +1,46 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_WEBRTC_ENDPOINT_CHANNEL_H_
+#define CORE_INTERNAL_WEBRTC_ENDPOINT_CHANNEL_H_
+
+#include "connections/implementation/base_endpoint_channel.h"
+#ifdef NO_WEBRTC
+#include "connections/implementation/mediums/webrtc_socket_stub.h"
+#else
+#include "connections/implementation/mediums/webrtc_socket.h"
+#endif
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+class WebRtcEndpointChannel final : public BaseEndpointChannel {
+ public:
+ WebRtcEndpointChannel(const std::string& channel_name,
+ mediums::WebRtcSocketWrapper webrtc_socket);
+
+ proto::connections::Medium GetMedium() const override;
+
+ private:
+ void CloseImpl() override;
+
+ mediums::WebRtcSocketWrapper webrtc_socket_;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_WEBRTC_ENDPOINT_CHANNEL_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/wifi_lan_bwu_handler.cc b/chromium/third_party/nearby/src/connections/implementation/wifi_lan_bwu_handler.cc
new file mode 100644
index 00000000000..fb2f9f27d3a
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/wifi_lan_bwu_handler.cc
@@ -0,0 +1,166 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/wifi_lan_bwu_handler.h"
+
+#include <locale>
+#include <string>
+
+#include "absl/functional/bind_front.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/mediums/utils.h"
+#include "connections/implementation/offline_frames.h"
+#include "connections/implementation/wifi_lan_endpoint_channel.h"
+#include "internal/platform/wifi_lan.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+WifiLanBwuHandler::WifiLanBwuHandler(Mediums& mediums,
+ EndpointChannelManager& channel_manager,
+ BwuNotifications notifications)
+ : BaseBwuHandler(channel_manager, std::move(notifications)),
+ mediums_(mediums) {}
+
+// Called by BWU initiator. Set up WifiLan upgraded medium for this endpoint,
+// and returns a upgrade path info (ip address, port) for remote party to
+// perform discovery.
+ByteArray WifiLanBwuHandler::InitializeUpgradedMediumForEndpoint(
+ ClientProxy* client, const std::string& service_id,
+ const std::string& endpoint_id) {
+ // Use wrapped service ID to avoid have the same ID with the one for
+ // startAdvertising. Otherwise, the listening request would be ignored because
+ // the medium already start accepting the connection because the client not
+ // stop the advertising yet.
+ std::string upgrade_service_id = Utils::WrapUpgradeServiceId(service_id);
+
+ if (!wifi_lan_medium_.IsAcceptingConnections(upgrade_service_id)) {
+ if (!wifi_lan_medium_.StartAcceptingConnections(
+ upgrade_service_id,
+ {
+ .accepted_cb = absl::bind_front(
+ &WifiLanBwuHandler::OnIncomingWifiLanConnection, this,
+ client, service_id),
+ })) {
+ NEARBY_LOGS(ERROR)
+ << "WifiLanBwuHandler couldn't initiate the WifiLan upgrade for "
+ "endpoint "
+ << endpoint_id
+ << " because it failed to start listening for "
+ "incoming WifiLan connections.";
+ return {};
+ }
+ NEARBY_LOGS(INFO)
+ << "WifiLanBwuHandler successfully started listening for incoming "
+ "WifiLan connections while upgrading endpoint "
+ << endpoint_id;
+ }
+
+ // cache service ID to revert
+ active_service_ids_.insert(upgrade_service_id);
+
+ auto credential = wifi_lan_medium_.GetCredentials(upgrade_service_id);
+ auto ip_address = credential.first;
+ auto port = credential.second;
+ if (ip_address.empty()) {
+ NEARBY_LOGS(INFO)
+ << "WifiLanBwuHandler couldn't initiate the wifi_lan upgrade for "
+ "endpoint "
+ << endpoint_id
+ << " because the wifi_lan ip address were unable to be obtained.";
+ return {};
+ }
+
+ return parser::ForBwuWifiLanPathAvailable(ip_address, port);
+}
+
+void WifiLanBwuHandler::Revert() {
+ for (const std::string& service_id : active_service_ids_) {
+ wifi_lan_medium_.StopAcceptingConnections(service_id);
+ }
+ active_service_ids_.clear();
+
+ NEARBY_LOG(INFO, "WifiLanBwuHandler successfully reverted all states.");
+}
+
+// Called by BWU target. Retrieves a new medium info from incoming message,
+// and establishes connection over WifiLan using this info.
+std::unique_ptr<EndpointChannel>
+WifiLanBwuHandler::CreateUpgradedEndpointChannel(
+ ClientProxy* client, const std::string& service_id,
+ const std::string& endpoint_id, const UpgradePathInfo& upgrade_path_info) {
+ if (!upgrade_path_info.has_wifi_lan_socket()) {
+ return nullptr;
+ }
+ const UpgradePathInfo::WifiLanSocket& upgrade_path_info_socket =
+ upgrade_path_info.wifi_lan_socket();
+ if (!upgrade_path_info_socket.has_ip_address() ||
+ !upgrade_path_info_socket.has_wifi_port()) {
+ NEARBY_LOG(ERROR, "WifiLanBwuHandler failed to parse UpgradePathInfo.");
+ return nullptr;
+ }
+
+ const std::string& ip_address = upgrade_path_info_socket.ip_address();
+ std::int32_t port = upgrade_path_info_socket.wifi_port();
+
+ NEARBY_LOGS(VERBOSE) << "WifiLanBwuHandler is attempting to connect to "
+ "available WifiLan service ("
+ << ip_address << ":" << port << ") for endpoint "
+ << endpoint_id;
+
+ WifiLanSocket socket = wifi_lan_medium_.Connect(
+ service_id, ip_address, port, client->GetCancellationFlag(endpoint_id));
+ if (!socket.IsValid()) {
+ NEARBY_LOGS(ERROR)
+ << "WifiLanBwuHandler failed to connect to the WifiLan service ("
+ << ip_address << ":" << port << ") for endpoint " << endpoint_id;
+ return nullptr;
+ }
+
+ NEARBY_LOGS(VERBOSE)
+ << "WifiLanBwuHandler successfully connected to WifiLan service ("
+ << ip_address << ":" << port << ") while upgrading endpoint "
+ << endpoint_id;
+
+ // Create a new WifiLanEndpointChannel.
+ auto channel = absl::make_unique<WifiLanEndpointChannel>(service_id, socket);
+ if (channel == nullptr) {
+ NEARBY_LOGS(ERROR) << "WifiLanBwuHandler failed to create WifiLan endpoint "
+ "channel to the WifiLan service ("
+ << ip_address << ":" << port << ") for endpoint "
+ << endpoint_id;
+ socket.Close();
+ return nullptr;
+ }
+
+ return channel;
+}
+
+// Accept Connection Callback.
+void WifiLanBwuHandler::OnIncomingWifiLanConnection(
+ ClientProxy* client, const std::string& service_id, WifiLanSocket socket) {
+ auto channel = absl::make_unique<WifiLanEndpointChannel>(service_id, socket);
+ std::unique_ptr<IncomingSocketConnection> connection(
+ new IncomingSocketConnection{
+ .socket =
+ absl::make_unique<WifiLanIncomingSocket>(service_id, socket),
+ .channel = std::move(channel),
+ });
+ bwu_notifications_.incoming_connection_cb(client, std::move(connection));
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/wifi_lan_bwu_handler.h b/chromium/third_party/nearby/src/connections/implementation/wifi_lan_bwu_handler.h
new file mode 100644
index 00000000000..dba6b89b914
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/wifi_lan_bwu_handler.h
@@ -0,0 +1,80 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_WIFI_LAN_BWU_HANDLER_H_
+#define CORE_INTERNAL_WIFI_LAN_BWU_HANDLER_H_
+
+#include "connections/implementation/base_bwu_handler.h"
+#include "connections/implementation/client_proxy.h"
+#include "connections/implementation/endpoint_channel_manager.h"
+#include "connections/implementation/mediums/mediums.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Defines the set of methods that need to be implemented to handle the
+// per-Medium-specific operations needed to upgrade an EndpointChannel.
+class WifiLanBwuHandler : public BaseBwuHandler {
+ public:
+ WifiLanBwuHandler(Mediums& mediums, EndpointChannelManager& channel_manager,
+ BwuNotifications notifications);
+ ~WifiLanBwuHandler() override = default;
+
+ private:
+ ByteArray InitializeUpgradedMediumForEndpoint(
+ ClientProxy* client, const std::string& service_id,
+ const std::string& endpoint_id) override;
+
+ void Revert() override;
+
+ std::unique_ptr<EndpointChannel> CreateUpgradedEndpointChannel(
+ ClientProxy* client, const std::string& service_id,
+ const std::string& endpoint_id,
+ const UpgradePathInfo& upgrade_path_info) override;
+
+ Medium GetUpgradeMedium() const override { return Medium::WIFI_LAN; }
+
+ void OnEndpointDisconnect(ClientProxy* client,
+ const std::string& endpoint_id) override {}
+
+ void OnIncomingWifiLanConnection(ClientProxy* client,
+ const std::string& service_id,
+ WifiLanSocket socket);
+
+ class WifiLanIncomingSocket : public BwuHandler::IncomingSocket {
+ public:
+ explicit WifiLanIncomingSocket(const std::string& name,
+ WifiLanSocket socket)
+ : name_(name), socket_(socket) {}
+ ~WifiLanIncomingSocket() override = default;
+
+ std::string ToString() override { return name_; }
+ void Close() override { socket_.Close(); }
+
+ private:
+ std::string name_;
+ WifiLanSocket socket_;
+ };
+
+ Mediums& mediums_;
+ WifiLan& wifi_lan_medium_{mediums_.GetWifiLan()};
+ absl::flat_hash_set<std::string> active_service_ids_;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_WIFI_LAN_BWU_HANDLER_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/wifi_lan_endpoint_channel.cc b/chromium/third_party/nearby/src/connections/implementation/wifi_lan_endpoint_channel.cc
new file mode 100644
index 00000000000..85b22f70740
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/wifi_lan_endpoint_channel.cc
@@ -0,0 +1,47 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/wifi_lan_endpoint_channel.h"
+
+#include <string>
+
+#include "internal/platform/logging.h"
+#include "internal/platform/wifi_lan.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+WifiLanEndpointChannel::WifiLanEndpointChannel(const std::string& channel_name,
+ WifiLanSocket socket)
+ : BaseEndpointChannel(channel_name, &socket.GetInputStream(),
+ &socket.GetOutputStream()),
+ socket_(std::move(socket)) {}
+
+proto::connections::Medium WifiLanEndpointChannel::GetMedium() const {
+ return proto::connections::Medium::WIFI_LAN;
+}
+
+void WifiLanEndpointChannel::CloseImpl() {
+ auto status = socket_.Close();
+ if (!status.Ok()) {
+ NEARBY_LOGS(INFO)
+ << "Failed to close underlying socket for WifiLanEndpointChannel "
+ << GetName() << " : exception = " << status.value;
+ }
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/wifi_lan_endpoint_channel.h b/chromium/third_party/nearby/src/connections/implementation/wifi_lan_endpoint_channel.h
new file mode 100644
index 00000000000..27c847b010a
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/wifi_lan_endpoint_channel.h
@@ -0,0 +1,42 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_WIFI_LAN_ENDPOINT_CHANNEL_H_
+#define CORE_INTERNAL_WIFI_LAN_ENDPOINT_CHANNEL_H_
+
+#include "connections/implementation/base_endpoint_channel.h"
+#include "internal/platform/wifi_lan.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+class WifiLanEndpointChannel final : public BaseEndpointChannel {
+ public:
+ // Creates both outgoing and incoming WifiLan channels.
+ WifiLanEndpointChannel(const std::string& channel_name, WifiLanSocket socket);
+
+ proto::connections::Medium GetMedium() const override;
+
+ private:
+ void CloseImpl() override;
+
+ WifiLanSocket socket_;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_WIFI_LAN_ENDPOINT_CHANNEL_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/wifi_lan_service_info.cc b/chromium/third_party/nearby/src/connections/implementation/wifi_lan_service_info.cc
new file mode 100644
index 00000000000..b21c90de100
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/wifi_lan_service_info.cc
@@ -0,0 +1,205 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/wifi_lan_service_info.h"
+
+#include <inttypes.h>
+
+#include <cstring>
+#include <utility>
+
+#include "absl/strings/str_cat.h"
+#include "internal/platform/base64_utils.h"
+#include "internal/platform/base_input_stream.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// These definitions are necessary before C++17.
+constexpr absl::string_view WifiLanServiceInfo::kKeyEndpointInfo;
+constexpr std::uint32_t WifiLanServiceInfo::kServiceIdHashLength;
+constexpr int WifiLanServiceInfo::kMaxEndpointInfoLength;
+
+WifiLanServiceInfo::WifiLanServiceInfo(Version version, Pcp pcp,
+ absl::string_view endpoint_id,
+ const ByteArray& service_id_hash,
+ const ByteArray& endpoint_info,
+ const ByteArray& uwb_address,
+ WebRtcState web_rtc_state) {
+ if (version != Version::kV1 || endpoint_id.empty() ||
+ endpoint_id.length() != kEndpointIdLength ||
+ service_id_hash.size() != kServiceIdHashLength ||
+ endpoint_info.size() > kMaxEndpointInfoLength) {
+ return;
+ }
+ switch (pcp) {
+ case Pcp::kP2pCluster: // Fall through
+ case Pcp::kP2pStar: // Fall through
+ case Pcp::kP2pPointToPoint:
+ break;
+ default:
+ return;
+ }
+
+ version_ = version;
+ pcp_ = pcp;
+ service_id_hash_ = service_id_hash;
+ endpoint_id_ = std::string(endpoint_id);
+ endpoint_info_ = endpoint_info;
+ uwb_address_ = uwb_address;
+ web_rtc_state_ = web_rtc_state;
+}
+
+WifiLanServiceInfo::WifiLanServiceInfo(const NsdServiceInfo& nsd_service_info) {
+ auto txt_endpoint_info_name =
+ nsd_service_info.GetTxtRecord(std::string(kKeyEndpointInfo));
+ if (!txt_endpoint_info_name.empty()) {
+ endpoint_info_ = Base64Utils::Decode(txt_endpoint_info_name);
+ if (endpoint_info_.size() > kMaxEndpointInfoLength) {
+ NEARBY_LOG(INFO,
+ "Cannot deserialize EndpointInfo: expecting endpoint info "
+ "max %d raw bytes, got %" PRIu64,
+ kMaxEndpointInfoLength, endpoint_info_.size());
+ return;
+ }
+ }
+
+ auto service_info_name = nsd_service_info.GetServiceName();
+ ByteArray service_info_bytes = Base64Utils::Decode(service_info_name);
+ if (service_info_bytes.Empty()) {
+ NEARBY_LOG(
+ INFO,
+ "Cannot deserialize WifiLanServiceInfo: failed Base64 decoding of %s",
+ std::string(service_info_name).c_str());
+ return;
+ }
+
+ if (service_info_bytes.size() < kMinLanServiceNameLength) {
+ NEARBY_LOG(INFO,
+ "Cannot deserialize WifiLanServiceInfo: expecting min %d raw "
+ "bytes, got %" PRIu64,
+ kMinLanServiceNameLength, service_info_bytes.size());
+ return;
+ }
+
+ BaseInputStream base_input_stream{service_info_bytes};
+ // The first 1 byte is supposed to be the version and pcp.
+ auto version_and_pcp_byte = static_cast<char>(base_input_stream.ReadUint8());
+ // The upper 3 bits are supposed to be the version.
+ version_ =
+ static_cast<Version>((version_and_pcp_byte & kVersionBitmask) >> 5);
+ if (version_ != Version::kV1) {
+ NEARBY_LOG(INFO,
+ "Cannot deserialize WifiLanServiceInfo: unsupported Version %d",
+ version_);
+ return;
+ }
+ // The lower 5 bits are supposed to be the Pcp.
+ pcp_ = static_cast<Pcp>(version_and_pcp_byte & kPcpBitmask);
+ switch (pcp_) {
+ case Pcp::kP2pCluster: // Fall through
+ case Pcp::kP2pStar: // Fall through
+ case Pcp::kP2pPointToPoint:
+ break;
+ default:
+ NEARBY_LOG(INFO,
+ "Cannot deserialize WifiLanServiceInfo: unsupported V1 PCP %d",
+ pcp_);
+ }
+
+ // The next 4 bytes are supposed to be the endpoint_id.
+ endpoint_id_ = std::string{base_input_stream.ReadBytes(kEndpointIdLength)};
+
+ // The next 3 bytes are supposed to be the service_id_hash.
+ service_id_hash_ = base_input_stream.ReadBytes(kServiceIdHashLength);
+
+ // The next 1 byte is supposed to be the length of the uwb_address. If
+ // available, continues to deserialize UWB address and extra field of WebRtc
+ // state.
+ if (base_input_stream.IsAvailable(1)) {
+ std::uint32_t expected_uwb_address_length = base_input_stream.ReadUint8();
+ // If the length of uwb_address is not zero, then retrieve it.
+ if (expected_uwb_address_length != 0) {
+ uwb_address_ = base_input_stream.ReadBytes(expected_uwb_address_length);
+ if (uwb_address_.Empty() ||
+ uwb_address_.size() != expected_uwb_address_length) {
+ NEARBY_LOG(INFO,
+ "Cannot deserialize WifiLanServiceInfo: expected "
+ "uwbAddress size to be %d bytes, got %" PRIu64,
+ expected_uwb_address_length, uwb_address_.size());
+ // Clear enpoint_id for validity.
+ endpoint_id_.clear();
+ return;
+ }
+ }
+
+ // The next 1 byte is extra field.
+ web_rtc_state_ = WebRtcState::kUndefined;
+ if (base_input_stream.IsAvailable(kExtraFieldLength)) {
+ auto extra_field = static_cast<char>(base_input_stream.ReadUint8());
+ web_rtc_state_ = (extra_field & kWebRtcConnectableFlagBitmask) == 1
+ ? WebRtcState::kConnectable
+ : WebRtcState::kUnconnectable;
+ }
+ }
+}
+
+WifiLanServiceInfo::operator NsdServiceInfo() const {
+ if (!IsValid()) {
+ return {};
+ }
+
+ // The upper 3 bits are the Version.
+ auto version_and_pcp_byte = static_cast<char>(
+ (static_cast<uint32_t>(Version::kV1) << 5) & kVersionBitmask);
+ // The lower 5 bits are the PCP.
+ version_and_pcp_byte |=
+ static_cast<char>(static_cast<uint32_t>(pcp_) & kPcpBitmask);
+
+ std::string out = absl::StrCat(std::string(1, version_and_pcp_byte),
+ endpoint_id_, std::string(service_id_hash_));
+
+ // The next bytes are UWB address field.
+ if (!uwb_address_.Empty()) {
+ absl::StrAppend(&out, std::string(1, uwb_address_.size()));
+ absl::StrAppend(&out, std::string(uwb_address_));
+ } else {
+ // Write UWB address with length 0 to be able to read the next field, which
+ // needs to be appended.
+ if (web_rtc_state_ != WebRtcState::kUndefined)
+ absl::StrAppend(&out, std::string(1, uwb_address_.size()));
+ }
+
+ // The next 1 byte is extra field.
+ if (web_rtc_state_ != WebRtcState::kUndefined) {
+ int web_rtc_connectable_flag =
+ (web_rtc_state_ == WebRtcState::kConnectable) ? 1 : 0;
+ char field_byte = static_cast<char>(web_rtc_connectable_flag) &
+ kWebRtcConnectableFlagBitmask;
+ absl::StrAppend(&out, std::string(1, field_byte));
+ }
+
+ NsdServiceInfo nsd_service_info;
+ nsd_service_info.SetServiceName(
+ Base64Utils::Encode(ByteArray{std::move(out)}));
+ nsd_service_info.SetTxtRecord(std::string(kKeyEndpointInfo),
+ Base64Utils::Encode(endpoint_info_));
+ return nsd_service_info;
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/implementation/wifi_lan_service_info.h b/chromium/third_party/nearby/src/connections/implementation/wifi_lan_service_info.h
new file mode 100644
index 00000000000..9a68adc19ed
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/wifi_lan_service_info.h
@@ -0,0 +1,97 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_INTERNAL_WIFI_LAN_SERVICE_INFO_H_
+#define CORE_INTERNAL_WIFI_LAN_SERVICE_INFO_H_
+
+#include <cstdint>
+
+#include "absl/strings/string_view.h"
+#include "connections/implementation/base_pcp_handler.h"
+#include "connections/implementation/pcp.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/nsd_service_info.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Represents the format of the WifiLan service info used in Advertising +
+// Discovery.
+//
+// See go/nearby-offline-data-interchange-formats for the specification.
+class WifiLanServiceInfo {
+ public:
+ // Versions of the WifiLanServiceInfo.
+ enum class Version {
+ kUndefined = 0,
+ kV1 = 1,
+ };
+
+ // The key of TXTRecord for EndpointInfo.
+ static constexpr absl::string_view kKeyEndpointInfo{"n"};
+ static constexpr std::uint32_t kServiceIdHashLength = 3;
+ static constexpr int kMaxEndpointInfoLength = 131;
+
+ WifiLanServiceInfo() = default;
+ WifiLanServiceInfo(Version version, Pcp pcp, absl::string_view endpoint_id,
+ const ByteArray& service_id_hash,
+ const ByteArray& endpoint_info,
+ const ByteArray& uwb_address, WebRtcState web_rtc_state);
+
+ // Constructs WifiLanServiceInfo through NsdServiceInfo.
+ explicit WifiLanServiceInfo(const NsdServiceInfo& nsd_service_info);
+ WifiLanServiceInfo(const WifiLanServiceInfo&) = default;
+ WifiLanServiceInfo& operator=(const WifiLanServiceInfo&) = default;
+ WifiLanServiceInfo(WifiLanServiceInfo&&) = default;
+ WifiLanServiceInfo& operator=(WifiLanServiceInfo&&) = default;
+ ~WifiLanServiceInfo() = default;
+
+ explicit operator NsdServiceInfo() const;
+
+ bool IsValid() const { return !endpoint_id_.empty(); }
+ Version GetVersion() const { return version_; }
+ Pcp GetPcp() const { return pcp_; }
+ std::string GetEndpointId() const { return endpoint_id_; }
+ ByteArray GetEndpointInfo() const { return endpoint_info_; }
+ ByteArray GetServiceIdHash() const { return service_id_hash_; }
+ ByteArray GetUwbAddress() const { return uwb_address_; }
+ WebRtcState GetWebRtcState() const { return web_rtc_state_; }
+
+ private:
+ static constexpr int kMinLanServiceNameLength = 9;
+ static constexpr int kEndpointIdLength = 4;
+ static constexpr int kUwbAddressLengthSize = 1;
+ static constexpr int kExtraFieldLength = 1;
+
+ static constexpr int kVersionBitmask = 0x0E0;
+ static constexpr int kPcpBitmask = 0x01F;
+ static constexpr int kVersionShift = 5;
+ static constexpr int kWebRtcConnectableFlagBitmask = 0x01;
+
+ Version version_{Version::kUndefined};
+ Pcp pcp_{Pcp::kUnknown};
+ std::string endpoint_id_;
+ ByteArray service_id_hash_;
+ ByteArray endpoint_info_;
+ // TODO(b/169550050): Define UWB address field.
+ ByteArray uwb_address_;
+ WebRtcState web_rtc_state_{WebRtcState::kUndefined};
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_INTERNAL_WIFI_LAN_SERVICE_INFO_H_
diff --git a/chromium/third_party/nearby/src/connections/implementation/wifi_lan_service_info_test.cc b/chromium/third_party/nearby/src/connections/implementation/wifi_lan_service_info_test.cc
new file mode 100644
index 00000000000..fc290cc8904
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/implementation/wifi_lan_service_info_test.cc
@@ -0,0 +1,171 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/implementation/wifi_lan_service_info.h"
+
+#include <cstring>
+#include <memory>
+
+#include "gtest/gtest.h"
+#include "internal/platform/base64_utils.h"
+#include "internal/platform/nsd_service_info.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+
+constexpr WifiLanServiceInfo::Version kVersion =
+ WifiLanServiceInfo::Version::kV1;
+constexpr Pcp kPcp = Pcp::kP2pCluster;
+constexpr absl::string_view kEndPointID{"AB12"};
+constexpr absl::string_view kServiceIDHashBytes{"\x0a\x0b\x0c"};
+constexpr absl::string_view kEndPointName{"RAWK + ROWL!"};
+constexpr WebRtcState kWebRtcState = WebRtcState::kConnectable;
+
+// TODO(b/169550050): Implement UWBAddress.
+TEST(WifiLanServiceInfoTest, ConstructionWorks) {
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ ByteArray endpoint_info{std::string(kEndPointName)};
+ WifiLanServiceInfo wifi_lan_service_info{
+ kVersion, kPcp, kEndPointID, service_id_hash,
+ endpoint_info, ByteArray{}, kWebRtcState};
+
+ EXPECT_TRUE(wifi_lan_service_info.IsValid());
+ EXPECT_EQ(kPcp, wifi_lan_service_info.GetPcp());
+ EXPECT_EQ(kVersion, wifi_lan_service_info.GetVersion());
+ EXPECT_EQ(kEndPointID, wifi_lan_service_info.GetEndpointId());
+ EXPECT_EQ(service_id_hash, wifi_lan_service_info.GetServiceIdHash());
+ EXPECT_EQ(endpoint_info, wifi_lan_service_info.GetEndpointInfo());
+}
+
+TEST(WifiLanServiceInfoTest, ConstructionFromSerializedStringWorks) {
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ ByteArray endpoint_info{std::string(kEndPointName)};
+ WifiLanServiceInfo org_wifi_lan_service_info{
+ kVersion, kPcp, kEndPointID, service_id_hash,
+ endpoint_info, ByteArray{}, kWebRtcState};
+ NsdServiceInfo nsd_service_info{org_wifi_lan_service_info};
+
+ WifiLanServiceInfo wifi_lan_service_info{nsd_service_info};
+
+ EXPECT_TRUE(wifi_lan_service_info.IsValid());
+ EXPECT_EQ(kPcp, wifi_lan_service_info.GetPcp());
+ EXPECT_EQ(kVersion, wifi_lan_service_info.GetVersion());
+ EXPECT_EQ(kEndPointID, wifi_lan_service_info.GetEndpointId());
+ EXPECT_EQ(service_id_hash, wifi_lan_service_info.GetServiceIdHash());
+ EXPECT_EQ(endpoint_info, wifi_lan_service_info.GetEndpointInfo());
+ EXPECT_EQ(kWebRtcState, wifi_lan_service_info.GetWebRtcState());
+}
+
+TEST(WifiLanServiceInfoTest, ConstructionFailsWithBadVersion) {
+ auto bad_version = static_cast<WifiLanServiceInfo::Version>(666);
+
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ ByteArray endpoint_info{std::string(kEndPointName)};
+ WifiLanServiceInfo wifi_lan_service_info{
+ bad_version, kPcp, kEndPointID, service_id_hash,
+ endpoint_info, ByteArray{}, kWebRtcState};
+
+ EXPECT_FALSE(wifi_lan_service_info.IsValid());
+}
+
+TEST(WifiLanServiceInfoTest, ConstructionFailsWithBadPCP) {
+ auto bad_pcp = static_cast<Pcp>(666);
+
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ ByteArray endpoint_info{std::string(kEndPointName)};
+ WifiLanServiceInfo wifi_lan_service_info{
+ kVersion, bad_pcp, kEndPointID, service_id_hash,
+ endpoint_info, ByteArray{}, kWebRtcState};
+
+ EXPECT_FALSE(wifi_lan_service_info.IsValid());
+}
+
+TEST(WifiLanServiceInfoTest, ConstructionFailsWithShortEndpointId) {
+ std::string short_endpoint_id("AB1");
+
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ ByteArray endpoint_info{std::string(kEndPointName)};
+ WifiLanServiceInfo wifi_lan_service_info{
+ kVersion, kPcp, short_endpoint_id, service_id_hash,
+ endpoint_info, ByteArray{}, kWebRtcState};
+
+ EXPECT_FALSE(wifi_lan_service_info.IsValid());
+}
+
+TEST(WifiLanServiceInfoTest, ConstructionFailsWithLongEndpointId) {
+ std::string long_endpoint_id("AB12X");
+
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ ByteArray endpoint_info{std::string(kEndPointName)};
+ WifiLanServiceInfo wifi_lan_service_info{
+ kVersion, kPcp, long_endpoint_id, service_id_hash,
+ endpoint_info, ByteArray{}, kWebRtcState};
+
+ EXPECT_FALSE(wifi_lan_service_info.IsValid());
+}
+
+TEST(WifiLanServiceInfoTest, ConstructionFailsWithShortServiceIdHash) {
+ char short_service_id_hash_bytes[] = "\x0a\x0b";
+
+ ByteArray short_service_id_hash{short_service_id_hash_bytes};
+ ByteArray endpoint_info{std::string(kEndPointName)};
+ WifiLanServiceInfo wifi_lan_service_info{
+ kVersion, kPcp, kEndPointID, short_service_id_hash,
+ endpoint_info, ByteArray{}, kWebRtcState};
+
+ EXPECT_FALSE(wifi_lan_service_info.IsValid());
+}
+
+TEST(WifiLanServiceInfoTest, ConstructionFailsWithLongServiceIdHash) {
+ char long_service_id_hash_bytes[] = "\x0a\x0b\x0c\x0d";
+
+ ByteArray long_service_id_hash{long_service_id_hash_bytes};
+ ByteArray endpoint_info{std::string(kEndPointName)};
+ WifiLanServiceInfo wifi_lan_service_info{
+ kVersion, kPcp, kEndPointID, long_service_id_hash,
+ endpoint_info, ByteArray{}, kWebRtcState};
+
+ EXPECT_FALSE(wifi_lan_service_info.IsValid());
+}
+
+TEST(WifiLanServiceInfoTest, ConstructionFailsWithShortServiceNameLength) {
+ char wifi_lan_service_info_name[] = {'X', '\0'};
+ ByteArray wifi_lan_service_info_bytes{wifi_lan_service_info_name};
+
+ NsdServiceInfo nsd_service_info;
+ nsd_service_info.SetServiceName(
+ Base64Utils::Encode(wifi_lan_service_info_bytes));
+
+ WifiLanServiceInfo wifi_lan_service_info{nsd_service_info};
+
+ EXPECT_FALSE(wifi_lan_service_info.IsValid());
+}
+
+TEST(WifiLanServiceInfoTest, ConstructionFailsWithLongEndpointInfoLength) {
+ ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
+ ByteArray long_endpoint_info(WifiLanServiceInfo::kMaxEndpointInfoLength + 1);
+
+ WifiLanServiceInfo wifi_lan_service_info{
+ kVersion, kPcp, kEndPointID, service_id_hash,
+ long_endpoint_info, ByteArray{}, kWebRtcState};
+
+ EXPECT_FALSE(wifi_lan_service_info.IsValid());
+}
+
+} // namespace
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/listeners.h b/chromium/third_party/nearby/src/connections/listeners.h
new file mode 100644
index 00000000000..ff11b66e306
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/listeners.h
@@ -0,0 +1,198 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_LISTENERS_H_
+#define CORE_LISTENERS_H_
+
+#include <cstdint>
+#include <functional>
+#include <memory>
+#include <string>
+
+// This file defines all the protocol listeners and their parameter structures.
+// Listeners are defined as collections of std::function<T> instances, which is
+// more flexible than a virtual function:
+// - a subset of listener callbacks may be overridden, while others may remain
+// default-initialized.
+// - callbacks may be initialized with lambdas; lambda definitions are concize.
+
+#include "connections/connection_options.h"
+#include "connections/payload.h"
+#include "connections/status.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/byte_utils.h"
+#include "internal/platform/listeners.h"
+#include "internal/platform/core_config.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Common callback for asynchronously invoked methods.
+// Called after a job scheduled for execution is completed.
+// This is not the same as completion of the associated process,
+// which may have many states, and multiple async jobs, and be still ongoing.
+// Progress on the overall process is reported by the associated listener.
+struct DLL_API ResultCallback {
+ // Callback to access the status of the operation when available.
+ // status - result of job execution;
+ // Status::kSuccess, if successful; anything else indicates failure.
+ std::function<void(Status)> result_cb = DefaultCallback<Status>();
+};
+
+struct DLL_API ConnectionResponseInfo {
+ std::string GetAuthenticationDigits() {
+ return ByteUtils::ToFourDigitString(raw_authentication_token);
+ }
+
+ ByteArray remote_endpoint_info;
+ std::string authentication_token;
+ ByteArray raw_authentication_token;
+ bool is_incoming_connection = false;
+ bool is_connection_verified = false;
+};
+
+struct DLL_API PayloadProgressInfo {
+ std::int64_t payload_id = 0;
+ enum class Status {
+ kSuccess,
+ kFailure,
+ kInProgress,
+ kCanceled,
+ } status = Status::kSuccess;
+ std::int64_t total_bytes = 0;
+ std::int64_t bytes_transferred = 0;
+};
+
+enum class DLL_API DistanceInfo {
+ kUnknown = 1,
+ kVeryClose = 2,
+ kClose = 3,
+ kFar = 4,
+};
+
+struct DLL_API ConnectionListener {
+ // A basic encrypted channel has been created between you and the endpoint.
+ // Both sides are now asked if they wish to accept or reject the connection
+ // before any data can be sent over this channel.
+ //
+ // This is your chance, before you accept the connection, to confirm that you
+ // connected to the correct device. Both devices are given an identical token;
+ // it's up to you to decide how to verify it before proceeding. Typically this
+ // involves showing the token on both devices and having the users manually
+ // compare and confirm; however, this is only required if you desire a secure
+ // connection between the devices.
+ //
+ // Whichever route you decide to take (including not authenticating the other
+ // device), call Core::AcceptConnection() when you're ready to talk, or
+ // Core::RejectConnection() to close the connection.
+ //
+ // endpoint_id - The identifier for the remote endpoint.
+ // info - Other relevant information about the connection.
+ std::function<void(const std::string& endpoint_id,
+ const ConnectionResponseInfo& info)>
+ initiated_cb =
+ DefaultCallback<const std::string&, const ConnectionResponseInfo&>();
+
+ // Called after both sides have accepted the connection.
+ // Both sides may now send Payloads to each other.
+ // Call Core::SendPayload() or wait for incoming PayloadListener::OnPayload().
+ //
+ // endpoint_id - The identifier for the remote endpoint.
+ std::function<void(const std::string& endpoint_id)> accepted_cb =
+ DefaultCallback<const std::string&>();
+
+ // Called when either side rejected the connection.
+ // Payloads can not be exchaged. Call Core::DisconnectFromEndpoint()
+ // to terminate connection.
+ //
+ // endpoint_id - The identifier for the remote endpoint.
+ std::function<void(const std::string& endpoint_id, Status status)>
+ rejected_cb = DefaultCallback<const std::string&, Status>();
+
+ // Called when a remote endpoint is disconnected or has become unreachable.
+ // At this point service (re-)discovery may start again.
+ //
+ // endpoint_id - The identifier for the remote endpoint.
+ std::function<void(const std::string& endpoint_id)> disconnected_cb =
+ DefaultCallback<const std::string&>();
+
+ // Called when the connection's available bandwidth has changed.
+ //
+ // endpoint_id - The identifier for the remote endpoint.
+ // medium - Medium we upgraded to.
+ std::function<void(const std::string& endpoint_id, Medium medium)>
+ bandwidth_changed_cb = DefaultCallback<const std::string&, Medium>();
+};
+
+struct DLL_API DiscoveryListener {
+ // Called when a remote endpoint is discovered.
+ //
+ // endpoint_id - The ID of the remote endpoint that was discovered.
+ // endpoint_info - The info of the remote endpoint representd by ByteArray.
+ // service_id - The ID of the service advertised by the remote endpoint.
+ std::function<void(const std::string& endpoint_id,
+ const ByteArray& endpoint_info,
+ const std::string& service_id)>
+ endpoint_found_cb = DefaultCallback<const std::string&, const ByteArray&,
+ const std::string&>();
+
+ // Called when a remote endpoint is no longer discoverable; only called for
+ // endpoints that previously had been passed to {@link
+ // #onEndpointFound(String, DiscoveredEndpointInfo)}.
+ //
+ // endpoint_id - The ID of the remote endpoint that was lost.
+ std::function<void(const std::string& endpoint_id)> endpoint_lost_cb =
+ DefaultCallback<const std::string&>();
+
+ // Called when a remote endpoint is found with an updated distance.
+ //
+ // arguments:
+ // endpoint_id - The ID of the remote endpoint that was lost.
+ // info - The distance info, encoded as enum value.
+ std::function<void(const std::string& endpoint_id, DistanceInfo info)>
+ endpoint_distance_changed_cb =
+ DefaultCallback<const std::string&, DistanceInfo>();
+};
+
+struct DLL_API PayloadListener {
+ // Called when a Payload is received from a remote endpoint. Depending
+ // on the type of the Payload, all of the data may or may not have been
+ // received at the time of this call. Use OnPayloadProgress() to
+ // get updates on the status of the data received.
+ //
+ // endpoint_id - The identifier for the remote endpoint that sent the
+ // payload.
+ // payload - The Payload object received.
+ std::function<void(const std::string& endpoint_id, Payload payload)>
+ payload_cb = DefaultCallback<const std::string&, Payload>();
+
+ // Called with progress information about an active Payload transfer, either
+ // incoming or outgoing.
+ //
+ // endpoint_id - The identifier for the remote endpoint that is sending or
+ // receiving this payload.
+ // info - The PayloadProgressInfo structure describing the status of
+ // the transfer.
+ std::function<void(const std::string& endpoint_id,
+ const PayloadProgressInfo& info)>
+ payload_progress_cb =
+ DefaultCallback<const std::string&, const PayloadProgressInfo&>();
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_LISTENERS_H_
diff --git a/chromium/third_party/nearby/src/connections/listeners_test.cc b/chromium/third_party/nearby/src/connections/listeners_test.cc
new file mode 100644
index 00000000000..2595899a264
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/listeners_test.cc
@@ -0,0 +1,60 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/listeners.h"
+
+#include <memory>
+#include <utility>
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+namespace {
+
+TEST(ListenersTest, EnsureDefaultInitializedIsCallable) {
+ ConnectionListener listener;
+ std::string endpoint_id("endpoint_id");
+ listener.initiated_cb(endpoint_id, ConnectionResponseInfo());
+ listener.accepted_cb(endpoint_id);
+ listener.rejected_cb(endpoint_id, {Status::kError});
+ listener.disconnected_cb(endpoint_id);
+ listener.bandwidth_changed_cb(endpoint_id, Medium());
+ SUCCEED();
+}
+
+TEST(ListenersTest, EnsurePartiallyInitializedIsCallable) {
+ std::string endpoint_id = {"endpoint_id"};
+ bool initiated_cb_called = false;
+ ConnectionListener listener{
+ .initiated_cb =
+ [&](std::string, ConnectionResponseInfo) {
+ initiated_cb_called = true;
+ },
+ };
+ listener.initiated_cb(endpoint_id, ConnectionResponseInfo());
+ listener.accepted_cb(endpoint_id);
+ listener.rejected_cb(endpoint_id, {Status::kError});
+ listener.disconnected_cb(endpoint_id);
+ listener.bandwidth_changed_cb(endpoint_id, Medium());
+ EXPECT_TRUE(initiated_cb_called);
+}
+
+} // namespace
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/medium_selector.h b/chromium/third_party/nearby/src/connections/medium_selector.h
new file mode 100644
index 00000000000..4c7907d8d4d
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/medium_selector.h
@@ -0,0 +1,78 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+#ifndef CORE_MEDIUM_SELECTOR_H_
+#define CORE_MEDIUM_SELECTOR_H_
+
+#include "proto/connections_enums.pb.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+using Medium = location::nearby::proto::connections::Medium;
+
+// Generic type: allows definition of a feature T for every Medium.
+template <typename T>
+struct MediumSelector {
+ T bluetooth;
+ T ble;
+ T web_rtc;
+ T wifi_lan;
+
+ constexpr MediumSelector() = default;
+ constexpr MediumSelector(const MediumSelector&) = default;
+ constexpr MediumSelector& operator=(const MediumSelector&) = default;
+ constexpr bool Any(T value) const {
+ return bluetooth == value || ble == value || web_rtc == value ||
+ wifi_lan == value;
+ }
+
+ constexpr bool All(T value) const {
+ return bluetooth == value && ble == value && web_rtc == value &&
+ wifi_lan == value;
+ }
+
+ constexpr int Count(T value) const {
+ int count = 0;
+ if (bluetooth == value) count++;
+ if (ble == value) count++;
+ if (wifi_lan == value) count++;
+ if (web_rtc == value) count++;
+ return count;
+ }
+
+ constexpr MediumSelector& SetAll(T value) {
+ bluetooth = value;
+ ble = value;
+ web_rtc = value;
+ wifi_lan = value;
+ return *this;
+ }
+
+ std::vector<Medium> GetMediums(T value) const {
+ std::vector<Medium> mediums;
+ // Mediums are sorted in order of decreasing preference.
+ if (wifi_lan == value) mediums.push_back(Medium::WIFI_LAN);
+ if (web_rtc == value) mediums.push_back(Medium::WEB_RTC);
+ if (bluetooth == value) mediums.push_back(Medium::BLUETOOTH);
+ if (ble == value) mediums.push_back(Medium::BLE);
+ return mediums;
+ }
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_MEDIUM_SELECTOR_H_
diff --git a/chromium/third_party/nearby/src/connections/options_base.h b/chromium/third_party/nearby/src/connections/options_base.h
new file mode 100644
index 00000000000..4ddc4fab643
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/options_base.h
@@ -0,0 +1,39 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+#ifndef CORE_OPTIONS_BASE_H_
+#define CORE_OPTIONS_BASE_H_
+#include <string>
+
+#include "connections/medium_selector.h"
+#include "connections/strategy.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Feature On/Off switch for mediums.
+using BooleanMediumSelector = MediumSelector<bool>;
+
+// Connection Options: used for both Advertising and Discovery.
+// All fields are mutable, to make the type copy-assignable.
+struct OptionsBase {
+ Strategy strategy;
+ BooleanMediumSelector allowed{BooleanMediumSelector().SetAll(true)};
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_OPTIONS_BASE_H_
diff --git a/chromium/third_party/nearby/src/connections/out_of_band_connection_metadata.h b/chromium/third_party/nearby/src/connections/out_of_band_connection_metadata.h
new file mode 100644
index 00000000000..81800858a7e
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/out_of_band_connection_metadata.h
@@ -0,0 +1,60 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+#ifndef CORE_OUT_OF_BAND_CONNECTION_METADATA_H_
+#define CORE_OUT_OF_BAND_CONNECTION_METADATA_H_
+
+#include <string>
+
+#include "connections/medium_selector.h"
+#include "connections/strategy.h"
+#include "internal/platform/byte_array.h"
+#include "proto/connections_enums.pb.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Feature On/Off switch for mediums.
+using BooleanMediumSelector = MediumSelector<bool>;
+
+// Metadata injected to facilitate out-of-band connections. The medium field is
+// required, and the other fields are only specified for a specific medium.
+// Currently, Bluetooth is the only supported medium for out-of-band
+// connections.
+struct OutOfBandConnectionMetadata {
+ // Medium to use for the out-of-band connection.
+ Medium medium;
+
+ // Endpoint ID to use for the injected connection; will be included in the
+ // endpoint_found_cb callback. Must be exactly 4 bytes and should be randomly-
+ // generated such that no two IDs are identical.
+ std::string endpoint_id;
+
+ // Endpoint info to use for the injected connection; will be included in the
+ // endpoint_found_cb callback. Should uniquely identify the InjectEndpoint()
+ // call so that the client which made the call can verify the endpoint
+ // that was found is the one that was injected.
+ //
+ // Cannot be empty, and must be <131 bytes.
+ ByteArray endpoint_info;
+
+ // Used for Bluetooth connections.
+ ByteArray remote_bluetooth_mac_address;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_OUT_OF_BAND_CONNECTION_METADATA_H_
diff --git a/chromium/third_party/nearby/src/connections/params.h b/chromium/third_party/nearby/src/connections/params.h
new file mode 100644
index 00000000000..25393ee341e
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/params.h
@@ -0,0 +1,43 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_PARAMS_H_
+#define CORE_PARAMS_H_
+
+#include <string>
+
+#include "connections/listeners.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/core_config.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Used by Discovery in Core::RequestConnection().
+// Used by Advertising in Core::StartAdvertising().
+struct DLL_API ConnectionRequestInfo {
+ // endpoint_info - Identifing information about this endpoint (eg. name,
+ // device type).
+ // listener - A set of callbacks notified when remote endpoints request a
+ // connection to this endpoint.
+ ByteArray endpoint_info;
+ ConnectionListener listener;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_PARAMS_H_
diff --git a/chromium/third_party/nearby/src/connections/payload.cc b/chromium/third_party/nearby/src/connections/payload.cc
new file mode 100644
index 00000000000..4979d0549ff
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/payload.cc
@@ -0,0 +1,101 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/payload.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Payload is default-constructible, and moveable, but not copyable container
+// that holds at most one instance of one of:
+// ByteArray, InputStream, or InputFile.
+Payload::Payload(Payload&& other) noexcept = default;
+Payload::~Payload() = default;
+Payload& Payload::operator=(Payload&& other) noexcept = default;
+
+// Default (invalid) payload.
+Payload::Payload() : content_(absl::monostate()) {}
+
+// Constructors for outgoing payloads.
+Payload::Payload(ByteArray&& bytes) : content_(std::move(bytes)) {}
+
+Payload::Payload(const ByteArray& bytes) : content_(bytes) {}
+
+Payload::Payload(InputFile file)
+ : content_(std::move(file)),
+ id_(std::hash<std::string>()(file.GetFilePath())) {}
+
+// TODO(jfcarroll): Convert std::function to function pointer
+Payload::Payload(std::function<InputStream&()> stream)
+ : content_(std::move(stream)) {}
+
+// Constructors for incoming payloads.
+Payload::Payload(Id id, ByteArray&& bytes)
+ : content_(std::move(bytes)), id_(id) {}
+
+Payload::Payload(Id id, const ByteArray& bytes) : content_(bytes), id_(id) {}
+
+Payload::Payload(Id id, InputFile file) : content_(std::move(file)), id_(id) {}
+
+// TODO(jfcarroll): Convert std::function to function pointer
+Payload::Payload(Id id, std::function<InputStream&()> stream)
+ : content_(std::move(stream)), id_(id) {}
+
+// Returns ByteArray payload, if it has been defined, or empty ByteArray.
+const ByteArray& Payload::AsBytes() const& {
+ static const ByteArray empty; // NOLINT: function-level static is OK.
+ auto* result = absl::get_if<ByteArray>(&content_);
+ return result ? *result : empty;
+}
+ByteArray&& Payload::AsBytes() && {
+ auto* result = absl::get_if<ByteArray>(&content_);
+ return result ? std::move(*result) : std::move(ByteArray());
+}
+// Returns InputStream* payload, if it has been defined, or nullptr.
+InputStream* Payload::AsStream() {
+ auto* result = absl::get_if<std::function<InputStream&()>>(&content_);
+ return result ? &(*result)() : nullptr;
+}
+// Returns InputFile* payload, if it has been defined, or nullptr.
+InputFile* Payload::AsFile() { return absl::get_if<InputFile>(&content_); }
+
+// Returns Payload unique ID.
+Payload::Id Payload::GetId() const { return id_; }
+
+// Returns Payload type.
+Payload::Type Payload::GetType() const { return type_; }
+
+// Sets the payload offset in bytes
+void Payload::SetOffset(size_t offset) {
+ CHECK(type_ == Type::kFile || type_ == Type::kStream);
+ InputFile* file = AsFile();
+ if (file != nullptr) {
+ CHECK(file->GetTotalSize() > 0 && offset < (size_t)file->GetTotalSize());
+ }
+ offset_ = offset;
+}
+
+size_t Payload::GetOffset() { return offset_; }
+
+// Generate Payload Id; to be passed to outgoing file constructor.
+Payload::Id Payload::GenerateId() { return Prng().NextInt64(); }
+
+Payload::Type Payload::FindType() const {
+ return static_cast<Type>(content_.index());
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/payload.h b/chromium/third_party/nearby/src/connections/payload.h
new file mode 100644
index 00000000000..e82505a0fdc
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/payload.h
@@ -0,0 +1,104 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_PAYLOAD_H_
+#define CORE_PAYLOAD_H_
+
+#include <cstdint>
+#include <functional>
+#include <memory>
+#include <utility>
+
+#include "absl/types/variant.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/input_stream.h"
+#include "internal/platform/payload_id.h"
+#include "internal/platform/prng.h"
+#include "internal/platform/core_config.h"
+#include "internal/platform/file.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Payload is default-constructible, and moveable, but not copyable container
+// that holds at most one instance of one of:
+// ByteArray, InputStream, or InputFile.
+class DLL_API Payload {
+ public:
+ using Id = PayloadId;
+ // Order of types in variant, and values in Type enum is important.
+ // Enum values must match respective variant types.
+ using Content = absl::variant<absl::monostate, ByteArray,
+ std::function<InputStream&()>, InputFile>;
+ enum class Type { kUnknown = 0, kBytes = 1, kStream = 2, kFile = 3 };
+
+ Payload(Payload&& other) noexcept;
+ ~Payload();
+ Payload& operator=(Payload&& other) noexcept;
+
+ // Default (invalid) payload.
+ Payload();
+
+ // Constructors for outgoing payloads.
+ explicit Payload(ByteArray&& bytes);
+
+ explicit Payload(const ByteArray& bytes);
+ explicit Payload(InputFile file);
+ explicit Payload(std::function<InputStream&()> stream);
+
+ // Constructors for incoming payloads.
+ Payload(Id id, ByteArray&& bytes);
+ Payload(Id id, const ByteArray& bytes);
+ Payload(Id id, InputFile file);
+ Payload(Id id, std::function<InputStream&()> stream);
+
+
+ // Returns ByteArray payload, if it has been defined, or empty ByteArray.
+ const ByteArray& AsBytes() const&;
+ ByteArray&& AsBytes() &&;
+ // Returns InputStream* payload, if it has been defined, or nullptr.
+ InputStream* AsStream();
+ // Returns InputFile* payload, if it has been defined, or nullptr.
+ InputFile* AsFile();
+
+ // Returns Payload unique ID.
+ Id GetId() const;
+
+ // Returns Payload type.
+ Type GetType() const;
+
+ // Sets the payload offset in bytes
+ void SetOffset(size_t offset);
+
+ size_t GetOffset();
+
+ // Generate Payload Id; to be passed to outgoing file constructor.
+ static Id GenerateId();
+
+ private:
+ Type FindType() const;
+
+ Content content_;
+ Id id_{GenerateId()};
+ Type type_{FindType()};
+ size_t offset_{0};
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_PAYLOAD_H_
diff --git a/chromium/third_party/nearby/src/connections/payload_test.cc b/chromium/third_party/nearby/src/connections/payload_test.cc
new file mode 100644
index 00000000000..e12ce8fc162
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/payload_test.cc
@@ -0,0 +1,108 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/payload.h"
+
+#include <memory>
+#include <type_traits>
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/input_stream.h"
+#include "internal/platform/file.h"
+#include "internal/platform/pipe.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+TEST(PayloadTest, DefaultPayloadHasUnknownType) {
+ Payload payload;
+ EXPECT_EQ(payload.GetType(), Payload::Type::kUnknown);
+}
+
+TEST(PayloadTest, SupportsByteArrayType) {
+ const ByteArray bytes("bytes");
+ Payload payload(bytes);
+ EXPECT_EQ(payload.GetType(), Payload::Type::kBytes);
+ EXPECT_EQ(payload.AsStream(), nullptr);
+ EXPECT_EQ(payload.AsFile(), nullptr);
+ EXPECT_EQ(payload.AsBytes(), bytes);
+}
+
+TEST(PayloadTest, SupportsFileType) {
+ constexpr size_t kOffset = 99;
+ const auto payload_id = Payload::GenerateId();
+ InputFile file(payload_id, 100);
+ InputStream& stream = file.GetInputStream();
+
+ Payload payload(payload_id, std::move(file));
+ payload.SetOffset(kOffset);
+
+ EXPECT_EQ(payload.GetType(), Payload::Type::kFile);
+ EXPECT_EQ(payload.AsStream(), nullptr);
+ EXPECT_EQ(&payload.AsFile()->GetInputStream(), &stream);
+ EXPECT_EQ(payload.AsBytes(), ByteArray{});
+ EXPECT_EQ(payload.GetOffset(), kOffset);
+}
+
+TEST(PayloadTest, SupportsStreamType) {
+ constexpr size_t kOffset = 1234456;
+ auto pipe = std::make_shared<Pipe>();
+
+ Payload payload([streamable = pipe]() -> InputStream& {
+ // For some reason, linter warns us that we return a dangling reference.
+ // This is not true: we return a reference to internal variable of a
+ // shared_ptr<Pipe> which remains valid while Payload is valid, since
+ // shared_ptr<Pipe> is captured by value.
+ return streamable->GetInputStream(); // NOLINT
+ });
+ payload.SetOffset(kOffset);
+
+ EXPECT_EQ(payload.GetType(), Payload::Type::kStream);
+ EXPECT_EQ(payload.AsStream(), &pipe->GetInputStream());
+ EXPECT_EQ(payload.AsFile(), nullptr);
+ EXPECT_EQ(payload.AsBytes(), ByteArray{});
+ EXPECT_EQ(payload.GetOffset(), kOffset);
+}
+
+TEST(PayloadTest, PayloadIsMoveable) {
+ Payload payload1;
+ Payload payload2(ByteArray("bytes"));
+ auto id = payload2.GetId();
+ ByteArray bytes = payload2.AsBytes();
+ EXPECT_EQ(payload1.GetType(), Payload::Type::kUnknown);
+ EXPECT_EQ(payload2.GetType(), Payload::Type::kBytes);
+ payload1 = std::move(payload2);
+ EXPECT_EQ(payload1.GetType(), Payload::Type::kBytes);
+ EXPECT_EQ(payload1.AsBytes(), bytes);
+ EXPECT_EQ(payload1.GetId(), id);
+}
+
+TEST(PayloadTest, PayloadHasUniqueId) {
+ Payload payload1;
+ Payload payload2;
+ EXPECT_NE(payload1.GetId(), payload2.GetId());
+}
+
+TEST(PayloadTest, PayloadIsNotCopyable) {
+ EXPECT_FALSE(std::is_copy_constructible_v<Payload>);
+ EXPECT_FALSE(std::is_copy_assignable_v<Payload>);
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/power_level.h b/chromium/third_party/nearby/src/connections/power_level.h
new file mode 100644
index 00000000000..1753dfec3b5
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/power_level.h
@@ -0,0 +1,31 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef CORE_POWER_LEVEL_H_
+#define CORE_POWER_LEVEL_H_
+
+namespace location {
+namespace nearby {
+namespace connections { // Represents the various power levels that can be
+ // used, on mediums that support it.
+enum class PowerLevel {
+ kHighPower = 0,
+ kLowPower = 1,
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+#endif // CORE_POWER_LEVEL_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/status.h b/chromium/third_party/nearby/src/connections/status.h
index 4fef2ad1dff..4fef2ad1dff 100644
--- a/chromium/third_party/nearby/src/cpp/core/status.h
+++ b/chromium/third_party/nearby/src/connections/status.h
diff --git a/chromium/third_party/nearby/src/connections/status_test.cc b/chromium/third_party/nearby/src/connections/status_test.cc
new file mode 100644
index 00000000000..472aa6e5512
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/status_test.cc
@@ -0,0 +1,59 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/status.h"
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+TEST(StatusTest, DefaultIsError) {
+ Status status;
+ EXPECT_FALSE(status.Ok());
+ EXPECT_EQ(status, Status{Status::kError});
+}
+
+TEST(StatusTest, DefaultEquals) {
+ Status status1;
+ Status status2;
+ EXPECT_EQ(status1, status2);
+}
+
+TEST(StatusTest, ExplicitInitEquals) {
+ Status status1 = {Status::kSuccess};
+ Status status2 = {Status::kSuccess};
+ EXPECT_EQ(status1, status2);
+ EXPECT_TRUE(status1.Ok());
+}
+
+TEST(StatusTest, ExplicitInitNotEquals) {
+ Status status1 = {Status::kSuccess};
+ Status status2 = {Status::kAlreadyAdvertising};
+ EXPECT_NE(status1, status2);
+}
+
+TEST(StatusTest, CopyInitEquals) {
+ Status status1 = {Status::kAlreadyAdvertising};
+ Status status2 = {status1};
+
+ EXPECT_EQ(status1, status2);
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/strategy.cc b/chromium/third_party/nearby/src/connections/strategy.cc
new file mode 100644
index 00000000000..2b50fa6fffb
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/strategy.cc
@@ -0,0 +1,59 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/strategy.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+const Strategy Strategy::kNone = {Strategy::ConnectionType::kNone,
+ Strategy::TopologyType::kUnknown};
+const Strategy Strategy::kP2pCluster{Strategy::ConnectionType::kPointToPoint,
+ Strategy::TopologyType::kManyToMany};
+const Strategy Strategy::kP2pStar{Strategy::ConnectionType::kPointToPoint,
+ Strategy::TopologyType::kOneToMany};
+const Strategy Strategy::kP2pPointToPoint{
+ Strategy::ConnectionType::kPointToPoint, Strategy::TopologyType::kOneToOne};
+
+bool Strategy::IsNone() const { return *this == kNone; }
+
+bool Strategy::IsValid() const {
+ return *this == kP2pStar || *this == kP2pCluster || *this == kP2pPointToPoint;
+}
+
+std::string Strategy::GetName() const {
+ if (*this == Strategy::kP2pCluster) {
+ return "P2P_CLUSTER";
+ } else if (*this == Strategy::kP2pStar) {
+ return "P2P_STAR";
+ } else if (*this == Strategy::kP2pPointToPoint) {
+ return "P2P_POINT_TO_POINT";
+ } else {
+ return "UNKNOWN";
+ }
+}
+
+bool operator==(const Strategy& lhs, const Strategy& rhs) {
+ return lhs.connection_type_ == rhs.connection_type_ &&
+ lhs.topology_type_ == rhs.topology_type_;
+}
+
+bool operator!=(const Strategy& lhs, const Strategy& rhs) {
+ return !(lhs == rhs);
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/connections/strategy.h b/chromium/third_party/nearby/src/connections/strategy.h
new file mode 100644
index 00000000000..30fea2713fc
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/strategy.h
@@ -0,0 +1,72 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+#ifndef CORE_STRATEGY_H_
+#define CORE_STRATEGY_H_
+
+#include <string>
+
+#include "internal/platform/core_config.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+// Defines a copyable, comparable connection strategy type.
+// It is one of: kP2pCluster, kP2pStar, kP2pPointToPoint.
+class DLL_API Strategy {
+ public:
+ static const Strategy kNone;
+ static const Strategy kP2pCluster;
+ static const Strategy kP2pStar;
+ static const Strategy kP2pPointToPoint;
+ constexpr Strategy() : Strategy(kNone) {}
+ constexpr Strategy(const Strategy&) = default;
+ constexpr Strategy& operator=(const Strategy&) = default;
+
+ // Returns true, if strategy is kNone, false otherwise.
+ bool IsNone() const;
+
+ // Returns true, if a strategy is one of the supported strategies,
+ // false otherwise.
+ bool IsValid() const;
+
+ // Returns a string representing given strategy, for every valid strategy.
+ std::string GetName() const;
+
+ // Undefine strategy.
+ void Clear() { *this = kNone; }
+ friend bool operator==(const Strategy& lhs, const Strategy& rhs);
+ friend bool operator!=(const Strategy& lhs, const Strategy& rhs);
+
+ private:
+ enum class ConnectionType {
+ kNone = 0,
+ kPointToPoint = 1,
+ };
+ enum class TopologyType {
+ kUnknown = 0,
+ kOneToOne = 1,
+ kOneToMany = 2,
+ kManyToMany = 3,
+ };
+ constexpr Strategy(ConnectionType connection_type, TopologyType topology_type)
+ : connection_type_(connection_type), topology_type_(topology_type) {}
+ ConnectionType connection_type_;
+ TopologyType topology_type_;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+#endif // CORE_STRATEGY_H_
diff --git a/chromium/third_party/nearby/src/connections/strategy_test.cc b/chromium/third_party/nearby/src/connections/strategy_test.cc
new file mode 100644
index 00000000000..dfa56ba5f11
--- /dev/null
+++ b/chromium/third_party/nearby/src/connections/strategy_test.cc
@@ -0,0 +1,55 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "connections/strategy.h"
+
+#include "gtest/gtest.h"
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+TEST(StrategyTest, IsValidWorks) {
+ EXPECT_FALSE(Strategy().IsValid());
+ EXPECT_TRUE(Strategy::kP2pCluster.IsValid());
+ EXPECT_TRUE(Strategy::kP2pStar.IsValid());
+ EXPECT_TRUE(Strategy::kP2pPointToPoint.IsValid());
+}
+
+TEST(StrategyTest, IsNoneWorks) {
+ EXPECT_TRUE(Strategy().IsNone());
+ EXPECT_FALSE(Strategy::kP2pCluster.IsNone());
+ EXPECT_FALSE(Strategy::kP2pStar.IsNone());
+ EXPECT_FALSE(Strategy::kP2pPointToPoint.IsNone());
+}
+
+TEST(StrategyTest, CompareWorks) {
+ EXPECT_EQ(Strategy::kP2pCluster, Strategy::kP2pCluster);
+ EXPECT_EQ(Strategy::kP2pStar, Strategy::kP2pStar);
+ EXPECT_EQ(Strategy::kP2pPointToPoint, Strategy::kP2pPointToPoint);
+ EXPECT_NE(Strategy::kP2pCluster, Strategy::kP2pStar);
+ EXPECT_NE(Strategy::kP2pCluster, Strategy::kP2pPointToPoint);
+ EXPECT_NE(Strategy::kP2pStar, Strategy::kP2pPointToPoint);
+}
+
+TEST(StrategyTest, GetNameWorks) {
+ EXPECT_EQ(Strategy().GetName(), "UNKNOWN");
+ EXPECT_EQ(Strategy::kP2pCluster.GetName(), "P2P_CLUSTER");
+ EXPECT_EQ(Strategy::kP2pStar.GetName(), "P2P_STAR");
+ EXPECT_EQ(Strategy::kP2pPointToPoint.GetName(), "P2P_POINT_TO_POINT");
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/analytics/BUILD b/chromium/third_party/nearby/src/cpp/analytics/BUILD
deleted file mode 100644
index efb2063436b..00000000000
--- a/chromium/third_party/nearby/src/cpp/analytics/BUILD
+++ /dev/null
@@ -1,64 +0,0 @@
-licenses(["notice"])
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# https://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-cc_library(
- name = "analytics",
- srcs = [
- "analytics_recorder.cc",
- ],
- hdrs = [
- "analytics_recorder.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- copts = ["-DCORE_ADAPTER_DLL"],
- visibility = [
- "//core:__subpackages__",
- "//proto/analytics:__subpackages__",
- ],
- deps = [
- "//absl/container:btree",
- "//absl/time",
- "//core:core_types",
- "//core:event_logger",
- "//platform/base",
- "//platform/base:error_code_recorder",
- "//platform/public:logging",
- "//platform/public:types",
- "//proto:connections_enums_portable_proto",
- "//proto/analytics:connections_log_cc_proto",
- "//proto/errorcode:error_code_enums_portable_proto",
- ],
-)
-
-cc_test(
- name = "analytics_test",
- size = "small",
- srcs = [
- "analytics_recorder_test.cc",
- ],
- shard_count = 16,
- deps = [
- ":analytics",
- "//testing/base/public:gunit_main",
- "//absl/time",
- "//platform/base:error_code_recorder",
- "//platform/impl/g3", # build_cleaner: keep
- "//platform/public:comm",
- "//platform/public:logging",
- "//platform/public:types",
- "//proto:connections_enums_portable_proto",
- "//proto/analytics:connections_log_cc_proto",
- ],
-)
diff --git a/chromium/third_party/nearby/src/cpp/analytics/analytics_recorder.cc b/chromium/third_party/nearby/src/cpp/analytics/analytics_recorder.cc
deleted file mode 100644
index 6e1bbc46d53..00000000000
--- a/chromium/third_party/nearby/src/cpp/analytics/analytics_recorder.cc
+++ /dev/null
@@ -1,1113 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "analytics/analytics_recorder.h"
-
-#include <string>
-#include <utility>
-
-#include "absl/time/time.h"
-#include "platform/public/logging.h"
-#include "platform/public/mutex_lock.h"
-#include "platform/public/system_clock.h"
-#include "proto/analytics/connections_log.pb.h"
-#include "proto/connections_enums.pb.h"
-
-namespace location {
-namespace nearby {
-namespace analytics {
-
-namespace {
-const char kVersion[] = "v1.0.0";
-} // namespace
-
-using ::location::nearby::analytics::proto::ConnectionsLog;
-using ::location::nearby::proto::connections::ACCEPTED;
-using ::location::nearby::proto::connections::ADVERTISER;
-using ::location::nearby::proto::connections::BandwidthUpgradeErrorStage;
-using ::location::nearby::proto::connections::BandwidthUpgradeResult;
-using ::location::nearby::proto::connections::BYTES;
-using ::location::nearby::proto::connections::CLIENT_SESSION;
-using ::location::nearby::proto::connections::CONNECTION_CLOSED;
-using ::location::nearby::proto::connections::ConnectionAttemptDirection;
-using ::location::nearby::proto::connections::ConnectionAttemptResult;
-using ::location::nearby::proto::connections::ConnectionAttemptType;
-using ::location::nearby::proto::connections::ConnectionRequestResponse;
-using ::location::nearby::proto::connections::ConnectionsStrategy;
-using ::location::nearby::proto::connections::DisconnectionReason;
-using ::location::nearby::proto::connections::DISCOVERER;
-using ::location::nearby::proto::connections::EventType;
-using ::location::nearby::proto::connections::ERROR_CODE;
-using ::location::nearby::proto::connections::FILE;
-using ::location::nearby::proto::connections::IGNORED;
-using ::location::nearby::proto::connections::INCOMING;
-using ::location::nearby::proto::connections::INITIAL;
-using ::location::nearby::proto::connections::Medium;
-using ::location::nearby::proto::connections::MOVED_TO_NEW_MEDIUM;
-using ::location::nearby::proto::connections::NOT_SENT;
-using ::location::nearby::proto::connections::OUTGOING;
-using ::location::nearby::proto::connections::P2P_CLUSTER;
-using ::location::nearby::proto::connections::P2P_POINT_TO_POINT;
-using ::location::nearby::proto::connections::P2P_STAR;
-using ::location::nearby::proto::connections::PayloadStatus;
-using ::location::nearby::proto::connections::PayloadType;
-using ::location::nearby::proto::connections::REJECTED;
-using ::location::nearby::proto::connections::RESULT_SUCCESS;
-using ::location::nearby::proto::connections::SessionRole;
-using ::location::nearby::proto::connections::START_CLIENT_SESSION;
-using ::location::nearby::proto::connections::START_STRATEGY_SESSION;
-using ::location::nearby::proto::connections::STOP_CLIENT_SESSION;
-using ::location::nearby::proto::connections::STOP_STRATEGY_SESSION;
-using ::location::nearby::proto::connections::STREAM;
-using ::location::nearby::proto::connections::UNFINISHED;
-using ::location::nearby::proto::connections::UNFINISHED_ERROR;
-using ::location::nearby::proto::connections::UNKNOWN_MEDIUM;
-using ::location::nearby::proto::connections::UNKNOWN_PAYLOAD_TYPE;
-using ::location::nearby::proto::connections::UNKNOWN_STRATEGY;
-using ::location::nearby::proto::connections::UPGRADE_RESULT_SUCCESS;
-using ::location::nearby::proto::connections::UPGRADE_SUCCESS;
-using ::location::nearby::proto::connections::UPGRADE_UNFINISHED;
-using ::location::nearby::proto::connections::UPGRADED;
-
-AnalyticsRecorder::AnalyticsRecorder(EventLogger *event_logger)
- : event_logger_(event_logger) {
- started_client_session_time_ = SystemClock::ElapsedRealtime();
- NEARBY_LOGS(INFO) << "AnalyticsRecorder ctor event_logger_=" << event_logger_;
- MutexLock lock(&mutex_);
- if (CanRecordAnalyticsLocked("OnStartClientSession")) {
- LogEvent(START_CLIENT_SESSION);
- }
-}
-
-AnalyticsRecorder::~AnalyticsRecorder() {
- MutexLock lock(&mutex_);
- incoming_connection_requests_.clear();
- outgoing_connection_requests_.clear();
- active_connections_.clear();
- bandwidth_upgrade_attempts_.clear();
- serial_executor_.Shutdown();
-}
-
-void AnalyticsRecorder::OnStartAdvertising(connections::Strategy strategy,
- const std::vector<Medium> &mediums) {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("OnStartAdvertising")) {
- return;
- }
- if (!strategy.IsValid()) {
- NEARBY_LOGS(INFO) << "AnalyticsRecorder OnStartAdvertising with unknown "
- "strategy, bail out.";
- return;
- }
- // Initialize/update a StrategySession.
- UpdateStrategySessionLocked(strategy, ADVERTISER);
-
- // Initialize and set a AdvertisingPhase.
- started_advertising_phase_time_ = SystemClock::ElapsedRealtime();
- current_advertising_phase_ =
- absl::make_unique<ConnectionsLog::AdvertisingPhase>();
- absl::c_copy(mediums, RepeatedFieldBackInserter(
- current_advertising_phase_->mutable_medium()));
-}
-
-void AnalyticsRecorder::OnStopAdvertising() {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("OnStopAdvertising")) {
- return;
- }
- RecordAdvertisingPhaseDurationLocked();
-}
-
-void AnalyticsRecorder::OnStartDiscovery(connections::Strategy strategy,
- const std::vector<Medium> &mediums) {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("OnStartDiscovery")) {
- return;
- }
- if (!strategy.IsValid()) {
- NEARBY_LOGS(INFO) << "AnalyticsRecorder OnStartDiscovery unknown "
- "strategy enter, bail out.";
- return;
- }
-
- // Initialize/update a StrategySession.
- UpdateStrategySessionLocked(strategy, DISCOVERER);
-
- // Initialize and set a DiscoveryPhase.
- started_discovery_phase_time_ = SystemClock::ElapsedRealtime();
- current_discovery_phase_ =
- absl::make_unique<ConnectionsLog::DiscoveryPhase>();
- absl::c_copy(mediums, RepeatedFieldBackInserter(
- current_discovery_phase_->mutable_medium()));
-}
-
-void AnalyticsRecorder::OnStopDiscovery() {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("OnStopDiscovery")) {
- return;
- }
- RecordDiscoveryPhaseDurationLocked();
-}
-
-void AnalyticsRecorder::OnEndpointFound(Medium medium) {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("OnEndpointFound")) {
- return;
- }
- if (current_discovery_phase_ == nullptr) {
- NEARBY_LOGS(INFO) << "Unable to record discovered endpoint due to null "
- "current_discovery_phase_";
- return;
- }
- ConnectionsLog::DiscoveredEndpoint *discovered_endpoint =
- current_discovery_phase_->add_discovered_endpoint();
- discovered_endpoint->set_medium(medium);
- discovered_endpoint->set_latency_millis(absl::ToInt64Milliseconds(
- SystemClock::ElapsedRealtime() - started_discovery_phase_time_));
-}
-
-void AnalyticsRecorder::OnConnectionRequestReceived(
- const std::string &remote_endpoint_id) {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("OnConnectionRequestReceived")) {
- return;
- }
- absl::Time current_time = SystemClock::ElapsedRealtime();
- auto connection_request =
- absl::make_unique<ConnectionsLog::ConnectionRequest>();
- connection_request->set_duration_millis(absl::ToUnixMillis(current_time));
- connection_request->set_request_delay_millis(absl::ToInt64Milliseconds(
- current_time - started_advertising_phase_time_));
- incoming_connection_requests_.insert(
- {remote_endpoint_id, std::move(connection_request)});
-}
-
-void AnalyticsRecorder::OnConnectionRequestSent(
- const std::string &remote_endpoint_id) {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("OnConnectionRequestSent")) {
- return;
- }
- absl::Time current_time = SystemClock::ElapsedRealtime();
- auto connection_request =
- absl::make_unique<ConnectionsLog::ConnectionRequest>();
- connection_request->set_duration_millis(absl::ToUnixMillis(current_time));
- connection_request->set_request_delay_millis(
- absl::ToInt64Milliseconds(current_time - started_discovery_phase_time_));
- outgoing_connection_requests_.insert(
- {remote_endpoint_id, std::move(connection_request)});
-}
-
-void AnalyticsRecorder::OnRemoteEndpointAccepted(
- const std::string &remote_endpoint_id) {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("OnRemoteEndpointAccepted")) {
- return;
- }
- RemoteEndpointRespondedLocked(remote_endpoint_id, ACCEPTED);
-}
-
-void AnalyticsRecorder::OnLocalEndpointAccepted(
- const std::string &remote_endpoint_id) {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("OnLocalEndpointAccepted")) {
- return;
- }
- LocalEndpointRespondedLocked(remote_endpoint_id, ACCEPTED);
-}
-
-void AnalyticsRecorder::OnRemoteEndpointRejected(
- const std::string &remote_endpoint_id) {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("OnRemoteEndpointRejected")) {
- return;
- }
- RemoteEndpointRespondedLocked(remote_endpoint_id, REJECTED);
-}
-
-void AnalyticsRecorder::OnLocalEndpointRejected(
- const std::string &remote_endpoint_id) {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("OnLocalEndpointRejected")) {
- return;
- }
- LocalEndpointRespondedLocked(remote_endpoint_id, REJECTED);
-}
-
-void AnalyticsRecorder::OnIncomingConnectionAttempt(
- ConnectionAttemptType type, Medium medium, ConnectionAttemptResult result,
- absl::Duration duration, const std::string &connection_token) {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("OnIncomingConnectionAttempt")) {
- return;
- }
- if (current_strategy_session_ == nullptr) {
- NEARBY_LOGS(INFO) << "Unable to record incoming connection attempt due to "
- "null current_strategy_session_";
- return;
- }
- auto *connection_attempt =
- current_strategy_session_->add_connection_attempt();
- connection_attempt->set_duration_millis(absl::ToInt64Milliseconds(duration));
- connection_attempt->set_type(type);
- connection_attempt->set_direction(INCOMING);
- connection_attempt->set_medium(medium);
- connection_attempt->set_attempt_result(result);
- connection_attempt->set_connection_token(connection_token);
-}
-
-void AnalyticsRecorder::OnOutgoingConnectionAttempt(
- const std::string &remote_endpoint_id, ConnectionAttemptType type,
- Medium medium, ConnectionAttemptResult result, absl::Duration duration,
- const std::string &connection_token) {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("OnOutgoingConnectionAttempt")) {
- return;
- }
- if (current_strategy_session_ == nullptr) {
- NEARBY_LOGS(INFO) << "Unable to record outgoing connection attempt due to "
- "null current_strategy_session_";
- return;
- }
- auto *connection_attempt =
- current_strategy_session_->add_connection_attempt();
- connection_attempt->set_duration_millis(absl::ToInt64Milliseconds(duration));
- connection_attempt->set_type(type);
- connection_attempt->set_direction(OUTGOING);
- connection_attempt->set_medium(medium);
- connection_attempt->set_attempt_result(result);
- connection_attempt->set_connection_token(connection_token);
- if (type == INITIAL && result != RESULT_SUCCESS) {
- auto it = outgoing_connection_requests_.find(remote_endpoint_id);
- if (it != outgoing_connection_requests_.end()) {
- // An outgoing, initial ConnectionAttempt has a corresponding
- // ConnectionRequest that, since the ConnectionAttempt has failed, will
- // never be delivered to the advertiser.
- auto pair = outgoing_connection_requests_.extract(it);
- std::unique_ptr<ConnectionsLog::ConnectionRequest> &connection_request =
- pair.mapped();
- connection_request->set_local_response(NOT_SENT);
- connection_request->set_remote_response(NOT_SENT);
- UpdateDiscovererConnectionRequestLocked(connection_request.get());
- }
- }
-}
-
-void AnalyticsRecorder::OnConnectionEstablished(
- const std::string &endpoint_id, Medium medium,
- const std::string &connection_token) {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("OnConnectionEstablished")) {
- return;
- }
- auto it = active_connections_.find(endpoint_id);
- if (it != active_connections_.end()) {
- const std::unique_ptr<LogicalConnection> &logical_connection = it->second;
- logical_connection->PhysicalConnectionEstablished(medium, connection_token);
- } else {
- active_connections_.insert(
- {endpoint_id,
- absl::make_unique<LogicalConnection>(medium, connection_token)});
- }
-}
-
-void AnalyticsRecorder::OnConnectionClosed(const std::string &endpoint_id,
- Medium medium,
- DisconnectionReason reason) {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("OnConnectionClosed")) {
- return;
- }
- auto it = active_connections_.find(endpoint_id);
- if (it == active_connections_.end()) {
- return;
- }
- const std::unique_ptr<LogicalConnection> &logical_connection = it->second;
- logical_connection->PhysicalConnectionClosed(medium, reason);
- if (reason != UPGRADED) {
- // Unless this is an upgraded connection, remove this from our active
- // connections. Any future communication with an endpoint will need to be
- // re-established with a new ConnectionRequest.
- auto pair = active_connections_.extract(it);
- std::unique_ptr<LogicalConnection> &logical_connection = pair.mapped();
- absl::c_copy(
- logical_connection->GetEstablisedConnections(),
- RepeatedFieldBackInserter(
- current_strategy_session_->mutable_established_connection()));
- }
-}
-void AnalyticsRecorder::OnIncomingPayloadStarted(
- const std::string &endpoint_id, std::int64_t payload_id,
- connections::Payload::Type type, std::int64_t total_size_bytes) {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("OnIncomingPayloadStarted")) {
- return;
- }
- auto it = active_connections_.find(endpoint_id);
- if (it == active_connections_.end()) {
- return;
- }
- const std::unique_ptr<LogicalConnection> &logical_connection = it->second;
- logical_connection->IncomingPayloadStarted(
- payload_id, PayloadTypeToProtoPayloadType(type), total_size_bytes);
-}
-
-void AnalyticsRecorder::OnPayloadChunkReceived(const std::string &endpoint_id,
- std::int64_t payload_id,
- std::int64_t chunk_size_bytes) {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("OnPayloadChunkReceived")) {
- return;
- }
- auto it = active_connections_.find(endpoint_id);
- if (it == active_connections_.end()) {
- return;
- }
- const std::unique_ptr<LogicalConnection> &logical_connection = it->second;
- logical_connection->ChunkReceived(payload_id, chunk_size_bytes);
-}
-
-void AnalyticsRecorder::OnIncomingPayloadDone(const std::string &endpoint_id,
- std::int64_t payload_id,
- PayloadStatus status) {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("OnIncomingPayloadDone")) {
- return;
- }
- auto it = active_connections_.find(endpoint_id);
- if (it == active_connections_.end()) {
- return;
- }
- const std::unique_ptr<LogicalConnection> &logical_connection = it->second;
- logical_connection->IncomingPayloadDone(payload_id, status);
-}
-
-void AnalyticsRecorder::OnOutgoingPayloadStarted(
- const std::vector<std::string> &endpoint_ids, std::int64_t payload_id,
- connections::Payload::Type type, std::int64_t total_size_bytes) {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("OnOutgoingPayloadStarted")) {
- return;
- }
- for (const auto &endpoint_id : endpoint_ids) {
- auto it = active_connections_.find(endpoint_id);
- if (it == active_connections_.end()) {
- continue;
- }
- const std::unique_ptr<LogicalConnection> &logical_connection = it->second;
- logical_connection->OutgoingPayloadStarted(
- payload_id, PayloadTypeToProtoPayloadType(type), total_size_bytes);
- }
-}
-
-void AnalyticsRecorder::OnPayloadChunkSent(const std::string &endpoint_id,
- std::int64_t payload_id,
- std::int64_t chunk_size_bytes) {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("OnPayloadChunkSent")) {
- return;
- }
- auto it = active_connections_.find(endpoint_id);
- if (it == active_connections_.end()) {
- return;
- }
- const std::unique_ptr<LogicalConnection> &logical_connection = it->second;
- logical_connection->ChunkSent(payload_id, chunk_size_bytes);
-}
-
-void AnalyticsRecorder::OnOutgoingPayloadDone(const std::string &endpoint_id,
- std::int64_t payload_id,
- PayloadStatus status) {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("OnOutgoingPayloadDone")) {
- return;
- }
- auto it = active_connections_.find(endpoint_id);
- if (it == active_connections_.end()) {
- return;
- }
- const std::unique_ptr<LogicalConnection> &logical_connection = it->second;
- logical_connection->OutgoingPayloadDone(payload_id, status);
-}
-
-void AnalyticsRecorder::OnBandwidthUpgradeStarted(
- const std::string &endpoint_id, Medium from_medium, Medium to_medium,
- ConnectionAttemptDirection direction, const std::string &connection_token) {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("OnBandwidthUpgradeStarted")) {
- return;
- }
- auto bandwidth_upgrade_attempt =
- absl::make_unique<ConnectionsLog::BandwidthUpgradeAttempt>();
- bandwidth_upgrade_attempt->set_duration_millis(
- absl::ToUnixMillis(SystemClock::ElapsedRealtime()));
- bandwidth_upgrade_attempt->set_from_medium(from_medium);
- bandwidth_upgrade_attempt->set_to_medium(to_medium);
- bandwidth_upgrade_attempt->set_direction(direction);
- bandwidth_upgrade_attempt->set_connection_token(connection_token);
- bandwidth_upgrade_attempts_.insert(
- {endpoint_id, std::move(bandwidth_upgrade_attempt)});
-}
-
-void AnalyticsRecorder::OnBandwidthUpgradeError(
- const std::string &endpoint_id, BandwidthUpgradeResult result,
- BandwidthUpgradeErrorStage error_stage) {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("OnBandwidthUpgradeError")) {
- return;
- }
- FinishUpgradeAttemptLocked(endpoint_id, result, error_stage);
-}
-
-void AnalyticsRecorder::OnBandwidthUpgradeSuccess(
- const std::string &endpoint_id) {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("OnBandwidthUpgradeSuccess")) {
- return;
- }
- FinishUpgradeAttemptLocked(endpoint_id, UPGRADE_RESULT_SUCCESS,
- UPGRADE_SUCCESS);
-}
-
-void AnalyticsRecorder::OnErrorCode(const ErrorCodeParams& params) {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("OnErrorCode")) {
- return;
- }
- auto error_code = absl::make_unique<ConnectionsLog::ErrorCode>();
- error_code->set_medium(params.medium);
- error_code->set_event(params.event);
- error_code->set_connection_token(params.connection_token);
- error_code->set_description(params.description);
-
- if (params.is_common_error) {
- error_code->set_common_error(params.common_error);
- } else {
- switch (params.event) {
- case errorcode::proto::START_ADVERTISING:
- error_code->set_start_advertising_error(params.start_advertising_error);
- break;
- case errorcode::proto::STOP_ADVERTISING:
- error_code->set_stop_advertising_error(params.stop_advertising_error);
- break;
- case errorcode::proto::START_LISTENING_INCOMING_CONNECTION:
- error_code->set_start_listening_incoming_connection_error(
- params.start_listening_incoming_connection_error);
- break;
- case errorcode::proto::STOP_LISTENING_INCOMING_CONNECTION:
- error_code->set_stop_listening_incoming_connection_error(
- params.stop_listening_incoming_connection_error);
- break;
- case errorcode::proto::START_DISCOVERING:
- error_code->set_start_discovering_error(params.start_discovering_error);
- break;
- case errorcode::proto::STOP_DISCOVERING:
- error_code->set_stop_discovering_error(params.stop_discovering_error);
- break;
- case errorcode::proto::CONNECT:
- error_code->set_connect_error(params.connect_error);
- break;
- case errorcode::proto::DISCONNECT:
- error_code->set_disconnect_error(params.disconnect_error);
- break;
- case errorcode::proto::UNKNOWN_EVENT:
- default:
- error_code->set_common_error(params.common_error);
- break;
- }
- }
-
- serial_executor_.Execute(
- "analytics-recorder", [this, error_code = error_code.release()]() {
- ConnectionsLog connections_log;
- connections_log.set_event_type(ERROR_CODE);
- connections_log.set_version(kVersion);
- connections_log.set_allocated_error_code(error_code);
-
- NEARBY_LOGS(VERBOSE)
- << "AnalyticsRecorder LogErrorCode connections_log="
- << connections_log.DebugString();
-
- event_logger_->Log(connections_log);
- });
-}
-
-void AnalyticsRecorder::LogSession() {
- MutexLock lock(&mutex_);
- if (!CanRecordAnalyticsLocked("LogSession")) {
- return;
- }
- FinishStrategySessionLocked();
- client_session_->set_duration_millis(absl::ToInt64Milliseconds(
- SystemClock::ElapsedRealtime() - started_client_session_time_));
- LogClientSession();
- LogEvent(STOP_CLIENT_SESSION);
- session_was_logged_ = true;
-}
-
-bool AnalyticsRecorder::CanRecordAnalyticsLocked(
- const std::string &method_name) {
- NEARBY_LOGS(VERBOSE) << "AnalyticsRecorder LogEvent " << method_name
- << " is calling.";
- if (event_logger_ == nullptr) {
- NEARBY_LOGS(WARNING)
- << "AnalyticsRecorder CanRecordAnalytics Unexpected call "
- << method_name << " due to event_logger is null.";
- return false;
- }
-
- if (session_was_logged_) {
- NEARBY_LOGS(WARNING)
- << "AnalyticsRecorder CanRecordAnalytics Unexpected call "
- << method_name << " after session has already been logged.";
- return false;
- }
- return true;
-}
-
-void AnalyticsRecorder::LogClientSession() {
- serial_executor_.Execute(
- "analytics-recorder", [this]() {
- ConnectionsLog connections_log;
- connections_log.set_event_type(CLIENT_SESSION);
- connections_log.set_allocated_client_session(client_session_.release());
- connections_log.set_version(kVersion);
-
- NEARBY_LOGS(VERBOSE)
- << "AnalyticsRecorder LogClientSession connections_log="
- << connections_log.DebugString();
-
- event_logger_->Log(connections_log);
- });
-}
-
-void AnalyticsRecorder::LogEvent(EventType event_type) {
- serial_executor_.Execute("analytics-recorder", [this, event_type]() {
- ConnectionsLog connections_log;
- connections_log.set_event_type(event_type);
- connections_log.set_version(kVersion);
-
- NEARBY_LOGS(VERBOSE) << "AnalyticsRecorder LogEvent connections_log="
- << connections_log.DebugString();
-
- event_logger_->Log(connections_log);
- });
-}
-
-void AnalyticsRecorder::UpdateStrategySessionLocked(
- connections::Strategy strategy, SessionRole role) {
- // If we're not switching strategies, just update the current StrategySession
- // with the new role.
- if (strategy == current_strategy_) {
- if (absl::c_linear_search(current_strategy_session_->role(), role)) {
- // We've already acted as this role before, so make sure we've finished
- // recording the previous round.
- switch (role) {
- case ADVERTISER:
- FinishAdvertisingPhaseLocked();
- break;
- case DISCOVERER:
- FinishDiscoveryPhaseLocked();
- break;
- default:
- break;
- }
- } else {
- current_strategy_session_->add_role(role);
- }
- } else {
- // Otherwise, we're starting a new Strategy.
- current_strategy_ = strategy;
- FinishStrategySessionLocked();
- LogEvent(START_STRATEGY_SESSION);
- current_strategy_session_ =
- absl::make_unique<ConnectionsLog::StrategySession>();
- started_strategy_session_time_ = SystemClock::ElapsedRealtime();
- current_strategy_session_->set_strategy(
- StrategyToConnectionStrategy(strategy));
- current_strategy_session_->add_role(role);
- }
-}
-
-void AnalyticsRecorder::RecordAdvertisingPhaseDurationLocked() const {
- if (current_advertising_phase_ == nullptr) {
- NEARBY_LOGS(INFO) << "Unable to record advertising phase duration due to "
- "null current_advertising_phase_";
- return;
- }
- if (!current_advertising_phase_->has_duration_millis()) {
- current_advertising_phase_->set_duration_millis(absl::ToInt64Milliseconds(
- SystemClock::ElapsedRealtime() - started_advertising_phase_time_));
- }
-}
-
-void AnalyticsRecorder::FinishAdvertisingPhaseLocked() {
- if (current_advertising_phase_ != nullptr) {
- for (const auto &item : incoming_connection_requests_) {
- // ConnectionRequests still pending have been ignored by the local or
- // remote (or both) endpoints.
- const std::unique_ptr<ConnectionsLog::ConnectionRequest>
- &connection_request = item.second;
- MarkConnectionRequestIgnoredLocked(connection_request.get());
- UpdateAdvertiserConnectionRequestLocked(connection_request.get());
- }
- RecordAdvertisingPhaseDurationLocked();
- *current_strategy_session_->add_advertising_phase() =
- *std::move(current_advertising_phase_);
- }
- incoming_connection_requests_.clear();
-}
-
-void AnalyticsRecorder::RecordDiscoveryPhaseDurationLocked() const {
- if (current_discovery_phase_ == nullptr) {
- NEARBY_LOGS(INFO) << "Unable to record discovery phase duration due to "
- "null current_discovery_phase_";
- return;
- }
- if (!current_discovery_phase_->has_duration_millis()) {
- current_discovery_phase_->set_duration_millis(absl::ToInt64Milliseconds(
- SystemClock::ElapsedRealtime() - started_discovery_phase_time_));
- }
-}
-
-void AnalyticsRecorder::FinishDiscoveryPhaseLocked() {
- if (current_discovery_phase_ != nullptr) {
- for (const auto &item : outgoing_connection_requests_) {
- // ConnectionRequests still pending have been ignored by the local or
- // remote (or both) endpoints.
- const std::unique_ptr<ConnectionsLog::ConnectionRequest>
- &connection_request = item.second;
- MarkConnectionRequestIgnoredLocked(connection_request.get());
- UpdateDiscovererConnectionRequestLocked(connection_request.get());
- }
- RecordDiscoveryPhaseDurationLocked();
- *current_strategy_session_->add_discovery_phase() =
- *std::move(current_discovery_phase_);
- }
- outgoing_connection_requests_.clear();
-}
-
-bool AnalyticsRecorder::UpdateAdvertiserConnectionRequestLocked(
- ConnectionsLog::ConnectionRequest *request) {
- if (current_advertising_phase_ == nullptr) {
- NEARBY_LOGS(INFO)
- << "Unable to record advertiser connection request due to null "
- "current_advertising_phase_";
- return false;
- }
- if (BothEndpointsRespondedLocked(request)) {
- request->set_duration_millis(
- absl::ToUnixMillis(SystemClock::ElapsedRealtime()) -
- request->duration_millis());
- *current_advertising_phase_->add_received_connection_request() = *request;
- return true;
- }
- return false;
-}
-
-bool AnalyticsRecorder::UpdateDiscovererConnectionRequestLocked(
- ConnectionsLog::ConnectionRequest *request) {
- if (current_discovery_phase_ == nullptr) {
- NEARBY_LOGS(INFO) << "Unable to record discoverer connection request due "
- "to null current_discovery_phase_.";
- return false;
- }
- if (BothEndpointsRespondedLocked(request) ||
- request->local_response() == NOT_SENT) {
- request->set_duration_millis(
- absl::ToUnixMillis(SystemClock::ElapsedRealtime()) -
- request->duration_millis());
- *current_discovery_phase_->add_sent_connection_request() = *request;
- return true;
- }
- return false;
-}
-
-bool AnalyticsRecorder::BothEndpointsRespondedLocked(
- ConnectionsLog::ConnectionRequest *request) {
- return request->has_local_response() && request->has_remote_response();
-}
-
-void AnalyticsRecorder::LocalEndpointRespondedLocked(
- const std::string &remote_endpoint_id, ConnectionRequestResponse response) {
- auto out = outgoing_connection_requests_.find(remote_endpoint_id);
- if (out != outgoing_connection_requests_.end()) {
- ConnectionsLog::ConnectionRequest *connection_request = out->second.get();
- connection_request->set_local_response(response);
- if (UpdateDiscovererConnectionRequestLocked(connection_request)) {
- outgoing_connection_requests_.erase(out);
- }
- }
- auto in = incoming_connection_requests_.find(remote_endpoint_id);
- if (in != incoming_connection_requests_.end()) {
- ConnectionsLog::ConnectionRequest *connection_request = in->second.get();
- connection_request->set_local_response(response);
- if (UpdateAdvertiserConnectionRequestLocked(connection_request)) {
- incoming_connection_requests_.erase(in);
- }
- }
-}
-
-void AnalyticsRecorder::RemoteEndpointRespondedLocked(
- const std::string &remote_endpoint_id, ConnectionRequestResponse response) {
- auto out = outgoing_connection_requests_.find(remote_endpoint_id);
- if (out != outgoing_connection_requests_.end()) {
- ConnectionsLog::ConnectionRequest *connection_request = out->second.get();
- connection_request->set_remote_response(response);
- if (UpdateDiscovererConnectionRequestLocked(connection_request)) {
- outgoing_connection_requests_.erase(out);
- }
- }
- auto in = incoming_connection_requests_.find(remote_endpoint_id);
- if (in != incoming_connection_requests_.end()) {
- ConnectionsLog::ConnectionRequest *connection_request = in->second.get();
- connection_request->set_remote_response(response);
- if (UpdateAdvertiserConnectionRequestLocked(connection_request)) {
- incoming_connection_requests_.erase(in);
- }
- }
-}
-
-void AnalyticsRecorder::MarkConnectionRequestIgnoredLocked(
- ConnectionsLog::ConnectionRequest *request) {
- if (!request->has_local_response()) {
- request->set_local_response(IGNORED);
- }
- if (!request->has_remote_response()) {
- request->set_remote_response(IGNORED);
- }
-}
-
-void AnalyticsRecorder::FinishUpgradeAttemptLocked(
- const std::string &endpoint_id, BandwidthUpgradeResult result,
- BandwidthUpgradeErrorStage error_stage, bool erase_item) {
- if (current_strategy_session_ == nullptr) {
- NEARBY_LOGS(INFO) << "Unable to record upgrade attempt due to null "
- "current_strategy_session_";
- return;
- }
- // Add the BandwidthUpgradeAttempt in the current StrategySession.
- auto it = bandwidth_upgrade_attempts_.find(endpoint_id);
- if (it != bandwidth_upgrade_attempts_.end()) {
- ConnectionsLog::BandwidthUpgradeAttempt *attempt = it->second.get();
- attempt->set_duration_millis(
- absl::ToUnixMillis(SystemClock::ElapsedRealtime()) -
- attempt->duration_millis());
- attempt->set_error_stage(error_stage);
- attempt->set_upgrade_result(result);
- *current_strategy_session_->add_upgrade_attempt() = *attempt;
- if (erase_item) {
- bandwidth_upgrade_attempts_.erase(it);
- }
- }
-}
-
-void AnalyticsRecorder::FinishStrategySessionLocked() {
- if (current_strategy_session_ != nullptr) {
- FinishAdvertisingPhaseLocked();
- FinishDiscoveryPhaseLocked();
-
- // Finish any unfinished LogicalConnections.
- for (const auto &item : active_connections_) {
- const std::unique_ptr<LogicalConnection> &logical_connection =
- item.second;
- logical_connection->CloseAllPhysicalConnections();
- absl::c_copy(
- logical_connection->GetEstablisedConnections(),
- RepeatedFieldBackInserter(
- current_strategy_session_->mutable_established_connection()));
- }
- active_connections_.clear();
-
- // Finish any pending upgrade attempts.
- for (const auto &item : bandwidth_upgrade_attempts_) {
- FinishUpgradeAttemptLocked(item.first, UNFINISHED_ERROR,
- UPGRADE_UNFINISHED, /*erase_item=*/false);
- }
- bandwidth_upgrade_attempts_.clear();
-
- // Add the StrategySession in ClientSession
- current_strategy_session_->set_duration_millis(absl::ToInt64Milliseconds(
- started_strategy_session_time_ - SystemClock::ElapsedRealtime()));
- *client_session_->add_strategy_session() =
- *std::move(current_strategy_session_);
- LogEvent(STOP_STRATEGY_SESSION);
- }
-}
-
-ConnectionsStrategy AnalyticsRecorder::StrategyToConnectionStrategy(
- connections::Strategy strategy) {
- if (strategy == connections::Strategy::kP2pCluster) {
- return P2P_CLUSTER;
- }
- if (strategy == connections::Strategy::kP2pStar) {
- return P2P_STAR;
- }
- if (strategy == connections::Strategy::kP2pPointToPoint) {
- return P2P_POINT_TO_POINT;
- }
- return UNKNOWN_STRATEGY;
-}
-
-PayloadType AnalyticsRecorder::PayloadTypeToProtoPayloadType(
- connections::Payload::Type type) {
- switch (type) {
- case connections::Payload::Type::kBytes:
- return BYTES;
- case connections::Payload::Type::kFile:
- return FILE;
- case connections::Payload::Type::kStream:
- return STREAM;
- default:
- return UNKNOWN_PAYLOAD_TYPE;
- }
-}
-
-void AnalyticsRecorder::PendingPayload::AddChunk(
- std::int64_t chunk_size_bytes) {
- num_bytes_transferred_ += chunk_size_bytes;
- num_chunks_++;
-}
-
-ConnectionsLog::Payload AnalyticsRecorder::PendingPayload::GetProtoPayload(
- PayloadStatus status) {
- ConnectionsLog::Payload payload;
- payload.set_duration_millis(
- absl::ToInt64Milliseconds(SystemClock::ElapsedRealtime() - start_time_));
- payload.set_type(type_);
- payload.set_total_size_bytes(total_size_bytes_);
- payload.set_num_bytes_transferred(num_bytes_transferred_);
- payload.set_num_chunks(num_chunks_);
- payload.set_status(status);
-
- return payload;
-}
-
-void AnalyticsRecorder::LogicalConnection::PhysicalConnectionEstablished(
- Medium medium, const std::string &connection_token) {
- if (current_medium_ != UNKNOWN_MEDIUM) {
- NEARBY_LOGS(WARNING)
- << "Unexpected call to PhysicalConnectionEstablished while "
- "AnalyticsRecorder still has an active current medium.";
- }
-
- auto established_connection =
- absl::make_unique<ConnectionsLog::EstablishedConnection>();
- established_connection->set_medium(medium);
- established_connection->set_duration_millis(
- absl::ToUnixMillis(SystemClock::ElapsedRealtime()));
- established_connection->set_connection_token(connection_token);
- physical_connections_.insert({medium, std::move(established_connection)});
- current_medium_ = medium;
-}
-
-void AnalyticsRecorder::LogicalConnection::PhysicalConnectionClosed(
- Medium medium, DisconnectionReason reason) {
- if (current_medium_ == UNKNOWN_MEDIUM) {
- NEARBY_LOGS(WARNING)
- << "Unexpected call to PhysicalConnectionClosed() for medium "
- << Medium_Name(medium)
- << " while AnalyticsRecorder has no active current medium";
- } else if (current_medium_ != medium) {
- NEARBY_LOGS(WARNING)
- << "Unexpected call to PhysicalConnectionClosed() for medium "
- << Medium_Name(medium) << "while AnalyticsRecorder has active medium "
- << Medium_Name(current_medium_);
- }
-
- auto it = physical_connections_.find(medium);
- if (it == physical_connections_.end()) {
- NEARBY_LOGS(WARNING)
- << "Unexpected call to physicalConnectionClosed() for medium "
- << Medium_Name(medium)
- << " with no corresponding EstablishedConnection that was previously"
- " opened.";
- return;
- }
- ConnectionsLog::EstablishedConnection *established_connection =
- it->second.get();
- if (established_connection->has_disconnection_reason()) {
- NEARBY_LOGS(WARNING)
- << "Unexpected call to physicalConnectionClosed() for medium "
- << Medium_Name(medium) << " which already has disconnection reason "
- << DisconnectionReason_Name(
- established_connection->disconnection_reason());
- return;
- }
- FinishPhysicalConnection(established_connection, reason);
-
- if (medium == current_medium_) {
- // If the EstablishedConnection we just closed was the one that we have
- // marked as current, unset currentMedium.
- current_medium_ = UNKNOWN_MEDIUM;
- }
-}
-
-void AnalyticsRecorder::LogicalConnection::CloseAllPhysicalConnections() {
- for (const auto &physical_connection : physical_connections_) {
- ConnectionsLog::EstablishedConnection *established_connection =
- physical_connection.second.get();
- if (!established_connection->has_disconnection_reason()) {
- FinishPhysicalConnection(established_connection, UNFINISHED);
- }
- }
- current_medium_ = UNKNOWN_MEDIUM;
-}
-
-std::vector<ConnectionsLog::EstablishedConnection>
-AnalyticsRecorder::LogicalConnection::GetEstablisedConnections() {
- std::vector<ConnectionsLog::EstablishedConnection> established_connections;
- if (current_medium_ != UNKNOWN_MEDIUM) {
- NEARBY_LOGS(WARNING)
- << "AnalyticsRecorder expected no more active physical connections "
- "before logging this endpoint connection.";
- return established_connections;
- }
- std::transform(physical_connections_.begin(), physical_connections_.end(),
- std::back_inserter(established_connections),
- [](auto &kv) { return *kv.second; });
- physical_connections_.clear();
- return established_connections;
-}
-
-void AnalyticsRecorder::LogicalConnection::IncomingPayloadStarted(
- std::int64_t payload_id, PayloadType type, std::int64_t total_size_bytes) {
- incoming_payloads_.insert(
- {payload_id, absl::make_unique<PendingPayload>(type, total_size_bytes)});
-}
-
-void AnalyticsRecorder::LogicalConnection::ChunkReceived(
- std::int64_t payload_id, std::int64_t size_bytes) {
- auto it = incoming_payloads_.find(payload_id);
- if (it == incoming_payloads_.end()) {
- return;
- }
- PendingPayload *pending_payload = it->second.get();
- pending_payload->AddChunk(size_bytes);
-}
-
-void AnalyticsRecorder::LogicalConnection::IncomingPayloadDone(
- std::int64_t payload_id, PayloadStatus status) {
- if (current_medium_ == UNKNOWN_MEDIUM) {
- NEARBY_LOGS(WARNING) << "Unexpected call to incomingPayloadDone() while "
- "AnalyticsRecorder has no active current medium.";
- return;
- }
- auto it = physical_connections_.find(current_medium_);
- if (it != physical_connections_.end()) {
- const std::unique_ptr<ConnectionsLog::EstablishedConnection>
- &established_connection = it->second;
- auto it = incoming_payloads_.find(payload_id);
- if (it != incoming_payloads_.end()) {
- *established_connection->add_received_payload() =
- it->second->GetProtoPayload(status);
- incoming_payloads_.erase(it);
- }
- }
-}
-
-void AnalyticsRecorder::LogicalConnection::OutgoingPayloadStarted(
- std::int64_t payload_id, PayloadType type, std::int64_t total_size_bytes) {
- outgoing_payloads_.insert(
- {payload_id, absl::make_unique<PendingPayload>(type, total_size_bytes)});
-}
-
-void AnalyticsRecorder::LogicalConnection::ChunkSent(std::int64_t payload_id,
- std::int64_t size_bytes) {
- auto it = outgoing_payloads_.find(payload_id);
- if (it == outgoing_payloads_.end()) {
- return;
- }
- PendingPayload *payload = it->second.get();
- payload->AddChunk(size_bytes);
-}
-
-void AnalyticsRecorder::LogicalConnection::OutgoingPayloadDone(
- std::int64_t payload_id, PayloadStatus status) {
- if (current_medium_ == UNKNOWN_MEDIUM) {
- NEARBY_LOGS(WARNING) << "Unexpected call to outgoingPayloadDone() while "
- "AnalyticsRecorder has no active current medium.";
- return;
- }
- auto it = physical_connections_.find(current_medium_);
- if (it != physical_connections_.end()) {
- const std::unique_ptr<ConnectionsLog::EstablishedConnection>
- &established_connection = it->second;
- auto it = outgoing_payloads_.find(payload_id);
- if (it != outgoing_payloads_.end()) {
- *established_connection->add_sent_payload() =
- it->second->GetProtoPayload(status);
- outgoing_payloads_.erase(it);
- }
- }
-}
-
-void AnalyticsRecorder::LogicalConnection::FinishPhysicalConnection(
- ConnectionsLog::EstablishedConnection *established_connection,
- DisconnectionReason reason) {
- established_connection->set_disconnection_reason(reason);
- established_connection->set_duration_millis(
- absl::ToUnixMillis(SystemClock::ElapsedRealtime()) -
- established_connection->duration_millis());
-
- // Add any not-yet-finished payloads to this EstablishedConnection.
- std::vector<ConnectionsLog::Payload> in_payloads =
- ResolvePendingPayloads(incoming_payloads_, reason);
- absl::c_move(in_payloads,
- RepeatedFieldBackInserter(
- established_connection->mutable_received_payload()));
- std::vector<ConnectionsLog::Payload> out_payloads =
- ResolvePendingPayloads(outgoing_payloads_, reason);
- absl::c_move(out_payloads,
- RepeatedFieldBackInserter(
- established_connection->mutable_sent_payload()));
-}
-
-std::vector<ConnectionsLog::Payload>
-AnalyticsRecorder::LogicalConnection::ResolvePendingPayloads(
- absl::btree_map<std::int64_t, std::unique_ptr<PendingPayload>>
- &pending_payloads,
- DisconnectionReason reason) {
- std::vector<ConnectionsLog::Payload> completed_payloads;
- absl::btree_map<std::int64_t, std::unique_ptr<PendingPayload>>
- upgraded_payloads;
- PayloadStatus status =
- reason == UPGRADED ? MOVED_TO_NEW_MEDIUM : CONNECTION_CLOSED;
- for (const auto &item : pending_payloads) {
- const std::unique_ptr<PendingPayload> &pending_payload = item.second;
- ConnectionsLog::Payload proto_payload =
- pending_payload->GetProtoPayload(status);
- completed_payloads.push_back(proto_payload);
- if (reason == UPGRADED) {
- upgraded_payloads.insert(
- {item.first,
- absl::make_unique<PendingPayload>(
- pending_payload->type(), pending_payload->total_size_bytes())});
- }
- }
- pending_payloads.clear();
-
- if (reason == UPGRADED) {
- // Re-populate the map with a new PendingPayload for each pending payload,
- // since we expect them to be completed on the next EstablishedConnection.
- pending_payloads = std::move(upgraded_payloads);
- }
- // Return the list of completed payloads to be added to the current
- // EstablishedConnection.
- return completed_payloads;
-}
-
-} // namespace analytics
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/analytics/analytics_recorder.h b/chromium/third_party/nearby/src/cpp/analytics/analytics_recorder.h
deleted file mode 100644
index 55f09a475ee..00000000000
--- a/chromium/third_party/nearby/src/cpp/analytics/analytics_recorder.h
+++ /dev/null
@@ -1,347 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef ANALYTICS_ANALYTICS_RECORDER_H_
-#define ANALYTICS_ANALYTICS_RECORDER_H_
-
-#include <string>
-
-#include "absl/container/btree_map.h"
-#include "absl/time/time.h"
-#include "core/event_logger.h"
-#include "core/payload.h"
-#include "core/strategy.h"
-#include "platform/base/error_code_params.h"
-#include "platform/public/mutex.h"
-#include "platform/public/single_thread_executor.h"
-#include "proto/analytics/connections_log.pb.h"
-#include "proto/connections_enums.pb.h"
-
-namespace location {
-namespace nearby {
-namespace analytics {
-
-class AnalyticsRecorder {
- public:
- explicit AnalyticsRecorder(EventLogger *event_logger);
- virtual ~AnalyticsRecorder();
-
- // Advertising phase
- void OnStartAdvertising(
- connections::Strategy strategy,
- const std::vector<location::nearby::proto::connections::Medium> &mediums)
- ABSL_LOCKS_EXCLUDED(mutex_);
- void OnStopAdvertising() ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Discovery phase
- void OnStartDiscovery(
- connections::Strategy strategy,
- const std::vector<location::nearby::proto::connections::Medium> &mediums)
- ABSL_LOCKS_EXCLUDED(mutex_);
- void OnStopDiscovery() ABSL_LOCKS_EXCLUDED(mutex_);
- void OnEndpointFound(location::nearby::proto::connections::Medium medium)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Connection request
- void OnConnectionRequestReceived(const std::string &remote_endpoint_id)
- ABSL_LOCKS_EXCLUDED(mutex_);
- void OnConnectionRequestSent(const std::string &remote_endpoint_id)
- ABSL_LOCKS_EXCLUDED(mutex_);
- void OnRemoteEndpointAccepted(const std::string &remote_endpoint_id)
- ABSL_LOCKS_EXCLUDED(mutex_);
- void OnLocalEndpointAccepted(const std::string &remote_endpoint_id)
- ABSL_LOCKS_EXCLUDED(mutex_);
- void OnRemoteEndpointRejected(const std::string &remote_endpoint_id)
- ABSL_LOCKS_EXCLUDED(mutex_);
- void OnLocalEndpointRejected(const std::string &remote_endpoint_id)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Connection attempt
- void OnIncomingConnectionAttempt(
- location::nearby::proto::connections::ConnectionAttemptType type,
- location::nearby::proto::connections::Medium medium,
- location::nearby::proto::connections::ConnectionAttemptResult result,
- absl::Duration duration, const std::string &connection_token)
- ABSL_LOCKS_EXCLUDED(mutex_);
- void OnOutgoingConnectionAttempt(
- const std::string &remote_endpoint_id,
- location::nearby::proto::connections::ConnectionAttemptType type,
- location::nearby::proto::connections::Medium medium,
- location::nearby::proto::connections::ConnectionAttemptResult result,
- absl::Duration duration, const std::string &connection_token)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Connection established
- void OnConnectionEstablished(
- const std::string &endpoint_id,
- location::nearby::proto::connections::Medium medium,
- const std::string &connection_token) ABSL_LOCKS_EXCLUDED(mutex_);
- void OnConnectionClosed(
- const std::string &endpoint_id,
- location::nearby::proto::connections::Medium medium,
- location::nearby::proto::connections ::DisconnectionReason reason)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Payload
- void OnIncomingPayloadStarted(const std::string &endpoint_id,
- std::int64_t payload_id,
- connections::Payload::Type type,
- std::int64_t total_size_bytes)
- ABSL_LOCKS_EXCLUDED(mutex_);
- void OnPayloadChunkReceived(const std::string &endpoint_id,
- std::int64_t payload_id,
- std::int64_t chunk_size_bytes)
- ABSL_LOCKS_EXCLUDED(mutex_);
- void OnIncomingPayloadDone(
- const std::string &endpoint_id, std::int64_t payload_id,
- location::nearby::proto::connections::PayloadStatus status)
- ABSL_LOCKS_EXCLUDED(mutex_);
- void OnOutgoingPayloadStarted(const std::vector<std::string> &endpoint_ids,
- std::int64_t payload_id,
- connections::Payload::Type type,
- std::int64_t total_size_bytes)
- ABSL_LOCKS_EXCLUDED(mutex_);
- void OnPayloadChunkSent(const std::string &endpoint_id,
- std::int64_t payload_id,
- std::int64_t chunk_size_bytes)
- ABSL_LOCKS_EXCLUDED(mutex_);
- void OnOutgoingPayloadDone(
- const std::string &endpoint_id, std::int64_t payload_id,
- location::nearby::proto::connections::PayloadStatus status)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // BandwidthUpgrade
- void OnBandwidthUpgradeStarted(
- const std::string &endpoint_id,
- location::nearby::proto::connections::Medium from_medium,
- location::nearby::proto::connections::Medium to_medium,
- location::nearby::proto::connections::ConnectionAttemptDirection
- direction,
- const std::string &connection_token) ABSL_LOCKS_EXCLUDED(mutex_);
- void OnBandwidthUpgradeError(
- const std::string &endpoint_id,
- location::nearby::proto::connections::BandwidthUpgradeResult result,
- location::nearby::proto::connections::BandwidthUpgradeErrorStage
- error_stage) ABSL_LOCKS_EXCLUDED(mutex_);
- void OnBandwidthUpgradeSuccess(const std::string &endpoint_id)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Error Code
- void OnErrorCode(const ErrorCodeParams &params);
-
- // Invokes event_logger_.Log() at the end of life of client. Log action is
- // called in a separate thread to allow synchronous potentially lengthy
- // execution.
- void LogSession() ABSL_LOCKS_EXCLUDED(mutex_);
-
- private:
- // Tracks the chunks and duration of a Payload on a particular medium.
- class PendingPayload {
- public:
- PendingPayload(location::nearby::proto::connections::PayloadType type,
- std::int64_t total_size_bytes)
- : start_time_(SystemClock::ElapsedRealtime()),
- type_(type),
- total_size_bytes_(total_size_bytes),
- num_bytes_transferred_(0),
- num_chunks_(0) {}
- ~PendingPayload() = default;
-
- void AddChunk(std::int64_t chunk_size_bytes);
-
- proto::ConnectionsLog::Payload GetProtoPayload(
- location::nearby::proto::connections::PayloadStatus status);
-
- location::nearby::proto::connections::PayloadType type() const {
- return type_;
- }
-
- std::int64_t total_size_bytes() const { return total_size_bytes_; }
-
- private:
- absl::Time start_time_;
- location::nearby::proto::connections::PayloadType type_;
- std::int64_t total_size_bytes_;
- std::int64_t num_bytes_transferred_;
- int num_chunks_;
- };
-
- class LogicalConnection {
- public:
- LogicalConnection(
- location::nearby::proto::connections::Medium initial_medium,
- const std::string &connection_token) {
- PhysicalConnectionEstablished(initial_medium, connection_token);
- }
- LogicalConnection(const LogicalConnection &) = delete;
- LogicalConnection(LogicalConnection &&other)
- : current_medium_(std::move(other.current_medium_)),
- physical_connections_(std::move(other.physical_connections_)),
- incoming_payloads_(std::move(other.incoming_payloads_)),
- outgoing_payloads_(std::move(other.outgoing_payloads_)) {}
- LogicalConnection &operator=(const LogicalConnection &) = delete;
- LogicalConnection &&operator=(LogicalConnection &&) = delete;
- ~LogicalConnection() = default;
-
- void PhysicalConnectionEstablished(
- location::nearby::proto::connections::Medium medium,
- const std::string &connection_token);
- void PhysicalConnectionClosed(
- location::nearby::proto::connections::Medium medium,
- location::nearby::proto::connections::DisconnectionReason reason);
- void CloseAllPhysicalConnections();
-
- void IncomingPayloadStarted(
- std::int64_t payload_id,
- location::nearby::proto::connections::PayloadType type,
- std::int64_t total_size_bytes);
- void ChunkReceived(std::int64_t payload_id, std::int64_t size_bytes);
- void IncomingPayloadDone(
- std::int64_t payload_id,
- location::nearby::proto::connections::PayloadStatus status);
- void OutgoingPayloadStarted(
- std::int64_t payload_id,
- location::nearby::proto::connections::PayloadType type,
- std::int64_t total_size_bytes);
- void ChunkSent(std::int64_t payload_id, std::int64_t size_bytes);
- void OutgoingPayloadDone(
- std::int64_t payload_id,
- location::nearby::proto::connections::PayloadStatus status);
-
- std::vector<proto::ConnectionsLog::EstablishedConnection>
- GetEstablisedConnections();
-
- private:
- void FinishPhysicalConnection(
- proto::ConnectionsLog::EstablishedConnection *established_connection,
- location::nearby::proto::connections::DisconnectionReason reason);
- std::vector<proto::ConnectionsLog::Payload> ResolvePendingPayloads(
- absl::btree_map<std::int64_t, std::unique_ptr<PendingPayload>>
- &pending_payloads,
- location::nearby::proto::connections::DisconnectionReason reason);
-
- location::nearby::proto::connections::Medium current_medium_ =
- location::nearby::proto::connections::UNKNOWN_MEDIUM;
- absl::btree_map<
- location::nearby::proto::connections::Medium,
- std::unique_ptr<proto::ConnectionsLog::EstablishedConnection>>
- physical_connections_;
- absl::btree_map<std::int64_t, std::unique_ptr<PendingPayload>>
- incoming_payloads_;
- absl::btree_map<std::int64_t, std::unique_ptr<PendingPayload>>
- outgoing_payloads_;
- };
-
- bool CanRecordAnalyticsLocked(const std::string &method_name)
- ABSL_SHARED_LOCKS_REQUIRED(mutex_);
-
- // Callbacks the ConnectionsLog proto byte array data to the EventLogger with
- // ClientSession sub-proto.
- void LogClientSession();
- // Callbacks the ConnectionsLog proto byte array data to the EventLogger.
- void LogEvent(location::nearby::proto::connections::EventType event_type);
-
- void UpdateStrategySessionLocked(
- connections::Strategy strategy,
- location::nearby::proto::connections::SessionRole role)
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
- void RecordAdvertisingPhaseDurationLocked() const
- ABSL_SHARED_LOCKS_REQUIRED(mutex_);
- void FinishAdvertisingPhaseLocked() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
- void RecordDiscoveryPhaseDurationLocked() const
- ABSL_SHARED_LOCKS_REQUIRED(mutex_);
- void FinishDiscoveryPhaseLocked() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
- bool UpdateAdvertiserConnectionRequestLocked(
- proto::ConnectionsLog::ConnectionRequest *request)
- ABSL_SHARED_LOCKS_REQUIRED(mutex_);
- bool UpdateDiscovererConnectionRequestLocked(
- proto::ConnectionsLog::ConnectionRequest *request)
- ABSL_SHARED_LOCKS_REQUIRED(mutex_);
- bool BothEndpointsRespondedLocked(
- proto::ConnectionsLog::ConnectionRequest *request)
- ABSL_SHARED_LOCKS_REQUIRED(mutex_);
- void LocalEndpointRespondedLocked(
- const std::string &remote_endpoint_id,
- location::nearby::proto::connections::ConnectionRequestResponse response)
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
- void RemoteEndpointRespondedLocked(
- const std::string &remote_endpoint_id,
- location::nearby::proto::connections::ConnectionRequestResponse response)
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
- void MarkConnectionRequestIgnoredLocked(
- proto::ConnectionsLog::ConnectionRequest *request)
- ABSL_SHARED_LOCKS_REQUIRED(mutex_);
- void FinishUpgradeAttemptLocked(
- const std::string &endpoint_id,
- location::nearby::proto::connections::BandwidthUpgradeResult result,
- location::nearby::proto::connections::BandwidthUpgradeErrorStage
- error_stage,
- bool erase_item = true) ABSL_SHARED_LOCKS_REQUIRED(mutex_);
- void FinishStrategySessionLocked() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- location::nearby::proto::connections::ConnectionsStrategy
- StrategyToConnectionStrategy(connections::Strategy strategy);
- location::nearby::proto::connections::PayloadType
- PayloadTypeToProtoPayloadType(connections::Payload::Type type);
-
- // Not owned by AnalyticsRecorder. Pointer must refer to a valid object
- // that outlives the one constructed.
- EventLogger *event_logger_;
-
- SingleThreadExecutor serial_executor_;
- // Protects all sub-protos reading and writing in ConnectionLog.
- Mutex mutex_;
-
- // ClientSession
- std::unique_ptr<proto::ConnectionsLog::ClientSession> client_session_ =
- absl::make_unique<proto::ConnectionsLog::ClientSession>();
- absl::Time started_client_session_time_;
- bool session_was_logged_ ABSL_GUARDED_BY(mutex_) = false;
-
- // Current StrategySession
- connections::Strategy current_strategy_ ABSL_GUARDED_BY(mutex_) =
- connections::Strategy::kNone;
- std::unique_ptr<proto::ConnectionsLog::StrategySession>
- current_strategy_session_ ABSL_GUARDED_BY(mutex_);
- absl::Time started_strategy_session_time_ ABSL_GUARDED_BY(mutex_);
-
- // Current AdvertisingPhase
- std::unique_ptr<proto::ConnectionsLog::AdvertisingPhase>
- current_advertising_phase_;
- absl::Time started_advertising_phase_time_;
-
- // Current DiscoveryPhase
- std::unique_ptr<proto::ConnectionsLog::DiscoveryPhase>
- current_discovery_phase_;
- absl::Time started_discovery_phase_time_;
-
- absl::btree_map<std::string,
- std::unique_ptr<proto::ConnectionsLog::ConnectionRequest>>
- incoming_connection_requests_ ABSL_GUARDED_BY(mutex_);
- absl::btree_map<std::string,
- std::unique_ptr<proto::ConnectionsLog::ConnectionRequest>>
- outgoing_connection_requests_ ABSL_GUARDED_BY(mutex_);
- absl::btree_map<std::string, std::unique_ptr<LogicalConnection>>
- active_connections_ ABSL_GUARDED_BY(mutex_);
- absl::btree_map<
- std::string,
- std::unique_ptr<proto::ConnectionsLog::BandwidthUpgradeAttempt>>
- bandwidth_upgrade_attempts_ ABSL_GUARDED_BY(mutex_);
-};
-
-} // namespace analytics
-} // namespace nearby
-} // namespace location
-
-#endif // ANALYTICS_ANALYTICS_RECORDER_H_
diff --git a/chromium/third_party/nearby/src/cpp/analytics/analytics_recorder_test.cc b/chromium/third_party/nearby/src/cpp/analytics/analytics_recorder_test.cc
deleted file mode 100644
index d356833a523..00000000000
--- a/chromium/third_party/nearby/src/cpp/analytics/analytics_recorder_test.cc
+++ /dev/null
@@ -1,770 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "analytics/analytics_recorder.h"
-
-#include <string>
-#include <utility>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/time/time.h"
-#include "platform/base/error_code_params.h"
-#include "platform/base/error_code_recorder.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/logging.h"
-#include "proto/analytics/connections_log.pb.h"
-#include "proto/connections_enums.pb.h"
-
-namespace location {
-namespace nearby {
-namespace analytics {
-namespace {
-
-using ::location::nearby::analytics::proto::ConnectionsLog;
-using ::location::nearby::errorcode::proto::DISCONNECT;
-using ::location::nearby::errorcode::proto::DISCONNECT_NETWORK_FAILED;
-using ::location::nearby::errorcode::proto::INVALID_PARAMETER;
-using ::location::nearby::errorcode::proto::NULL_BLUETOOTH_DEVICE_NAME;
-using ::location::nearby::errorcode::proto::START_DISCOVERING;
-using ::location::nearby::errorcode::proto::START_EXTENDED_DISCOVERING_FAILED;
-using ::location::nearby::errorcode::proto::
- TACHYON_SEND_MESSAGE_STATUS_EXCEPTION;
-using ::location::nearby::proto::connections::BLE;
-using ::location::nearby::proto::connections::BLUETOOTH;
-using ::location::nearby::proto::connections::CLIENT_SESSION;
-using ::location::nearby::proto::connections::ERROR_CODE;
-using ::location::nearby::proto::connections::EventType;
-using ::location::nearby::proto::connections::INCOMING;
-using ::location::nearby::proto::connections::INITIAL;
-using ::location::nearby::proto::connections::LOCAL_DISCONNECTION;
-using ::location::nearby::proto::connections::Medium;
-using ::location::nearby::proto::connections::RESULT_ERROR;
-using ::location::nearby::proto::connections::RESULT_SUCCESS;
-using ::location::nearby::proto::connections::START_STRATEGY_SESSION;
-using ::location::nearby::proto::connections::STOP_CLIENT_SESSION;
-using ::location::nearby::proto::connections::STOP_STRATEGY_SESSION;
-using ::location::nearby::proto::connections::SUCCESS;
-using ::location::nearby::proto::connections::UPGRADED;
-using ::location::nearby::proto::connections::WEB_RTC;
-using ::location::nearby::proto::connections::WIFI_LAN;
-using ::location::nearby::proto::connections::WIFI_LAN_MEDIUM_ERROR;
-using ::location::nearby::proto::connections::WIFI_LAN_SOCKET_CREATION;
-
-using ::testing::Contains;
-using ::testing::EqualsProto;
-using ::testing::proto::Partially;
-
-constexpr absl::Duration kDefaultTimeout = absl::Milliseconds(1000);
-
-class FakeEventLogger : public EventLogger {
- public:
- explicit FakeEventLogger(CountDownLatch& client_session_done_latch)
- : client_session_done_latch_(client_session_done_latch) {}
-
- void Log(const ConnectionsLog& connections_log) override {
- EventType event_type = connections_log.event_type();
- logged_event_types_.push_back(event_type);
- if (event_type == CLIENT_SESSION) {
- logged_client_session_count_++;
- logged_client_session_ = connections_log.client_session();
- }
- if (event_type == ERROR_CODE) {
- error_code_ = connections_log.error_code();
- }
- if (event_type == STOP_CLIENT_SESSION) {
- client_session_done_latch_.CountDown();
- }
- }
-
- int GetLoggedClientSessionCount() const {
- return logged_client_session_count_;
- }
-
- const ConnectionsLog::ClientSession& GetLoggedClientSession() {
- return logged_client_session_;
- }
-
- const ConnectionsLog::ErrorCode& GetErrorCode() { return error_code_; }
-
- std::vector<EventType> GetLoggedEventTypes() { return logged_event_types_; }
-
- private:
- int logged_client_session_count_ = 0;
- CountDownLatch& client_session_done_latch_;
- ConnectionsLog::ClientSession logged_client_session_;
- ConnectionsLog::ErrorCode error_code_;
- std::vector<EventType> logged_event_types_;
-};
-
-TEST(AnalyticsRecorderTest, SessionOnlyLoggedOnceWorks) {
- CountDownLatch client_session_done_latch(1);
- FakeEventLogger event_logger(client_session_done_latch);
- AnalyticsRecorder analytics_recorder(&event_logger);
-
- analytics_recorder.LogSession();
- analytics_recorder.LogSession();
- analytics_recorder.LogSession();
- analytics_recorder.LogSession();
- ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
-
- // Only called once.
- EXPECT_EQ(event_logger.GetLoggedClientSessionCount(), 1);
-}
-
-TEST(AnalyticsRecorderTest, SetFieldsCorrectlyForNestedAdvertisingCalls) {
- connections::Strategy strategy = connections::Strategy::kP2pStar;
- std::vector<Medium> mediums = {BLE, BLUETOOTH};
-
- CountDownLatch client_session_done_latch(1);
- FakeEventLogger event_logger(client_session_done_latch);
- AnalyticsRecorder analytics_recorder(&event_logger);
-
- analytics_recorder.OnStartAdvertising(strategy, mediums);
- analytics_recorder.OnStopAdvertising();
- analytics_recorder.OnStartAdvertising(strategy, {BLUETOOTH});
-
- analytics_recorder.LogSession();
- ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
-
- EXPECT_THAT(event_logger.GetLoggedClientSession(), Partially(EqualsProto(R"pb(
- strategy_session <
- strategy: P2P_STAR
- role: ADVERTISER
- advertising_phase < medium: BLE medium: BLUETOOTH >
- advertising_phase < medium: BLUETOOTH >
- >)pb")));
-}
-
-TEST(AnalyticsRecorderTest, SetFieldsCorrectlyForNestedDiscoveryCalls) {
- connections::Strategy strategy = connections::Strategy::kP2pStar;
- std::vector<Medium> mediums = {BLE, BLUETOOTH};
-
- CountDownLatch client_session_done_latch(1);
- FakeEventLogger event_logger(client_session_done_latch);
- AnalyticsRecorder analytics_recorder(&event_logger);
-
- analytics_recorder.OnStartDiscovery(strategy, mediums);
- analytics_recorder.OnStopDiscovery();
- analytics_recorder.OnEndpointFound(BLUETOOTH);
- analytics_recorder.OnEndpointFound(BLE);
- analytics_recorder.OnStartDiscovery(strategy, {BLUETOOTH});
-
- analytics_recorder.LogSession();
- ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
-
- EXPECT_THAT(event_logger.GetLoggedClientSession(), Partially(EqualsProto(R"pb(
- strategy_session <
- strategy: P2P_STAR
- role: DISCOVERER
- discovery_phase <
- medium: BLE
- medium: BLUETOOTH
- discovered_endpoint < medium: BLUETOOTH >
- discovered_endpoint < medium: BLE >
- >
- discovery_phase < medium: BLUETOOTH >
- >)pb")));
-}
-
-TEST(AnalyticsRecorderTest,
- OneStrategySessionForMultipleRoundsOfDiscoveryAdvertising) {
- connections::Strategy strategy = connections::Strategy::kP2pStar;
- std::vector<Medium> mediums = {BLE, BLUETOOTH};
-
- CountDownLatch client_session_done_latch(1);
- FakeEventLogger event_logger(client_session_done_latch);
- AnalyticsRecorder analytics_recorder(&event_logger);
-
- analytics_recorder.OnStartAdvertising(strategy, mediums);
- analytics_recorder.OnStartDiscovery(strategy, mediums);
- analytics_recorder.OnStopAdvertising();
- analytics_recorder.OnStopDiscovery();
- analytics_recorder.OnStartAdvertising(strategy, mediums);
- analytics_recorder.OnStopAdvertising();
- analytics_recorder.OnStartDiscovery(strategy, mediums);
- analytics_recorder.OnStopDiscovery();
- analytics_recorder.OnStartDiscovery(strategy, mediums);
- analytics_recorder.OnStartAdvertising(strategy, mediums);
- analytics_recorder.OnStopDiscovery();
- analytics_recorder.OnStopAdvertising();
-
- analytics_recorder.LogSession();
- ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
-
- std::vector<EventType> event_types = event_logger.GetLoggedEventTypes();
- EXPECT_THAT(event_types, Contains(START_STRATEGY_SESSION).Times(1));
- EXPECT_THAT(event_types, Contains(STOP_STRATEGY_SESSION).Times(1));
-
- EXPECT_THAT(event_logger.GetLoggedClientSession(), Partially(EqualsProto(R"pb(
- strategy_session <
- strategy: P2P_STAR
- role: ADVERTISER
- role: DISCOVERER
- discovery_phase < medium: BLE medium: BLUETOOTH >
- discovery_phase < medium: BLE medium: BLUETOOTH >
- discovery_phase < medium: BLE medium: BLUETOOTH >
- advertising_phase < medium: BLE medium: BLUETOOTH >
- advertising_phase < medium: BLE medium: BLUETOOTH >
- advertising_phase < medium: BLE medium: BLUETOOTH >
- >)pb")));
-}
-
-TEST(AnalyticsRecorderTest, AdvertiserConnectionRequestsWorks) {
- connections::Strategy strategy = connections::Strategy::kP2pStar;
- std::vector<Medium> mediums = {BLE, BLUETOOTH};
- std::string endpoint_id_0 = "endpoint_id_0";
- std::string endpoint_id_1 = "endpoint_id_1";
- std::string endpoint_id_2 = "endpoint_id_2";
- std::string endpoint_id_3 = "endpoint_id_3";
-
- CountDownLatch client_session_done_latch(1);
- FakeEventLogger event_logger(client_session_done_latch);
- AnalyticsRecorder analytics_recorder(&event_logger);
-
- analytics_recorder.OnStartAdvertising(strategy, mediums);
- analytics_recorder.OnConnectionRequestReceived(endpoint_id_0);
- analytics_recorder.OnLocalEndpointAccepted(endpoint_id_0);
- analytics_recorder.OnRemoteEndpointAccepted(endpoint_id_0);
-
- analytics_recorder.OnConnectionRequestReceived(endpoint_id_1);
- analytics_recorder.OnLocalEndpointAccepted(endpoint_id_1);
- analytics_recorder.OnRemoteEndpointRejected(endpoint_id_1);
-
- analytics_recorder.OnConnectionRequestReceived(endpoint_id_2);
- analytics_recorder.OnLocalEndpointRejected(endpoint_id_2);
- analytics_recorder.OnRemoteEndpointAccepted(endpoint_id_2);
-
- analytics_recorder.OnConnectionRequestReceived(endpoint_id_3);
- analytics_recorder.OnLocalEndpointRejected(endpoint_id_3);
- analytics_recorder.OnRemoteEndpointRejected(endpoint_id_3);
-
- analytics_recorder.LogSession();
- ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
-
- EXPECT_THAT(event_logger.GetLoggedClientSession(), Partially(EqualsProto(R"pb(
- strategy_session <
- strategy: P2P_STAR
- role: ADVERTISER
- advertising_phase <
- medium: BLE
- medium: BLUETOOTH
- received_connection_request <
- local_response: ACCEPTED
- remote_response: ACCEPTED
- >
- received_connection_request <
- local_response: ACCEPTED
- remote_response: REJECTED
- >
- received_connection_request <
- local_response: REJECTED
- remote_response: ACCEPTED
- >
- received_connection_request <
- local_response: REJECTED
- remote_response: REJECTED
- >
- >
- >)pb")));
-}
-
-TEST(AnalyticsRecorderTest, DiscoveryConnectionRequestsWorks) {
- connections::Strategy strategy = connections::Strategy::kP2pStar;
- std::vector<Medium> mediums = {BLE, BLUETOOTH};
- std::string endpoint_id_0 = "endpoint_id_0";
- std::string endpoint_id_1 = "endpoint_id_1";
- std::string endpoint_id_2 = "endpoint_id_2";
- std::string endpoint_id_3 = "endpoint_id_3";
-
- CountDownLatch client_session_done_latch(1);
- FakeEventLogger event_logger(client_session_done_latch);
- AnalyticsRecorder analytics_recorder(&event_logger);
-
- analytics_recorder.OnStartDiscovery(strategy, mediums);
-
- analytics_recorder.OnConnectionRequestSent(endpoint_id_0);
- analytics_recorder.OnLocalEndpointAccepted(endpoint_id_0);
- analytics_recorder.OnRemoteEndpointAccepted(endpoint_id_0);
-
- analytics_recorder.OnConnectionRequestSent(endpoint_id_1);
- analytics_recorder.OnLocalEndpointAccepted(endpoint_id_1);
- analytics_recorder.OnRemoteEndpointRejected(endpoint_id_1);
-
- analytics_recorder.OnConnectionRequestSent(endpoint_id_2);
- analytics_recorder.OnLocalEndpointRejected(endpoint_id_2);
- analytics_recorder.OnRemoteEndpointAccepted(endpoint_id_2);
-
- analytics_recorder.OnConnectionRequestSent(endpoint_id_3);
- analytics_recorder.OnLocalEndpointRejected(endpoint_id_3);
- analytics_recorder.OnRemoteEndpointRejected(endpoint_id_3);
-
- analytics_recorder.LogSession();
- ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
-
- EXPECT_THAT(event_logger.GetLoggedClientSession(), Partially(EqualsProto(R"pb(
- strategy_session <
- strategy: P2P_STAR
- role: DISCOVERER
- discovery_phase <
- medium: BLE
- medium: BLUETOOTH
- sent_connection_request <
- local_response: ACCEPTED
- remote_response: ACCEPTED
- >
- sent_connection_request <
- local_response: ACCEPTED
- remote_response: REJECTED
- >
- sent_connection_request <
- local_response: REJECTED
- remote_response: ACCEPTED
- >
- sent_connection_request <
- local_response: REJECTED
- remote_response: REJECTED
- >
- >
- >)pb")));
-}
-
-TEST(AnalyticsRecorderTest,
- AdvertiserUnfinishedConnectionRequestsIncludedAsIgnored) {
- connections::Strategy strategy = connections::Strategy::kP2pStar;
- std::vector<Medium> mediums = {BLE, BLUETOOTH};
- std::string endpoint_id_0 = "endpoint_id_0";
- std::string endpoint_id_1 = "endpoint_id_1";
- std::string endpoint_id_2 = "endpoint_id_2";
-
- CountDownLatch client_session_done_latch(1);
- FakeEventLogger event_logger(client_session_done_latch);
- AnalyticsRecorder analytics_recorder(&event_logger);
-
- analytics_recorder.OnStartAdvertising(strategy, mediums);
- // Ignored by local.
- analytics_recorder.OnConnectionRequestReceived(endpoint_id_0);
- analytics_recorder.OnRemoteEndpointAccepted(endpoint_id_0);
-
- // Ignored by remote.
- analytics_recorder.OnConnectionRequestReceived(endpoint_id_1);
- analytics_recorder.OnLocalEndpointAccepted(endpoint_id_1);
-
- // Ignored by both.
- analytics_recorder.OnConnectionRequestReceived(endpoint_id_2);
-
- analytics_recorder.LogSession();
- ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
-
- EXPECT_THAT(event_logger.GetLoggedClientSession(), Partially(EqualsProto(R"pb(
- strategy_session <
- strategy: P2P_STAR
- role: ADVERTISER
- advertising_phase <
- medium: BLE
- medium: BLUETOOTH
- received_connection_request <
- local_response: IGNORED
- remote_response: ACCEPTED
- >
- received_connection_request <
- local_response: ACCEPTED
- remote_response: IGNORED
- >
- received_connection_request <
- local_response: IGNORED
- remote_response: IGNORED
- >
- >
- >)pb")));
-}
-
-TEST(AnalyticsRecorderTest,
- DiscovererUnfinishedConnectionRequestsIncludedAsIgnored) {
- connections::Strategy strategy = connections::Strategy::kP2pStar;
- std::vector<Medium> mediums = {BLE, BLUETOOTH};
- std::string endpoint_id_0 = "endpoint_id_0";
- std::string endpoint_id_1 = "endpoint_id_1";
- std::string endpoint_id_2 = "endpoint_id_2";
-
- CountDownLatch client_session_done_latch(1);
- FakeEventLogger event_logger(client_session_done_latch);
- AnalyticsRecorder analytics_recorder(&event_logger);
-
- analytics_recorder.OnStartDiscovery(strategy, mediums);
-
- // Ignored by local.
- analytics_recorder.OnConnectionRequestSent(endpoint_id_0);
- analytics_recorder.OnRemoteEndpointAccepted(endpoint_id_0);
-
- // Ignored by remote.
- analytics_recorder.OnConnectionRequestSent(endpoint_id_1);
- analytics_recorder.OnLocalEndpointAccepted(endpoint_id_1);
-
- // Ignored by both.
- analytics_recorder.OnConnectionRequestSent(endpoint_id_2);
-
- analytics_recorder.LogSession();
- ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
-
- EXPECT_THAT(event_logger.GetLoggedClientSession(), Partially(EqualsProto(R"pb(
- strategy_session <
- strategy: P2P_STAR
- role: DISCOVERER
- discovery_phase <
- medium: BLE
- medium: BLUETOOTH
- sent_connection_request <
- local_response: IGNORED
- remote_response: ACCEPTED
- >
- sent_connection_request <
- local_response: ACCEPTED
- remote_response: IGNORED
- >
- sent_connection_request <
- local_response: IGNORED
- remote_response: IGNORED
- >
- >
- >)pb")));
-}
-
-TEST(AnalyticsRecorderTest, SuccessfulIncomingConnectionAttempt) {
- connections::Strategy strategy = connections::Strategy::kP2pStar;
- std::vector<Medium> mediums = {BLE, BLUETOOTH};
- std::string endpoint_id = "endpoint_id";
- std::string connection_token = "";
-
- CountDownLatch client_session_done_latch(1);
- FakeEventLogger event_logger(client_session_done_latch);
- AnalyticsRecorder analytics_recorder{&event_logger};
-
- analytics_recorder.OnStartAdvertising(strategy, mediums);
- analytics_recorder.OnIncomingConnectionAttempt(
- INITIAL, BLUETOOTH, RESULT_SUCCESS, absl::Duration{}, connection_token);
- analytics_recorder.OnStopAdvertising();
-
- analytics_recorder.LogSession();
- ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
-
- EXPECT_THAT(event_logger.GetLoggedClientSession(), Partially(EqualsProto(R"pb(
- strategy_session <
- strategy: P2P_STAR
- role: ADVERTISER
- advertising_phase < medium: BLE medium: BLUETOOTH >
- connection_attempt <
- type: INITIAL
- direction: INCOMING
- medium: BLUETOOTH
- attempt_result: RESULT_SUCCESS
- connection_token: ""
- >
- >)pb")));
-}
-
-TEST(AnalyticsRecorderTest,
- FailedConnectionAttemptUpdatesConnectionRequestNotSent) {
- connections::Strategy strategy = connections::Strategy::kP2pStar;
- std::vector<Medium> mediums = {BLE, BLUETOOTH};
- std::string endpoint_id = "endpoint_id";
- std::string connection_token = "";
-
- CountDownLatch client_session_done_latch(1);
- FakeEventLogger event_logger(client_session_done_latch);
- AnalyticsRecorder analytics_recorder(&event_logger);
-
- analytics_recorder.OnStartDiscovery(strategy, mediums);
- analytics_recorder.OnConnectionRequestSent(endpoint_id);
- analytics_recorder.OnOutgoingConnectionAttempt(
- endpoint_id, INITIAL, BLUETOOTH, RESULT_ERROR, absl::Duration{},
- connection_token);
-
- analytics_recorder.LogSession();
- ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
-
- EXPECT_THAT(event_logger.GetLoggedClientSession(), Partially(EqualsProto(R"pb(
- strategy_session <
- strategy: P2P_STAR
- role: DISCOVERER
- discovery_phase <
- medium: BLE
- medium: BLUETOOTH
- sent_connection_request <
- local_response: NOT_SENT
- remote_response: NOT_SENT
- >
- >
- connection_attempt <
- type: INITIAL
- direction: OUTGOING
- medium: BLUETOOTH
- attempt_result: RESULT_ERROR
- connection_token: ""
- >
- >)pb")));
-}
-
-TEST(AnalyticsRecorderTest, UnfinishedEstablishedConnectionsAddedAsUnfinished) {
- connections::Strategy strategy = connections::Strategy::kP2pStar;
- std::vector<Medium> mediums = {BLE, BLUETOOTH};
- std::string endpoint_id = "endpoint_id";
- std::string connection_token = "connection_token";
-
- CountDownLatch client_session_done_latch(1);
- FakeEventLogger event_logger(client_session_done_latch);
- AnalyticsRecorder analytics_recorder(&event_logger);
-
- analytics_recorder.OnStartAdvertising(strategy, mediums);
- analytics_recorder.OnConnectionEstablished(endpoint_id, BLUETOOTH,
- connection_token);
- analytics_recorder.OnConnectionClosed(endpoint_id, BLUETOOTH, UPGRADED);
- analytics_recorder.OnConnectionEstablished(endpoint_id, WIFI_LAN,
- connection_token);
-
- analytics_recorder.LogSession();
- ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
-
- EXPECT_THAT(event_logger.GetLoggedClientSession(), Partially(EqualsProto(R"pb(
- strategy_session <
- strategy: P2P_STAR
- role: ADVERTISER
- advertising_phase < medium: BLE medium: BLUETOOTH >
- established_connection <
- medium: BLUETOOTH
- disconnection_reason: UPGRADED
- connection_token: "connection_token"
- >
- established_connection <
- medium: WIFI_LAN
- disconnection_reason: UNFINISHED
- connection_token: "connection_token"
- >
- >)pb")));
-}
-
-TEST(AnalyticsRecorderTest, OutgoingPayloadUpgraded) {
- connections::Strategy strategy = connections::Strategy::kP2pStar;
- std::vector<Medium> mediums = {BLE, BLUETOOTH};
- std::string endpoint_id = "endpoint_id";
- std::int64_t payload_id = 123456789;
- std::string connection_token = "connection_token";
-
- CountDownLatch client_session_done_latch(1);
- FakeEventLogger event_logger(client_session_done_latch);
- AnalyticsRecorder analytics_recorder(&event_logger);
-
- analytics_recorder.OnStartAdvertising(strategy, mediums);
- analytics_recorder.OnConnectionEstablished(endpoint_id, BLUETOOTH,
- connection_token);
- analytics_recorder.OnOutgoingPayloadStarted(
- {endpoint_id}, payload_id, connections::Payload::Type::kFile, 50);
- analytics_recorder.OnPayloadChunkSent(endpoint_id, payload_id, 10);
- analytics_recorder.OnPayloadChunkSent(endpoint_id, payload_id, 10);
- analytics_recorder.OnConnectionClosed(endpoint_id, BLUETOOTH, UPGRADED);
- analytics_recorder.OnConnectionEstablished(endpoint_id, WIFI_LAN,
- connection_token);
- analytics_recorder.OnPayloadChunkSent(endpoint_id, payload_id, 10);
- analytics_recorder.OnPayloadChunkSent(endpoint_id, payload_id, 10);
- analytics_recorder.OnPayloadChunkSent(endpoint_id, payload_id, 10);
- analytics_recorder.OnOutgoingPayloadDone(endpoint_id, payload_id, SUCCESS);
- analytics_recorder.OnConnectionClosed(endpoint_id, WIFI_LAN,
- LOCAL_DISCONNECTION);
-
- analytics_recorder.LogSession();
- ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
-
- EXPECT_THAT(event_logger.GetLoggedClientSession(), Partially(EqualsProto(R"pb(
- strategy_session <
- strategy: P2P_STAR
- role: ADVERTISER
- advertising_phase < medium: BLE medium: BLUETOOTH >
- established_connection <
- medium: BLUETOOTH
- sent_payload <
- type: FILE
- total_size_bytes: 50
- num_bytes_transferred: 20
- num_chunks: 2
- status: MOVED_TO_NEW_MEDIUM
- >
- disconnection_reason: UPGRADED
- connection_token: "connection_token"
- >
- established_connection <
- medium: WIFI_LAN
- sent_payload <
- type: FILE
- total_size_bytes: 50
- num_bytes_transferred: 30
- num_chunks: 3
- status: SUCCESS
- >
- disconnection_reason: LOCAL_DISCONNECTION
- connection_token: "connection_token"
- >
- >)pb")));
-}
-
-TEST(AnalyticsRecorderTest, UpgradeAttemptWorks) {
- connections::Strategy strategy = connections::Strategy::kP2pStar;
- std::vector<Medium> mediums = {BLE, BLUETOOTH};
- std::string endpoint_id = "endpoint_id";
- std::string endpoint_id_1 = "endpoint_id_1";
- std::string endpoint_id_2 = "endpoint_id_2";
- std::string connection_token = "connection_token";
-
- CountDownLatch client_session_done_latch(1);
- FakeEventLogger event_logger(client_session_done_latch);
- AnalyticsRecorder analytics_recorder(&event_logger);
-
- analytics_recorder.OnStartAdvertising(strategy, mediums);
-
- analytics_recorder.OnBandwidthUpgradeStarted(endpoint_id, BLE, WIFI_LAN,
- INCOMING, connection_token);
-
- analytics_recorder.OnBandwidthUpgradeStarted(
- endpoint_id_1, BLUETOOTH, WIFI_LAN, INCOMING, connection_token);
- // Error to upgrade.
- analytics_recorder.OnBandwidthUpgradeError(endpoint_id, WIFI_LAN_MEDIUM_ERROR,
- WIFI_LAN_SOCKET_CREATION);
- // Success to upgrade.
- analytics_recorder.OnBandwidthUpgradeSuccess(endpoint_id_1);
- // Upgrade is unfinished.
- analytics_recorder.OnBandwidthUpgradeStarted(
- endpoint_id_2, BLUETOOTH, WIFI_LAN, INCOMING, connection_token);
-
- analytics_recorder.LogSession();
- ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
-
- EXPECT_THAT(event_logger.GetLoggedClientSession(), Partially(EqualsProto(R"pb(
- strategy_session <
- strategy: P2P_STAR
- role: ADVERTISER
- advertising_phase < medium: BLE medium: BLUETOOTH >
- upgrade_attempt <
- direction: INCOMING
- from_medium: BLE
- to_medium: WIFI_LAN
- upgrade_result: WIFI_LAN_MEDIUM_ERROR
- error_stage: WIFI_LAN_SOCKET_CREATION
- connection_token: "connection_token"
- >
- upgrade_attempt <
- direction: INCOMING
- from_medium: BLUETOOTH
- to_medium: WIFI_LAN
- upgrade_result: UPGRADE_RESULT_SUCCESS
- error_stage: UPGRADE_SUCCESS
- connection_token: "connection_token"
- >
- upgrade_attempt {
- direction: INCOMING
- from_medium: BLUETOOTH
- to_medium: WIFI_LAN
- upgrade_result: UNFINISHED_ERROR
- error_stage: UPGRADE_UNFINISHED
- connection_token: "connection_token"
- }
- >)pb")));
-}
-
-TEST(AnalyticsRecorderTest, SetErrorCodeFieldsCorrectly) {
- connections::Strategy strategy = connections::Strategy::kP2pStar;
- std::vector<Medium> mediums = {WEB_RTC};
- std::string connection_token = "connection_token";
-
- CountDownLatch client_session_done_latch(1);
- FakeEventLogger event_logger(client_session_done_latch);
- AnalyticsRecorder analytics_recorder(&event_logger);
- analytics_recorder.OnStartDiscovery(strategy, mediums);
-
- ErrorCodeParams error_code_params = ErrorCodeRecorder::BuildErrorCodeParams(
- WEB_RTC, DISCONNECT, DISCONNECT_NETWORK_FAILED,
- TACHYON_SEND_MESSAGE_STATUS_EXCEPTION, "", connection_token);
- analytics_recorder.OnErrorCode(error_code_params);
-
- analytics_recorder.LogSession();
- ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
-
- EXPECT_THAT(event_logger.GetErrorCode(), Partially(EqualsProto(R"pb(
- medium: WEB_RTC
- event: DISCONNECT
- description: TACHYON_SEND_MESSAGE_STATUS_EXCEPTION
- disconnect_error: DISCONNECT_NETWORK_FAILED
- connection_token: "connection_token"
- )pb")));
-}
-
-TEST(AnalyticsRecorderTest, SetErrorCodeFieldsCorrectlyForUnknownDescription) {
- connections::Strategy strategy = connections::Strategy::kP2pStar;
- std::vector<Medium> mediums = {BLUETOOTH};
- std::string connection_token = "connection_token";
-
- CountDownLatch client_session_done_latch(1);
- FakeEventLogger event_logger(client_session_done_latch);
- AnalyticsRecorder analytics_recorder(&event_logger);
- analytics_recorder.OnStartDiscovery(strategy, mediums);
-
- ErrorCodeParams error_code_params;
- // Skip setting error_code_params.description
- error_code_params.medium = BLUETOOTH;
- error_code_params.event = START_DISCOVERING;
- error_code_params.start_discovering_error = START_EXTENDED_DISCOVERING_FAILED;
- error_code_params.connection_token = connection_token;
- analytics_recorder.OnErrorCode(error_code_params);
-
- analytics_recorder.LogSession();
- ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
-
- EXPECT_THAT(event_logger.GetErrorCode(), Partially(EqualsProto(R"pb(
- medium: BLUETOOTH
- event: START_DISCOVERING
- description: UNKNOWN
- start_discovering_error: START_EXTENDED_DISCOVERING_FAILED
- connection_token: "connection_token"
- )pb")));
-}
-
-TEST(AnalyticsRecorderTest, SetErrorCodeFieldsCorrectlyForCommonError) {
- connections::Strategy strategy = connections::Strategy::kP2pStar;
- std::vector<Medium> mediums = {BLUETOOTH};
- std::string connection_token = "connection_token";
-
- CountDownLatch client_session_done_latch(1);
- FakeEventLogger event_logger(client_session_done_latch);
- AnalyticsRecorder analytics_recorder(&event_logger);
- analytics_recorder.OnStartDiscovery(strategy, mediums);
-
- ErrorCodeParams error_code_params = ErrorCodeRecorder::BuildErrorCodeParams(
- BLUETOOTH, START_DISCOVERING, INVALID_PARAMETER,
- NULL_BLUETOOTH_DEVICE_NAME, "", connection_token);
- analytics_recorder.OnErrorCode(error_code_params);
-
- analytics_recorder.LogSession();
- ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
-
- EXPECT_THAT(event_logger.GetErrorCode(), Partially(EqualsProto(R"pb(
- medium: BLUETOOTH
- event: START_DISCOVERING
- description: NULL_BLUETOOTH_DEVICE_NAME
- common_error: INVALID_PARAMETER
- connection_token: "connection_token"
- )pb")));
-}
-
-} // namespace
-} // namespace analytics
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/cal/api/BUILD b/chromium/third_party/nearby/src/cpp/cal/api/BUILD
index 895cb796feb..5ca855b17eb 100644
--- a/chromium/third_party/nearby/src/cpp/cal/api/BUILD
+++ b/chromium/third_party/nearby/src/cpp/cal/api/BUILD
@@ -19,15 +19,14 @@ cc_library(
hdrs = [
"ble.h",
],
- compatible_with = ["//buildenv/target:non_prod"],
visibility = [
"//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
- "//third_party/nearby_connections/cpp:__subpackages__",
+ "//third_party/nearby/cpp:__subpackages__",
],
deps = [
- "//absl/strings",
- "//absl/time",
- "//absl/types:optional",
- "//third_party/nearby_connections/cpp/cal/base:types",
+ "//cpp/cal/base:types",
+ "@com_google_absl//absl/strings",
+ "@com_google_absl//absl/time",
+ "@com_google_absl//absl/types:optional",
],
)
diff --git a/chromium/third_party/nearby/src/cpp/cal/api/ble.h b/chromium/third_party/nearby/src/cpp/cal/api/ble.h
index 80682b4eb6b..29879059c8a 100644
--- a/chromium/third_party/nearby/src/cpp/cal/api/ble.h
+++ b/chromium/third_party/nearby/src/cpp/cal/api/ble.h
@@ -22,7 +22,7 @@
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "absl/types/optional.h"
-#include "third_party/nearby_connections/cpp/cal/base/ble_types.h"
+#include "third_party/nearby/cpp/cal/base/ble_types.h"
namespace nearby {
namespace cal {
namespace api {
diff --git a/chromium/third_party/nearby/src/cpp/cal/base/BUILD b/chromium/third_party/nearby/src/cpp/cal/base/BUILD
index aa9e115ed2c..325cd7d6437 100644
--- a/chromium/third_party/nearby/src/cpp/cal/base/BUILD
+++ b/chromium/third_party/nearby/src/cpp/cal/base/BUILD
@@ -19,12 +19,11 @@ cc_library(
hdrs = [
"ble_types.h",
],
- compatible_with = ["//buildenv/target:non_prod"],
visibility = [
"//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
- "//third_party/nearby_connections/cpp:__subpackages__",
+ "//third_party/nearby/cpp:__subpackages__",
],
deps = [
- "//platform/base",
+ "//internal/platform:base",
],
)
diff --git a/chromium/third_party/nearby/src/cpp/cal/base/ble_types.h b/chromium/third_party/nearby/src/cpp/cal/base/ble_types.h
index 3dba08fb412..091bff72005 100644
--- a/chromium/third_party/nearby/src/cpp/cal/base/ble_types.h
+++ b/chromium/third_party/nearby/src/cpp/cal/base/ble_types.h
@@ -14,14 +14,15 @@
#ifndef CAL_BASE_TYPES_H_
#define CAL_BASE_TYPES_H_
+
// TODO(hais) relocate base def class accordingly.
#include <map>
-#include "platform/base/byte_array.h"
-#include "platform/base/exception.h"
-#include "platform/base/input_stream.h"
-#include "platform/base/listeners.h"
-#include "platform/base/output_stream.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/input_stream.h"
+#include "internal/platform/listeners.h"
+#include "internal/platform/output_stream.h"
namespace nearby {
namespace cal {
@@ -48,16 +49,20 @@ enum class PowerMode {
struct AdvertiseSettings {
AdvertiseMode advertise_mode;
- PowerMode poser_mode;
+ PowerMode power_mode;
int timeout;
bool is_connectable;
- std::string local_name;
};
struct BleAdvertisementData {
AdvertiseSettings advertise_settings;
- // service UUID to advertise bytes map
- std::map<std::string, ByteArray> service_data_map;
+ // service UUID to advertise bytes map:16-bit service UUID - service Data
+ //
+ // Data type value : 0x16
+ // if platform can't advertise data from this key (reaonly in iOS), then (iOS)
+ // should advertise data via LocalName data type. It means the service_uuid
+ // here is useless for iOS platform.
+ std::map<std::string, location::nearby::ByteArray> service_data_map;
};
enum class ScanMode {
@@ -75,4 +80,5 @@ struct ScanSettings {
} // namespace cal
} // namespace nearby
+
#endif // CAL_BASE_TYPES_H_
diff --git a/chromium/third_party/nearby/src/cpp/cal/public/BUILD b/chromium/third_party/nearby/src/cpp/cal/public/BUILD
index ab5ecaaf0eb..7ebd95b407d 100644
--- a/chromium/third_party/nearby/src/cpp/cal/public/BUILD
+++ b/chromium/third_party/nearby/src/cpp/cal/public/BUILD
@@ -22,14 +22,13 @@ cc_library(
hdrs = [
"ble.h",
],
- compatible_with = ["//buildenv/target:non_prod"],
visibility = [
"//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
- "//third_party/nearby_connections/cpp:__subpackages__",
+ "//third_party/nearby:__subpackages__",
],
deps = [
- "//third_party/nearby_connections/cpp/cal/api:ble",
- "//third_party/nearby_connections/cpp/cal/base:types",
+ "//third_party/nearby/cpp/cal/api:ble",
+ "//cpp/cal/base:types",
],
)
@@ -42,9 +41,10 @@ cc_test(
],
deps = [
":ble",
- "//testing/base/public:gunit",
- "//testing/base/public:gunit_main",
- "//third_party/nearby_connections/cpp/cal/api:ble",
- "//third_party/nearby_connections/cpp/cal/base:types",
+ "//third_party/nearby/cpp/cal/api:ble",
+ "//cpp/cal/base:types",
+ "@com_github_protobuf_matchers//protobuf-matchers",
+ "@com_google_googletest//:gtest",
+ "@com_google_googletest//:gtest_main",
],
)
diff --git a/chromium/third_party/nearby/src/cpp/cal/public/ble.cc b/chromium/third_party/nearby/src/cpp/cal/public/ble.cc
index f460b447e14..15c7e6f8371 100644
--- a/chromium/third_party/nearby/src/cpp/cal/public/ble.cc
+++ b/chromium/third_party/nearby/src/cpp/cal/public/ble.cc
@@ -12,12 +12,12 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-#include "third_party/nearby_connections/cpp/cal/public/ble.h"
+#include "third_party/nearby/cpp/cal/public/ble.h"
#include <memory>
-#include "third_party/nearby_connections/cpp/cal/api/ble.h"
-#include "third_party/nearby_connections/cpp/cal/base/ble_types.h"
+#include "third_party/nearby/cpp/cal/api/ble.h"
+#include "third_party/nearby/cpp/cal/base/ble_types.h"
namespace nearby {
namespace cal {
diff --git a/chromium/third_party/nearby/src/cpp/cal/public/ble.h b/chromium/third_party/nearby/src/cpp/cal/public/ble.h
index dab6d239ef1..5d0352de843 100644
--- a/chromium/third_party/nearby/src/cpp/cal/public/ble.h
+++ b/chromium/third_party/nearby/src/cpp/cal/public/ble.h
@@ -17,8 +17,8 @@
#include <memory>
-#include "third_party/nearby_connections/cpp/cal/api/ble.h"
-#include "third_party/nearby_connections/cpp/cal/base/ble_types.h"
+#include "third_party/nearby/cpp/cal/api/ble.h"
+#include "third_party/nearby/cpp/cal/base/ble_types.h"
namespace nearby {
namespace cal {
diff --git a/chromium/third_party/nearby/src/cpp/cal/public/ble_test.cc b/chromium/third_party/nearby/src/cpp/cal/public/ble_test.cc
index 81ecdc473d3..d7c01520532 100644
--- a/chromium/third_party/nearby/src/cpp/cal/public/ble_test.cc
+++ b/chromium/third_party/nearby/src/cpp/cal/public/ble_test.cc
@@ -15,10 +15,11 @@
#include <memory>
#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
#include "gtest/gtest.h"
-#include "third_party/nearby_connections/cpp/cal/api/ble.h"
-#include "third_party/nearby_connections/cpp/cal/base/ble_types.h"
-#include "third_party/nearby_connections/cpp/cal/public/ble.h"
+#include "third_party/nearby/cpp/cal/api/ble.h"
+#include "third_party/nearby/cpp/cal/base/ble_types.h"
+#include "third_party/nearby/cpp/cal/public/ble.h"
namespace nearby {
namespace cal {
diff --git a/chromium/third_party/nearby/src/cpp/core/BUILD b/chromium/third_party/nearby/src/cpp/core/BUILD
deleted file mode 100644
index d4d5d83c8c6..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/BUILD
+++ /dev/null
@@ -1,114 +0,0 @@
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# https://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-licenses(["notice"])
-
-cc_library(
- name = "core",
- srcs = [
- "core.cc",
- ],
- hdrs = [
- "core.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- copts = ["-DCORE_ADAPTER_DLL"],
- visibility = [
- "//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
- "//third_party/nearby_connections/windows:__subpackages__",
- ],
- deps = [
- ":core_types",
- ":event_logger",
- "//absl/strings",
- "//absl/time",
- "//absl/types:span",
- "//core/internal",
- "//platform/base",
- "//platform/public:logging",
- "//platform/public:types",
- ],
-)
-
-cc_library(
- name = "core_types",
- srcs = [
- "options.cc",
- "payload.cc",
- "strategy.cc",
- ],
- hdrs = [
- "listeners.h",
- "options.h",
- "params.h",
- "payload.h",
- "status.h",
- "strategy.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- copts = ["-DCORE_ADAPTER_DLL"],
- visibility = [
- "//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
- "//analytics:__subpackages__",
- "//core:__subpackages__",
- ],
- deps = [
- "//absl/strings",
- "//absl/types:variant",
- "//platform/base",
- "//platform/base:util",
- "//platform/public:types",
- "//proto:connections_enums_portable_proto",
- ],
-)
-
-cc_library(
- name = "event_logger",
- hdrs = [
- "event_logger.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- visibility = [
- "//analytics:__subpackages__",
- ],
- deps = [
- "//proto/analytics:connections_log_cc_proto",
- ],
-)
-
-cc_test(
- name = "core_test",
- size = "small",
- srcs = [
- "core_test.cc",
- "listeners_test.cc",
- "payload_test.cc",
- "status_test.cc",
- "strategy_test.cc",
- ],
- shard_count = 16,
- deps = [
- ":core",
- ":core_types",
- "//testing/base/public:gunit_main",
- "//absl/strings",
- "//absl/time",
- "//absl/types:variant",
- "//core/internal",
- "//core/internal:internal_test",
- "//platform/base",
- "//platform/impl/g3", # build_cleaner: keep
- "//platform/public:logging",
- "//platform/public:types",
- ],
-)
diff --git a/chromium/third_party/nearby/src/cpp/core/core.cc b/chromium/third_party/nearby/src/cpp/core/core.cc
deleted file mode 100644
index beb859690e9..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/core.cc
+++ /dev/null
@@ -1,156 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/core.h"
-
-#include <cassert>
-#include <string>
-#include <utility>
-#include <vector>
-
-#include "absl/time/clock.h"
-#include "core/options.h"
-#include "platform/base/feature_flags.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-constexpr absl::Duration kWaitForDisconnect = absl::Milliseconds(5000);
-} // namespace
-
-Core::Core(ServiceControllerRouter* router) : router_(router) {}
-
-Core::~Core() {
- CountDownLatch latch(1);
- router_->StopAllEndpoints(
- &client_, {
- .result_cb = [&latch](Status) { latch.CountDown(); },
- });
- if (!latch.Await(kWaitForDisconnect).result()) {
- NEARBY_LOG(FATAL, "Unable to shutdown");
- }
-}
-
-Core::Core(Core&&) = default;
-
-Core& Core::operator=(Core&&) = default;
-
-void Core::StartAdvertising(absl::string_view service_id,
- ConnectionOptions options,
- ConnectionRequestInfo info,
- ResultCallback callback) {
- assert(!service_id.empty());
- assert(options.strategy.IsValid());
-
- router_->StartAdvertising(&client_, service_id, options, info, callback);
-}
-
-void Core::StopAdvertising(const ResultCallback callback) {
- router_->StopAdvertising(&client_, callback);
-}
-
-void Core::StartDiscovery(absl::string_view service_id,
- ConnectionOptions options, DiscoveryListener listener,
- ResultCallback callback) {
- assert(!service_id.empty());
- assert(options.strategy.IsValid());
-
- router_->StartDiscovery(&client_, service_id, options, listener, callback);
-}
-
-void Core::InjectEndpoint(absl::string_view service_id,
- OutOfBandConnectionMetadata metadata,
- ResultCallback callback) {
- router_->InjectEndpoint(&client_, service_id, metadata, callback);
-}
-
-void Core::StopDiscovery(ResultCallback callback) {
- router_->StopDiscovery(&client_, callback);
-}
-
-void Core::RequestConnection(absl::string_view endpoint_id,
- ConnectionRequestInfo info,
- ConnectionOptions options,
- ResultCallback callback) {
- assert(!endpoint_id.empty());
-
- // Assign the default from feature flags for the keep-alive frame interval and
- // timeout values if client don't mind them or has the unexpected ones.
- if (options.keep_alive_interval_millis == 0 ||
- options.keep_alive_timeout_millis == 0 ||
- options.keep_alive_interval_millis >= options.keep_alive_timeout_millis) {
- NEARBY_LOG(
- WARNING,
- "Client request connection with keep-alive frame as interval=%d, "
- "timeout=%d, which is un-expected. Change to default.",
- options.keep_alive_interval_millis, options.keep_alive_timeout_millis);
- options.keep_alive_interval_millis =
- FeatureFlags::GetInstance().GetFlags().keep_alive_interval_millis;
- options.keep_alive_timeout_millis =
- FeatureFlags::GetInstance().GetFlags().keep_alive_timeout_millis;
- }
-
- router_->RequestConnection(&client_, endpoint_id, info, options, callback);
-}
-
-void Core::AcceptConnection(absl::string_view endpoint_id,
- PayloadListener listener, ResultCallback callback) {
- assert(!endpoint_id.empty());
-
- router_->AcceptConnection(&client_, endpoint_id, listener, callback);
-}
-
-void Core::RejectConnection(absl::string_view endpoint_id,
- ResultCallback callback) {
- assert(!endpoint_id.empty());
-
- router_->RejectConnection(&client_, endpoint_id, callback);
-}
-
-void Core::InitiateBandwidthUpgrade(absl::string_view endpoint_id,
- ResultCallback callback) {
- router_->InitiateBandwidthUpgrade(&client_, endpoint_id, callback);
-}
-
-void Core::SendPayload(absl::Span<const std::string> endpoint_ids,
- Payload payload, ResultCallback callback) {
- assert(payload.GetType() != Payload::Type::kUnknown);
- assert(!endpoint_ids.empty());
-
- router_->SendPayload(&client_, endpoint_ids, std::move(payload), callback);
-}
-
-void Core::CancelPayload(std::int64_t payload_id, ResultCallback callback) {
- assert(payload_id != 0);
-
- router_->CancelPayload(&client_, payload_id, callback);
-}
-
-void Core::DisconnectFromEndpoint(absl::string_view endpoint_id,
- ResultCallback callback) {
- assert(!endpoint_id.empty());
-
- router_->DisconnectFromEndpoint(&client_, endpoint_id, callback);
-}
-
-void Core::StopAllEndpoints(ResultCallback callback) {
- router_->StopAllEndpoints(&client_, callback);
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/core.h b/chromium/third_party/nearby/src/cpp/core/core.h
deleted file mode 100644
index 1166ad48cc4..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/core.h
+++ /dev/null
@@ -1,247 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_CORE_H_
-#define CORE_CORE_H_
-
-#include <functional>
-#include <string>
-
-#include "absl/strings/string_view.h"
-#include "absl/types/span.h"
-#include "core/event_logger.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/service_controller.h"
-#include "core/internal/service_controller_router.h"
-#include "core/listeners.h"
-#include "core/options.h"
-#include "core/params.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// This class defines the API of the Nearby Connections Core library.
-class Core {
- public:
- explicit Core(ServiceControllerRouter* router);
- // Client needs to call this constructor if analytics logger is needed.
- Core(analytics::EventLogger* event_logger, ServiceControllerRouter* router)
- : client_(event_logger), router_(router) {}
- ~Core();
- Core(Core&&);
- Core& operator=(Core&&);
-
- // Starts advertising an endpoint for a local app.
- //
- // service_id - An identifier to advertise your app to other endpoints.
- // This can be an arbitrary string, so long as it uniquely
- // identifies your service. A good default is to use your
- // app's package name.
- // options - The options for advertising.
- // info - Connection parameters:
- // > name - A human readable name for this endpoint, to appear on
- // other devices.
- // > listener - A callback notified when remote endpoints request a
- // connection to this endpoint.
- // callback - to access the status of the operation when available.
- // Possible status codes include:
- // Status::STATUS_OK if advertising started successfully.
- // Status::STATUS_ALREADY_ADVERTISING if the app is already advertising.
- // Status::STATUS_OUT_OF_ORDER_API_CALL if the app is currently
- // connected to remote endpoints; call StopAllEndpoints first.
- void StartAdvertising(absl::string_view service_id, ConnectionOptions options,
- ConnectionRequestInfo info, ResultCallback callback);
-
- // Stops advertising a local endpoint. Should be called after calling
- // StartAdvertising, as soon as the application no longer needs to advertise
- // itself or goes inactive. Payloads can still be sent to connected
- // endpoints after advertising ends.
- //
- // result_cb - to access the status of the operation when available.
- // Possible status codes include:
- // Status::STATUS_OK if none of the above errors occurred.
- void StopAdvertising(ResultCallback callback);
-
- // Starts discovery for remote endpoints with the specified service ID.
- //
- // service_id - The ID for the service to be discovered, as specified in
- // the corresponding call to StartAdvertising.
- // listener - A callback notified when a remote endpoint is discovered.
- // options - The options for discovery.
- // result_cb - to access the status of the operation when available.
- // Possible status codes include:
- // Status::STATUS_OK if discovery started successfully.
- // Status::STATUS_ALREADY_DISCOVERING if the app is already
- // discovering the specified service.
- // Status::STATUS_OUT_OF_ORDER_API_CALL if the app is currently
- // connected to remote endpoints; call StopAllEndpoints first.
- void StartDiscovery(absl::string_view service_id, ConnectionOptions options,
- DiscoveryListener listener, ResultCallback callback);
-
- // Stops discovery for remote endpoints, after a previous call to
- // StartDiscovery, when the client no longer needs to discover endpoints or
- // goes inactive. Payloads can still be sent to connected endpoints after
- // discovery ends.
- //
- // result_cb - to access the status of the operation when available.
- // Possible status codes include:
- // Status::STATUS_OK if none of the above errors occurred.
- void StopDiscovery(ResultCallback callback);
-
- // Invokes the discovery callback from a previous call to StartDiscovery()
- // with the given endpoint info. The previous call to StartDiscovery() must
- // have been passed ConnectionOptions with is_out_of_band_connection == true.
- //
- // service_id - The ID for the service to be discovered, as
- // specified in the corresponding call to
- // StartDiscovery().
- // metadata - Metadata used in order to inject the endpoint.
- // result_cb - to access the status of the operation when
- // available.
- // Possible status codes include:
- // Status::kSuccess if endpoint injection was attempted.
- // Status::kError if endpoint_id, endpoint_info, or
- // remote_bluetooth_mac_address are malformed.
- // Status::kOutOfOrderApiCall if the app is not discovering.
- void InjectEndpoint(absl::string_view service_id,
- OutOfBandConnectionMetadata metadata,
- ResultCallback callback);
-
- // Sends a request to connect to a remote endpoint.
- //
- // endpoint_id - The identifier for the remote endpoint to which a
- // connection request will be sent. Should match the value
- // provided in a call to
- // DiscoveryListener::endpoint_found_cb()
- // info - Connection parameters:
- // > name - A human readable name for the local endpoint, to appear on
- // the remote endpoint.
- // > listener - A callback notified when the remote endpoint sends a
- // response to the connection request.
- // result_cb - to access the status of the operation when available.
- // Possible status codes include:
- // Status::STATUS_OK if the connection request was sent.
- // Status::STATUS_ALREADY_CONNECTED_TO_ENDPOINT if the app already
- // has a connection to the specified endpoint.
- // Status::STATUS_RADIO_ERROR if we failed to connect because of an
- // issue with Bluetooth/WiFi.
- // Status::STATUS_ERROR if we failed to connect for any other reason.
- void RequestConnection(absl::string_view endpoint_id,
- ConnectionRequestInfo info, ConnectionOptions options,
- ResultCallback callback);
-
- // Accepts a connection to a remote endpoint. This method must be called
- // before Payloads can be exchanged with the remote endpoint.
- //
- // endpoint_id - The identifier for the remote endpoint. Should match the
- // value provided in a call to
- // ConnectionListener::onConnectionInitiated.
- // listener - A callback for payloads exchanged with the remote endpoint.
- // result_cb - to access the status of the operation when available.
- // Possible status codes include:
- // Status::STATUS_OK if the connection request was accepted.
- // Status::STATUS_ALREADY_CONNECTED_TO_ENDPOINT if the app already.
- // has a connection to the specified endpoint.
- void AcceptConnection(absl::string_view endpoint_id, PayloadListener listener,
- ResultCallback callback);
-
- // Rejects a connection to a remote endpoint.
- //
- // endpoint_id - The identifier for the remote endpoint. Should match the
- // value provided in a call to
- // ConnectionListener::onConnectionInitiated().
- // result_cb - to access the status of the operation when available.
- // Possible status codes include:
- // Status::STATUS_OK} if the connection request was rejected.
- // Status::STATUS_ALREADY_CONNECTED_TO_ENDPOINT} if the app already
- // has a connection to the specified endpoint.
- void RejectConnection(absl::string_view endpoint_id, ResultCallback callback);
-
- // Sends a Payload to a remote endpoint. Payloads can only be sent to remote
- // endpoints once a notice of connection acceptance has been delivered via
- // ConnectionListener::onConnectionResult().
- //
- // endpoint_ids - Array of remote endpoint identifiers for the to which the
- // payload should be sent.
- // payload - The Payload to be sent.
- // result_cb - to access the status of the operation when available.
- // Possible status codes include:
- // Status::STATUS_OUT_OF_ORDER_API_CALL if the device has not first
- // performed advertisement or discovery (to set the Strategy.
- // Status::STATUS_ENDPOINT_UNKNOWN if there's no active (or pending)
- // connection to the remote endpoint.
- // Status::STATUS_OK if none of the above errors occurred. Note that this
- // indicates that Nearby Connections will attempt to send the Payload,
- // but not that the send has successfully completed yet. Errors might
- // still occur during transmission (and at different times for
- // different endpoints), and will be delivered via
- // PayloadCallback#onPayloadTransferUpdate.
- void SendPayload(absl::Span<const std::string> endpoint_ids, Payload payload,
- ResultCallback callback);
-
- // Cancels a Payload currently in-flight to or from remote endpoint(s).
- //
- // payload_id - The identifier for the Payload to be canceled.
- // result_cb - to access the status of the operation when available.
- // Possible status codes include:
- // Status::STATUS_OK if none of the above errors occurred.
- void CancelPayload(std::int64_t payload_id, ResultCallback callback);
-
- // Disconnects from a remote endpoint. {@link Payload}s can no longer be sent
- // to or received from the endpoint after this method is called.
- //
- // endpoint_id - The identifier for the remote endpoint to disconnect from.
- // result_cb - to access the status of the operation when available.
- // Possible status codes include:
- // Status::STATUS_OK - finished successfully.
- void DisconnectFromEndpoint(absl::string_view endpoint_id,
- ResultCallback callback);
-
- // Disconnects from, and removes all traces of, all connected and/or
- // discovered endpoints. This call is expected to be preceded by a call to
- // StopAdvertising or StartDiscovery as needed. After calling
- // StopAllEndpoints, no further operations with remote endpoints will be
- // possible until a new call to one of StartAdvertising() or StartDiscovery().
- //
- // result_cb - to access the status of the operation when available.
- // Possible status codes include:
- // Status::STATUS_OK - finished successfully.
- void StopAllEndpoints(ResultCallback callback);
-
- // Sends a request to initiate connection bandwidth upgrade.
- //
- // endpoint_id - The identifier for the remote endpoint which will be
- // switching to a higher connection data rate and possibly
- // different wireless protocol. On success, calls
- // ConnectionListener::bandwidth_changed_cb().
- // result_cb - to access the status of the operation when available.
- // Possible status codes include:
- // Status::STATUS_OK - finished successfully.
- void InitiateBandwidthUpgrade(absl::string_view endpoint_id,
- ResultCallback callback);
-
- // Gets the local endpoint generated by Nearby Connections.
- std::string GetLocalEndpointId() { return client_.GetLocalEndpointId(); }
-
- private:
- ClientProxy client_;
- ServiceControllerRouter* router_ = nullptr;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_CORE_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/core_test.cc b/chromium/third_party/nearby/src/cpp/core/core_test.cc
deleted file mode 100644
index 982baae7ac2..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/core_test.cc
+++ /dev/null
@@ -1,52 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/core.h"
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/time/clock.h"
-#include "core/internal/mock_service_controller_router.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-
-TEST(CoreTest, ConstructorDestructorWorks) {
- MockServiceControllerRouter mock;
- // Called when Core is destroyed.
- EXPECT_CALL(mock, StopAllEndpoints)
- .WillOnce([&](ClientProxy* client, const ResultCallback& callback) {
- callback.result_cb({Status::kSuccess});
- });
- Core core{&mock};
-}
-
-TEST(CoreTest, DestructorReportsFatalFailure) {
- ASSERT_DEATH(
- {
- MockServiceControllerRouter mock;
- // Never invoke the result callback so ~Core will time out.
- EXPECT_CALL(mock, StopAllEndpoints);
- Core core{&mock};
- },
- "Unable to shutdown");
-}
-
-} // namespace
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/event_logger.h b/chromium/third_party/nearby/src/cpp/core/event_logger.h
deleted file mode 100644
index 3602c5a58ca..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/event_logger.h
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_EVENT_LOGGER_H_
-#define CORE_EVENT_LOGGER_H_
-
-#include "proto/analytics/connections_log.pb.h"
-
-namespace location {
-namespace nearby {
-namespace analytics {
-
-// Allows callers to log |ConnectionsLog| collected at Nearby Connections
-// library. Callers need to implement the API if they want to collect this log.
-class EventLogger {
- public:
- virtual ~EventLogger() = default;
-
- // Logs |ConnectionsLog| details. Might block to do I/O, e.g. upload
- // synchronously to some metrics server.
- virtual void Log(const proto::ConnectionsLog& connections_log) = 0;
-};
-
-} // namespace analytics
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_EVENT_LOGGER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/BUILD b/chromium/third_party/nearby/src/cpp/core/internal/BUILD
deleted file mode 100644
index 9247f02e790..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/BUILD
+++ /dev/null
@@ -1,214 +0,0 @@
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# https://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-licenses(["notice"])
-
-cc_library(
- name = "internal",
- srcs = [
- "base_endpoint_channel.cc",
- "base_pcp_handler.cc",
- "ble_advertisement.cc",
- "ble_endpoint_channel.cc",
- "bluetooth_bwu_handler.cc",
- "bluetooth_device_name.cc",
- "bluetooth_endpoint_channel.cc",
- "bwu_manager.cc",
- "client_proxy.cc",
- "encryption_runner.cc",
- "endpoint_channel_manager.cc",
- "endpoint_manager.cc",
- "injected_bluetooth_device_store.cc",
- "internal_payload.cc",
- "internal_payload_factory.cc",
- "offline_frames.cc",
- "offline_frames_validator.cc",
- "offline_service_controller.cc",
- "p2p_cluster_pcp_handler.cc",
- "p2p_point_to_point_pcp_handler.cc",
- "p2p_star_pcp_handler.cc",
- "payload_manager.cc",
- "pcp_manager.cc",
- "service_controller_router.cc",
- "webrtc_bwu_handler.cc",
- "webrtc_endpoint_channel.cc",
- "wifi_lan_bwu_handler.cc",
- "wifi_lan_endpoint_channel.cc",
- "wifi_lan_service_info.cc",
- ],
- hdrs = [
- "base_bwu_handler.h",
- "base_endpoint_channel.h",
- "base_pcp_handler.h",
- "ble_advertisement.h",
- "ble_endpoint_channel.h",
- "bluetooth_bwu_handler.h",
- "bluetooth_device_name.h",
- "bluetooth_endpoint_channel.h",
- "bwu_handler.h",
- "bwu_manager.h",
- "client_proxy.h",
- "encryption_runner.h",
- "endpoint_channel.h",
- "endpoint_channel_manager.h",
- "endpoint_manager.h",
- "injected_bluetooth_device_store.h",
- "internal_payload.h",
- "internal_payload_factory.h",
- "offline_frames.h",
- "offline_frames_validator.h",
- "offline_service_controller.h",
- "p2p_cluster_pcp_handler.h",
- "p2p_point_to_point_pcp_handler.h",
- "p2p_star_pcp_handler.h",
- "payload_manager.h",
- "pcp.h",
- "pcp_handler.h",
- "pcp_manager.h",
- "service_controller.h",
- "service_controller_router.h",
- "webrtc_bwu_handler.h",
- "webrtc_endpoint_channel.h",
- "wifi_lan_bwu_handler.h",
- "wifi_lan_endpoint_channel.h",
- "wifi_lan_service_info.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- copts = ["-DCORE_ADAPTER_DLL"],
- visibility = [
- "//core:__pkg__",
- "//core/internal/fuzzers:__pkg__",
- ],
- deps = [
- ":message_lite",
- "//absl/base:core_headers",
- "//absl/container:btree",
- "//absl/container:flat_hash_map",
- "//absl/container:flat_hash_set",
- "//absl/functional:bind_front",
- "//absl/memory",
- "//absl/strings",
- "//absl/time",
- "//absl/types:span",
- "//analytics",
- "//core:core_types",
- "//core/internal/mediums",
- "//core/internal/mediums:utils",
- "//core/internal/mediums/webrtc",
- "//platform/api:comm",
- "//platform/base",
- "//platform/base:cancellation_flag",
- "//platform/base:error_code_recorder",
- "//platform/base:util",
- "//platform/public:comm",
- "//platform/public:logging",
- "//platform/public:types",
- "//proto:connections_enums_portable_proto",
- "//proto/connections:offline_wire_formats_portable_proto",
- "//securegcm:ukey2",
- ],
-)
-
-cc_library(
- name = "message_lite",
- hdrs = [
- "message_lite.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- visibility = [
- "//core:__subpackages__",
- ],
- deps = [
- "//net/proto2/compat/public:proto2_lite",
- ],
-)
-
-cc_library(
- name = "internal_test",
- testonly = True,
- srcs = [
- "offline_simulation_user.cc",
- "simulation_user.cc",
- ],
- hdrs = [
- "mock_service_controller.h",
- "mock_service_controller_router.h",
- "offline_simulation_user.h",
- "simulation_user.h",
- ],
- visibility = [
- "//core:__subpackages__",
- ],
- deps = [
- ":internal",
- "//testing/base/public:gunit_for_library_testonly",
- "//absl/functional:bind_front",
- "//absl/strings",
- "//core:core_types",
- "//platform/base",
- "//platform/base:test_util",
- "//platform/public:types",
- ],
-)
-
-cc_test(
- name = "core_internal_test",
- size = "small",
- timeout = "moderate",
- srcs = [
- "base_endpoint_channel_test.cc",
- "base_pcp_handler_test.cc",
- "ble_advertisement_test.cc",
- "bluetooth_device_name_test.cc",
- "bwu_manager_test.cc",
- "client_proxy_test.cc",
- "encryption_runner_test.cc",
- "endpoint_channel_manager_test.cc",
- "endpoint_manager_test.cc",
- "injected_bluetooth_device_store_test.cc",
- "internal_payload_factory_test.cc",
- "offline_frames_test.cc",
- "offline_frames_validator_test.cc",
- "offline_service_controller_test.cc",
- "p2p_cluster_pcp_handler_test.cc",
- "payload_manager_test.cc",
- "pcp_manager_test.cc",
- "service_controller_router_test.cc",
- "wifi_lan_service_info_test.cc",
- ],
- shard_count = 16,
- deps = [
- ":internal",
- ":internal_test",
- "//testing/base/public:gunit",
- "//testing/base/public:gunit_main",
- "//absl/container:flat_hash_set",
- "//absl/strings",
- "//absl/synchronization",
- "//absl/time",
- "//absl/types:span",
- "//analytics",
- "//core:core_types",
- "//core/internal/mediums",
- "//core/internal/mediums:utils",
- "//platform/base",
- "//platform/base:test_util",
- "//platform/impl/g3", # build_cleaner: keep
- "//platform/public:comm",
- "//platform/public:logging",
- "//platform/public:types",
- "//proto:connections_enums_portable_proto",
- "//proto/connections:offline_wire_formats_portable_proto",
- "//securegcm:ukey2",
- ],
-)
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/base_bwu_handler.h b/chromium/third_party/nearby/src/cpp/core/internal/base_bwu_handler.h
deleted file mode 100644
index e26ca7b7450..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/base_bwu_handler.h
+++ /dev/null
@@ -1,58 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_BASE_BWU_HANDLER_H_
-#define CORE_INTERNAL_BASE_BWU_HANDLER_H_
-
-#include <cstdint>
-#include <memory>
-#include <string>
-
-#include "absl/container/flat_hash_map.h"
-#include "absl/time/clock.h"
-#include "core/internal/bwu_handler.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/endpoint_channel_manager.h"
-#include "platform/public/cancelable_alarm.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/scheduled_executor.h"
-#include "platform/public/single_thread_executor.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-class BaseBwuHandler : public BwuHandler {
- public:
- using ClientIntroduction = BwuNegotiationFrame::ClientIntroduction;
-
- BaseBwuHandler(EndpointChannelManager& channel_manager,
- BwuNotifications bwu_notifications)
- : channel_manager_(&channel_manager),
- bwu_notifications_(std::move(bwu_notifications)) {}
- ~BaseBwuHandler() override = default;
-
- protected:
- // Represents the incoming Socket the Initiator has gotten after initializing
- // its upgraded bandwidth medium.
- EndpointChannelManager* GetEndpointChannelManager();
- EndpointChannelManager* channel_manager_;
- BwuNotifications bwu_notifications_;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_BASE_BWU_HANDLER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/base_endpoint_channel.cc b/chromium/third_party/nearby/src/cpp/core/internal/base_endpoint_channel.cc
deleted file mode 100644
index bdc0d743ffe..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/base_endpoint_channel.cc
+++ /dev/null
@@ -1,364 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/base_endpoint_channel.h"
-
-#include <cassert>
-
-#include "absl/strings/escaping.h"
-#include "absl/strings/str_cat.h"
-#include "core/internal/offline_frames.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/exception.h"
-#include "platform/public/logging.h"
-#include "platform/public/mutex.h"
-#include "platform/public/mutex_lock.h"
-#include "proto/connections_enums.pb.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-namespace {
-
-std::int32_t BytesToInt(const ByteArray& bytes) {
- const char* int_bytes = bytes.data();
-
- std::int32_t result = 0;
- result |= (static_cast<std::int32_t>(int_bytes[0]) & 0x0FF) << 24;
- result |= (static_cast<std::int32_t>(int_bytes[1]) & 0x0FF) << 16;
- result |= (static_cast<std::int32_t>(int_bytes[2]) & 0x0FF) << 8;
- result |= (static_cast<std::int32_t>(int_bytes[3]) & 0x0FF);
-
- return result;
-}
-
-ByteArray IntToBytes(std::int32_t value) {
- char int_bytes[sizeof(std::int32_t)];
- int_bytes[0] = static_cast<char>((value >> 24) & 0x0FF);
- int_bytes[1] = static_cast<char>((value >> 16) & 0x0FF);
- int_bytes[2] = static_cast<char>((value >> 8) & 0x0FF);
- int_bytes[3] = static_cast<char>((value)&0x0FF);
-
- return ByteArray(int_bytes, sizeof(int_bytes));
-}
-
-ExceptionOr<ByteArray> ReadExactly(InputStream* reader, std::int64_t size) {
- ByteArray buffer(size);
- std::int64_t current_pos = 0;
-
- while (current_pos < size) {
- ExceptionOr<ByteArray> read_bytes = reader->Read(size - current_pos);
- if (!read_bytes.ok()) {
- return read_bytes;
- }
- ByteArray result = read_bytes.result();
-
- if (result.Empty()) {
- NEARBY_LOGS(WARNING) << __func__ << ": Empty result when reading bytes.";
- return ExceptionOr<ByteArray>(Exception::kIo);
- }
-
- buffer.CopyAt(current_pos, result);
- current_pos += result.size();
- }
-
- return ExceptionOr<ByteArray>(std::move(buffer));
-}
-
-ExceptionOr<std::int32_t> ReadInt(InputStream* reader) {
- ExceptionOr<ByteArray> read_bytes = ReadExactly(reader, sizeof(std::int32_t));
- if (!read_bytes.ok()) {
- return ExceptionOr<std::int32_t>(read_bytes.exception());
- }
- return ExceptionOr<std::int32_t>(BytesToInt(std::move(read_bytes.result())));
-}
-
-Exception WriteInt(OutputStream* writer, std::int32_t value) {
- return writer->Write(IntToBytes(value));
-}
-
-} // namespace
-
-BaseEndpointChannel::BaseEndpointChannel(const std::string& channel_name,
- InputStream* reader,
- OutputStream* writer)
- : channel_name_(channel_name), reader_(reader), writer_(writer) {}
-
-ExceptionOr<ByteArray> BaseEndpointChannel::Read() {
- ByteArray result;
- {
- MutexLock lock(&reader_mutex_);
-
- ExceptionOr<std::int32_t> read_int = ReadInt(reader_);
- if (!read_int.ok()) {
- return ExceptionOr<ByteArray>(read_int.exception());
- }
-
- if (read_int.result() < 0 || read_int.result() > kMaxAllowedReadBytes) {
- NEARBY_LOGS(WARNING) << __func__ << ": Read an invalid number of bytes: "
- << read_int.result();
- return ExceptionOr<ByteArray>(Exception::kIo);
- }
-
- ExceptionOr<ByteArray> read_bytes = ReadExactly(reader_, read_int.result());
- if (!read_bytes.ok()) {
- return read_bytes;
- }
- result = std::move(read_bytes.result());
- }
-
- {
- MutexLock crypto_lock(&crypto_mutex_);
- if (IsEncryptionEnabledLocked()) {
- // If encryption is enabled, decode the message.
- std::string input(std::move(result));
- std::unique_ptr<std::string> decrypted_data =
- crypto_context_->DecodeMessageFromPeer(input);
- if (decrypted_data) {
- result = ByteArray(std::move(*decrypted_data));
- } else {
- // It could be a protocol race, where remote party sends a KEEP_ALIVE
- // before encryption is setup on their side, and we receive it after
- // we switched to encryption mode.
- // In this case, we verify that message is indeed a valid KEEP_ALIVE,
- // and let it through if it is, otherwise message is erased.
- // TODO(apolyudov): verify this happens at most once per session.
- result = {};
- auto parsed = parser::FromBytes(ByteArray(input));
- if (parsed.ok()) {
- if (parser::GetFrameType(parsed.result()) == V1Frame::KEEP_ALIVE) {
- NEARBY_LOGS(INFO)
- << __func__
- << ": Read unencrypted KEEP_ALIVE on encrypted channel.";
- result = ByteArray(input);
- } else {
- NEARBY_LOGS(WARNING)
- << __func__ << ": Read unexpected unencrypted frame of type "
- << parser::GetFrameType(parsed.result());
- }
- } else {
- NEARBY_LOGS(WARNING)
- << __func__ << ": Unable to parse data as unencrypted message.";
- }
- }
- if (result.Empty()) {
- NEARBY_LOGS(WARNING) << __func__ << ": Unable to parse read result.";
- return ExceptionOr<ByteArray>(Exception::kInvalidProtocolBuffer);
- }
- }
- }
-
- {
- MutexLock lock(&last_read_mutex_);
- last_read_timestamp_ = SystemClock::ElapsedRealtime();
- }
- return ExceptionOr<ByteArray>(result);
-}
-
-Exception BaseEndpointChannel::Write(const ByteArray& data) {
- {
- MutexLock pause_lock(&is_paused_mutex_);
- if (is_paused_) {
- BlockUntilUnpaused();
- }
- }
-
- ByteArray encrypted_data;
- const ByteArray* data_to_write = &data;
- {
- // Holding both mutexes is necessary to prevent the keep alive and payload
- // threads from writing encrypted messages out of order which causes a
- // failure to decrypt on the reader side. However we need to release the
- // crypto lock after encrypting to ensure read decryption is not blocked.
- MutexLock lock(&writer_mutex_);
- {
- MutexLock crypto_lock(&crypto_mutex_);
- if (IsEncryptionEnabledLocked()) {
- // If encryption is enabled, encode the message.
- std::unique_ptr<std::string> encrypted =
- crypto_context_->EncodeMessageToPeer(std::string(data));
- if (!encrypted) {
- NEARBY_LOGS(WARNING) << __func__ << ": Failed to encrypt data.";
- return {Exception::kIo};
- }
- encrypted_data = ByteArray(std::move(*encrypted));
- data_to_write = &encrypted_data;
- }
- }
-
- Exception write_exception =
- WriteInt(writer_, static_cast<std::int32_t>(data_to_write->size()));
- if (write_exception.Raised()) {
- NEARBY_LOGS(WARNING) << __func__ << ": Failed to write header: "
- << write_exception.value;
- return write_exception;
- }
- write_exception = writer_->Write(*data_to_write);
- if (write_exception.Raised()) {
- NEARBY_LOGS(WARNING) << __func__ << ": Failed to write data: "
- << write_exception.value;
- return write_exception;
- }
- Exception flush_exception = writer_->Flush();
- if (flush_exception.Raised()) {
- NEARBY_LOGS(WARNING) << __func__ << ": Failed to flush writer: "
- << flush_exception.value;
- return flush_exception;
- }
- }
-
- {
- MutexLock lock(&last_write_mutex_);
- last_write_timestamp_ = SystemClock::ElapsedRealtime();
- }
- return {Exception::kSuccess};
-}
-
-void BaseEndpointChannel::Close() {
- {
- // In case channel is paused, resume it first thing.
- MutexLock lock(&is_paused_mutex_);
- UnblockPausedWriter();
- }
- CloseIo();
- CloseImpl();
-}
-
-void BaseEndpointChannel::CloseIo() {
- // Keep this method dedicated to reader and writer handling an nothing else.
- {
- // Do not take reader_mutex_ here: read may be in progress, and it will
- // deadlock. Calling Close() with Read() in progress will terminate the
- // IO and Read() will proceed normally (with Exception::kIo).
- Exception exception = reader_->Close();
- if (!exception.Ok()) {
- NEARBY_LOGS(WARNING) << __func__
- << ": Exception closing reader: " << exception.value;
- }
- }
- {
- // Do not take writer_mutex_ here: write may be in progress, and it will
- // deadlock. Calling Close() with Write() in progress will terminate the
- // IO and Write() will proceed normally (with Exception::kIo).
- Exception exception = writer_->Close();
- if (!exception.Ok()) {
- NEARBY_LOGS(WARNING) << __func__
- << ": Exception closing writer: " << exception.value;
- }
- }
-}
-
-void BaseEndpointChannel::SetAnalyticsRecorder(
- analytics::AnalyticsRecorder* analytics_recorder,
- const std::string& endpoint_id) {
- analytics_recorder_ = analytics_recorder;
- endpoint_id_ = endpoint_id;
-}
-
-void BaseEndpointChannel::Close(
- proto::connections::DisconnectionReason reason) {
- NEARBY_LOGS(INFO) << __func__
- << ": Closing endpoint channel, reason: " << reason;
- Close();
-
- if (analytics_recorder_ != nullptr && !endpoint_id_.empty()) {
- analytics_recorder_->OnConnectionClosed(endpoint_id_, GetMedium(), reason);
- }
-}
-
-std::string BaseEndpointChannel::GetType() const {
- MutexLock crypto_lock(&crypto_mutex_);
- std::string subtype = IsEncryptionEnabledLocked() ? "ENCRYPTED_" : "";
- std::string medium = proto::connections::Medium_Name(
- proto::connections::Medium::UNKNOWN_MEDIUM);
-
- if (GetMedium() != proto::connections::Medium::UNKNOWN_MEDIUM) {
- medium =
- absl::StrCat(subtype, proto::connections::Medium_Name(GetMedium()));
- }
- return medium;
-}
-
-std::string BaseEndpointChannel::GetName() const { return channel_name_; }
-
-int BaseEndpointChannel::GetMaxTransmitPacketSize() const {
- // Return default value if the medium never define it's chunk size.
- return kDefaultMaxTransmitPacketSize;
-}
-
-void BaseEndpointChannel::EnableEncryption(
- std::shared_ptr<EncryptionContext> context) {
- MutexLock crypto_lock(&crypto_mutex_);
- crypto_context_ = context;
-}
-
-void BaseEndpointChannel::DisableEncryption() {
- MutexLock crypto_lock(&crypto_mutex_);
- crypto_context_.reset();
-}
-
-bool BaseEndpointChannel::IsPaused() const {
- MutexLock lock(&is_paused_mutex_);
- return is_paused_;
-}
-
-void BaseEndpointChannel::Pause() {
- MutexLock lock(&is_paused_mutex_);
- is_paused_ = true;
-}
-
-void BaseEndpointChannel::Resume() {
- MutexLock lock(&is_paused_mutex_);
- is_paused_ = false;
- is_paused_cond_.Notify();
-}
-
-absl::Time BaseEndpointChannel::GetLastReadTimestamp() const {
- MutexLock lock(&last_read_mutex_);
- return last_read_timestamp_;
-}
-
-absl::Time BaseEndpointChannel::GetLastWriteTimestamp() const {
- MutexLock lock(&last_write_mutex_);
- return last_write_timestamp_;
-}
-
-bool BaseEndpointChannel::IsEncryptionEnabledLocked() const {
- return crypto_context_ != nullptr;
-}
-
-void BaseEndpointChannel::BlockUntilUnpaused() {
- // For more on how this works, see
- // https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html
- while (is_paused_) {
- Exception wait_succeeded = is_paused_cond_.Wait();
- if (!wait_succeeded.Ok()) {
- NEARBY_LOGS(WARNING) << __func__ << ": Failure waiting to unpause: "
- << wait_succeeded.value;
- return;
- }
- }
-}
-
-void BaseEndpointChannel::UnblockPausedWriter() {
- // For more on how this works, see
- // https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html
- is_paused_ = false;
- is_paused_cond_.Notify();
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/base_endpoint_channel.h b/chromium/third_party/nearby/src/cpp/core/internal/base_endpoint_channel.h
deleted file mode 100644
index 94518bda306..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/base_endpoint_channel.h
+++ /dev/null
@@ -1,156 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_BASE_ENDPOINT_CHANNEL_H_
-#define CORE_INTERNAL_BASE_ENDPOINT_CHANNEL_H_
-
-#include <cstdint>
-#include <memory>
-#include <string>
-
-#include "securegcm/d2d_connection_context_v1.h"
-#include "absl/base/thread_annotations.h"
-#include "analytics/analytics_recorder.h"
-#include "core/internal/endpoint_channel.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/input_stream.h"
-#include "platform/base/output_stream.h"
-#include "platform/public/atomic_reference.h"
-#include "platform/public/condition_variable.h"
-#include "platform/public/mutex.h"
-#include "platform/public/system_clock.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-class BaseEndpointChannel : public EndpointChannel {
- public:
- BaseEndpointChannel(const std::string& channel_name, InputStream* reader,
- OutputStream* writer);
- ~BaseEndpointChannel() override = default;
-
- ExceptionOr<ByteArray> Read()
- ABSL_LOCKS_EXCLUDED(reader_mutex_, crypto_mutex_,
- last_read_mutex_) override;
-
- Exception Write(const ByteArray& data)
- ABSL_LOCKS_EXCLUDED(writer_mutex_, crypto_mutex_) override;
-
- // Closes this EndpointChannel, without tracking the closure in analytics.
- void Close() ABSL_LOCKS_EXCLUDED(is_paused_mutex_) override;
-
- // Closes this EndpointChannel and records the closure with the given reason.
- void Close(proto::connections::DisconnectionReason reason) override;
-
- // Returns a one-word type descriptor for the concrete EndpointChannel
- // implementation that can be used in log messages; eg: BLUETOOTH, BLE,
- // WIFI.
- std::string GetType() const override;
-
- // Returns the name of the EndpointChannel.
- std::string GetName() const override;
-
- // Returns the maximum supported transmit packet size(MTU) for the underlying
- // transport.
- int GetMaxTransmitPacketSize() const override;
-
- // Enables encryption on the EndpointChannel.
- // Should be called after connection is accepted by both parties, and
- // before entering data phase, where Payloads may be exchanged.
- void EnableEncryption(std::shared_ptr<EncryptionContext> context) override;
-
- // Disables encryption on the EndpointChannel.
- void DisableEncryption() override;
-
- // True if the EndpointChannel is currently pausing all writes.
- bool IsPaused() const ABSL_LOCKS_EXCLUDED(is_paused_mutex_) override;
-
- // Pauses all writes on this EndpointChannel until resume() is called.
- void Pause() ABSL_LOCKS_EXCLUDED(is_paused_mutex_) override;
-
- // Resumes any writes on this EndpointChannel that were suspended when pause()
- // was called.
- void Resume() ABSL_LOCKS_EXCLUDED(is_paused_mutex_) override;
-
- // Returns the timestamp (returned by ElapsedRealtime) of the last read from
- // this endpoint, or -1 if no reads have occurred.
- absl::Time GetLastReadTimestamp() const
- ABSL_LOCKS_EXCLUDED(last_read_mutex_) override;
-
- // Returns the timestamp (returned by ElapsedRealtime) of the last write to
- // this endpoint, or -1 if no writes have occurred.
- absl::Time GetLastWriteTimestamp() const
- ABSL_LOCKS_EXCLUDED(last_write_mutex_) override;
-
- void SetAnalyticsRecorder(analytics::AnalyticsRecorder* analytics_recorder,
- const std::string& endpoint_id) override;
-
- protected:
- virtual void CloseImpl() = 0;
-
- private:
- // Used to sanity check that our frame sizes are reasonable.
- static constexpr std::int32_t kMaxAllowedReadBytes = 1048576; // 1MB
-
- // The default maximum transmit unit/packet size.
- static constexpr int kDefaultMaxTransmitPacketSize = 65536; // 64 KB
-
- bool IsEncryptionEnabledLocked() const
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(crypto_mutex_);
- void UnblockPausedWriter() ABSL_EXCLUSIVE_LOCKS_REQUIRED(is_paused_mutex_);
- void BlockUntilUnpaused() ABSL_EXCLUSIVE_LOCKS_REQUIRED(is_paused_mutex_);
- void CloseIo() ABSL_NO_THREAD_SAFETY_ANALYSIS;
-
- // We need a separate mutex to protect read timestamp, because if a read
- // blocks on IO, we don't want timestamp read access to block too.
- mutable Mutex last_read_mutex_;
- absl::Time last_read_timestamp_ ABSL_GUARDED_BY(last_read_mutex_) =
- absl::InfinitePast();
-
- // We need a separate mutex to protect write timestamp, because if a write
- // blocks on IO, we don't want timestamp write access to block too.
- mutable Mutex last_write_mutex_;
- absl::Time last_write_timestamp_ ABSL_GUARDED_BY(last_write_mutex_) =
- absl::InfinitePast();
-
- const std::string channel_name_;
-
- // The reader and writer are synchronized independently since we can't have
- // writes waiting on reads that might potentially block forever.
- Mutex reader_mutex_;
- InputStream* reader_ ABSL_PT_GUARDED_BY(reader_mutex_);
-
- Mutex writer_mutex_;
- OutputStream* writer_ ABSL_PT_GUARDED_BY(writer_mutex_);
-
- // An encryptor/decryptor. May be null.
- mutable Mutex crypto_mutex_;
- std::shared_ptr<EncryptionContext> crypto_context_
- ABSL_GUARDED_BY(crypto_mutex_) ABSL_PT_GUARDED_BY(crypto_mutex_);
-
- mutable Mutex is_paused_mutex_;
- ConditionVariable is_paused_cond_{&is_paused_mutex_};
- // If true, writes should block until this has been set to false.
- bool is_paused_ ABSL_GUARDED_BY(is_paused_mutex_) = false;
-
- analytics::AnalyticsRecorder* analytics_recorder_ = nullptr;
- std::string endpoint_id_ = "";
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_BASE_ENDPOINT_CHANNEL_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/base_endpoint_channel_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/base_endpoint_channel_test.cc
deleted file mode 100644
index 9d8ebc7e569..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/base_endpoint_channel_test.cc
+++ /dev/null
@@ -1,409 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/base_endpoint_channel.h"
-
-#include <functional>
-#include <string>
-#include <utility>
-
-#include "securegcm/d2d_connection_context_v1.h"
-#include "securegcm/ukey2_handshake.h"
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/synchronization/mutex.h"
-#include "absl/time/time.h"
-#include "core/internal/encryption_runner.h"
-#include "core/internal/offline_frames.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/exception.h"
-#include "platform/base/input_stream.h"
-#include "platform/base/output_stream.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/logging.h"
-#include "platform/public/multi_thread_executor.h"
-#include "platform/public/pipe.h"
-#include "platform/public/single_thread_executor.h"
-#include "proto/connections_enums.pb.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-
-using ::location::nearby::proto::connections::DisconnectionReason;
-using ::location::nearby::proto::connections::Medium;
-using EncryptionContext = BaseEndpointChannel::EncryptionContext;
-
-class TestEndpointChannel : public BaseEndpointChannel {
- public:
- explicit TestEndpointChannel(InputStream* input, OutputStream* output)
- : BaseEndpointChannel("channel", input, output) {}
-
- MOCK_METHOD(Medium, GetMedium, (), (const override));
- MOCK_METHOD(void, CloseImpl, (), (override));
-};
-
-std::function<void()> MakeDataPump(
- std::string label, InputStream* input, OutputStream* output,
- std::function<void(const ByteArray&)> monitor = nullptr) {
- return [label, input, output, monitor]() {
- NEARBY_LOGS(INFO) << "streaming data through '" << label << "'";
- while (true) {
- auto read_response = input->Read(Pipe::kChunkSize);
- if (!read_response.ok()) {
- NEARBY_LOGS(INFO) << "Peer reader closed on '" << label << "'";
- output->Close();
- break;
- }
- if (monitor) {
- monitor(read_response.result());
- }
- auto write_response = output->Write(read_response.result());
- if (write_response.Raised()) {
- NEARBY_LOGS(INFO) << "Peer writer closed on '" << label << "'";
- input->Close();
- break;
- }
- }
- NEARBY_LOGS(INFO) << "streaming terminated on '" << label << "'";
- };
-}
-
-std::function<void(const ByteArray&)> MakeDataMonitor(const std::string& label,
- std::string* capture,
- absl::Mutex* mutex) {
- return [label, capture, mutex](const ByteArray& input) mutable {
- std::string s = std::string(input);
- {
- absl::MutexLock lock(mutex);
- *capture += s;
- }
- NEARBY_LOGS(INFO) << "source='" << label << "'"
- << "; message='" << s << "'";
- };
-}
-
-std::pair<std::shared_ptr<EncryptionContext>,
- std::shared_ptr<EncryptionContext>>
-DoDhKeyExchange(BaseEndpointChannel* channel_a,
- BaseEndpointChannel* channel_b) {
- std::shared_ptr<EncryptionContext> context_a;
- std::shared_ptr<EncryptionContext> context_b;
- EncryptionRunner crypto_a;
- EncryptionRunner crypto_b;
- ClientProxy proxy_a;
- ClientProxy proxy_b;
- CountDownLatch latch(2);
- crypto_a.StartClient(
- &proxy_a, "endpoint_id", channel_a,
- {
- .on_success_cb =
- [&latch, &context_a](
- const std::string& endpoint_id,
- std::unique_ptr<securegcm::UKey2Handshake> ukey2,
- const std::string& auth_token,
- const ByteArray& raw_auth_token) {
- NEARBY_LOGS(INFO) << "client-A side key negotiation done";
- EXPECT_TRUE(ukey2->VerifyHandshake());
- auto context = ukey2->ToConnectionContext();
- EXPECT_NE(context, nullptr);
- context_a = std::move(context);
- latch.CountDown();
- },
- .on_failure_cb =
- [&latch](const std::string& endpoint_id,
- EndpointChannel* channel) {
- NEARBY_LOGS(INFO) << "client-A side key negotiation failed";
- latch.CountDown();
- },
- });
- crypto_b.StartServer(
- &proxy_b, "endpoint_id", channel_b,
- {
- .on_success_cb =
- [&latch, &context_b](
- const std::string& endpoint_id,
- std::unique_ptr<securegcm::UKey2Handshake> ukey2,
- const std::string& auth_token,
- const ByteArray& raw_auth_token) {
- NEARBY_LOGS(INFO) << "client-B side key negotiation done";
- EXPECT_TRUE(ukey2->VerifyHandshake());
- auto context = ukey2->ToConnectionContext();
- EXPECT_NE(context, nullptr);
- context_b = std::move(context);
- latch.CountDown();
- },
- .on_failure_cb =
- [&latch](const std::string& endpoint_id,
- EndpointChannel* channel) {
- NEARBY_LOGS(INFO) << "client-B side key negotiation failed";
- latch.CountDown();
- },
- });
- EXPECT_TRUE(latch.Await(absl::Milliseconds(5000)).result());
- return std::make_pair(std::move(context_a), std::move(context_b));
-}
-
-TEST(BaseEndpointChannelTest, ConstructorDestructorWorks) {
- Pipe pipe;
- InputStream& input_stream = pipe.GetInputStream();
- OutputStream& output_stream = pipe.GetOutputStream();
-
- TestEndpointChannel test_channel(&input_stream, &output_stream);
-}
-
-TEST(BaseEndpointChannelTest, ReadWrite) {
- // Direct not-encrypted IO.
- Pipe pipe_a; // channel_a writes to pipe_a, reads from pipe_b.
- Pipe pipe_b; // channel_b writes to pipe_b, reads from pipe_a.
- TestEndpointChannel channel_a(&pipe_b.GetInputStream(),
- &pipe_a.GetOutputStream());
- TestEndpointChannel channel_b(&pipe_a.GetInputStream(),
- &pipe_b.GetOutputStream());
- ByteArray tx_message{"data message"};
- channel_a.Write(tx_message);
- ByteArray rx_message = std::move(channel_b.Read().result());
- EXPECT_EQ(rx_message, tx_message);
-}
-
-TEST(BaseEndpointChannelTest, NotEncryptedReadWriteCanBeIntercepted) {
- // Not encrypted IO; MITM scenario.
-
- // Setup test communication environment.
- absl::Mutex mutex;
- std::string capture_a;
- std::string capture_b;
- Pipe client_a; // Channel "a" writes to client "a", reads from server "a".
- Pipe client_b; // Channel "b" writes to client "b", reads from server "b".
- Pipe server_a; // Data pump "a" reads from client "a", writes to server "b".
- Pipe server_b; // Data pump "b" reads from client "b", writes to server "a".
- TestEndpointChannel channel_a(&server_a.GetInputStream(),
- &client_a.GetOutputStream());
- TestEndpointChannel channel_b(&server_b.GetInputStream(),
- &client_b.GetOutputStream());
-
- ON_CALL(channel_a, GetMedium).WillByDefault([]() { return Medium::BLE; });
- ON_CALL(channel_b, GetMedium).WillByDefault([]() { return Medium::BLE; });
-
- MultiThreadExecutor executor(2);
- executor.Execute(MakeDataPump(
- "pump_a", &client_a.GetInputStream(), &server_b.GetOutputStream(),
- MakeDataMonitor("monitor_a", &capture_a, &mutex)));
- executor.Execute(MakeDataPump(
- "pump_b", &client_b.GetInputStream(), &server_a.GetOutputStream(),
- MakeDataMonitor("monitor_b", &capture_b, &mutex)));
-
- EXPECT_EQ(channel_a.GetType(), "BLE");
- EXPECT_EQ(channel_b.GetType(), "BLE");
-
- // Start data transfer
- ByteArray tx_message{"data message"};
- channel_a.Write(tx_message);
- ByteArray rx_message = std::move(channel_b.Read().result());
-
- // Verify expectations.
- EXPECT_EQ(rx_message, tx_message);
- {
- absl::MutexLock lock(&mutex);
- std::string message{tx_message};
- EXPECT_TRUE(capture_a.find(message) != std::string::npos ||
- capture_b.find(message) != std::string::npos);
- }
-
- // Shutdown test environment.
- channel_a.Close(DisconnectionReason::LOCAL_DISCONNECTION);
- channel_b.Close(DisconnectionReason::REMOTE_DISCONNECTION);
-}
-
-TEST(BaseEndpointChannelTest, EncryptedReadWriteCanNotBeIntercepted) {
- // Encrypted IO; MITM scenario.
-
- // Setup test communication environment.
- absl::Mutex mutex;
- std::string capture_a;
- std::string capture_b;
- Pipe client_a; // Channel "a" writes to client "a", reads from server "a".
- Pipe client_b; // Channel "b" writes to client "b", reads from server "b".
- Pipe server_a; // Data pump "a" reads from client "a", writes to server "b".
- Pipe server_b; // Data pump "b" reads from client "b", writes to server "a".
- TestEndpointChannel channel_a(&server_a.GetInputStream(),
- &client_a.GetOutputStream());
- TestEndpointChannel channel_b(&server_b.GetInputStream(),
- &client_b.GetOutputStream());
-
- ON_CALL(channel_a, GetMedium).WillByDefault([]() {
- return Medium::BLUETOOTH;
- });
- ON_CALL(channel_b, GetMedium).WillByDefault([]() {
- return Medium::BLUETOOTH;
- });
-
- MultiThreadExecutor executor(2);
- executor.Execute(MakeDataPump(
- "pump_a", &client_a.GetInputStream(), &server_b.GetOutputStream(),
- MakeDataMonitor("monitor_a", &capture_a, &mutex)));
- executor.Execute(MakeDataPump(
- "pump_b", &client_b.GetInputStream(), &server_a.GetOutputStream(),
- MakeDataMonitor("monitor_b", &capture_b, &mutex)));
-
- // Run DH key exchange; setup encryption contexts for channels.
- auto [context_a, context_b] = DoDhKeyExchange(&channel_a, &channel_b);
- ASSERT_NE(context_a, nullptr);
- ASSERT_NE(context_b, nullptr);
- channel_a.EnableEncryption(context_a);
- channel_b.EnableEncryption(context_b);
-
- EXPECT_EQ(channel_a.GetType(), "ENCRYPTED_BLUETOOTH");
- EXPECT_EQ(channel_b.GetType(), "ENCRYPTED_BLUETOOTH");
-
- // Start data transfer
- ByteArray tx_message{"data message"};
- channel_a.Write(tx_message);
- ByteArray rx_message = std::move(channel_b.Read().result());
-
- // Verify expectations.
- EXPECT_EQ(rx_message, tx_message);
- {
- absl::MutexLock lock(&mutex);
- std::string message{tx_message};
- EXPECT_TRUE(capture_a.find(message) == std::string::npos &&
- capture_b.find(message) == std::string::npos);
- }
-
- // Shutdown test environment.
- channel_a.Close(DisconnectionReason::LOCAL_DISCONNECTION);
- channel_b.Close(DisconnectionReason::REMOTE_DISCONNECTION);
-}
-
-TEST(BaseEndpointChannelTest, CanBesuspendedAndResumed) {
- // Setup test communication environment.
- Pipe pipe_a; // channel_a writes to pipe_a, reads from pipe_b.
- Pipe pipe_b; // channel_b writes to pipe_b, reads from pipe_a.
- TestEndpointChannel channel_a(&pipe_b.GetInputStream(),
- &pipe_a.GetOutputStream());
- TestEndpointChannel channel_b(&pipe_a.GetInputStream(),
- &pipe_b.GetOutputStream());
-
- ON_CALL(channel_a, GetMedium).WillByDefault([]() {
- return Medium::WIFI_LAN;
- });
- ON_CALL(channel_b, GetMedium).WillByDefault([]() {
- return Medium::WIFI_LAN;
- });
-
- EXPECT_EQ(channel_a.GetType(), "WIFI_LAN");
- EXPECT_EQ(channel_b.GetType(), "WIFI_LAN");
-
- // Start data transfer
- ByteArray tx_message{"data message"};
- ByteArray more_message{"more data"};
- channel_a.Write(tx_message);
- ByteArray rx_message = std::move(channel_b.Read().result());
-
- // Pause and make sure reader blocks.
- MultiThreadExecutor pause_resume_executor(2);
- channel_a.Pause();
- pause_resume_executor.Execute([&channel_a, &more_message]() {
- // Write will block until channel is resumed, or closed.
- EXPECT_TRUE(channel_a.Write(more_message).Ok());
- });
- CountDownLatch latch(1);
- ByteArray read_more;
- pause_resume_executor.Execute([&channel_b, &read_more, &latch]() {
- // Read will block until channel is resumed, or closed.
- auto response = channel_b.Read();
- EXPECT_TRUE(response.ok());
- read_more = std::move(response.result());
- latch.CountDown();
- });
- absl::SleepFor(absl::Milliseconds(500));
- EXPECT_TRUE(read_more.Empty());
-
- // Resume; verify that data transfer comepleted.
- channel_a.Resume();
- EXPECT_TRUE(latch.Await(absl::Milliseconds(1000)).result());
- EXPECT_EQ(read_more, more_message);
-
- // Shutdown test environment.
- channel_a.Close(DisconnectionReason::LOCAL_DISCONNECTION);
- channel_b.Close(DisconnectionReason::REMOTE_DISCONNECTION);
-}
-
-TEST(BaseEndpointChannelTest, ReadAfterInputStreamClosed) {
- Pipe pipe;
- InputStream& input_stream = pipe.GetInputStream();
- OutputStream& output_stream = pipe.GetOutputStream();
-
- TestEndpointChannel test_channel(&input_stream, &output_stream);
-
- // Close the output stream before trying to read from the input.
- output_stream.Close();
-
- // Trying to read should fail gracefully with an IO error.
- ExceptionOr<ByteArray> read_data = test_channel.Read();
-
- ASSERT_FALSE(read_data.ok());
- ASSERT_TRUE(read_data.GetException().Raised(Exception::kIo));
-}
-
-TEST(BaseEndpointChannelTest, ReadUnencryptedFrameOnEncryptedChannel) {
- // Setup test communication environment.
- Pipe pipe_a; // channel_a writes to pipe_a, reads from pipe_b.
- Pipe pipe_b; // channel_b writes to pipe_b, reads from pipe_a.
- TestEndpointChannel channel_a(&pipe_b.GetInputStream(),
- &pipe_a.GetOutputStream());
- TestEndpointChannel channel_b(&pipe_a.GetInputStream(),
- &pipe_b.GetOutputStream());
-
- ON_CALL(channel_a, GetMedium).WillByDefault([]() {
- return Medium::BLUETOOTH;
- });
- ON_CALL(channel_b, GetMedium).WillByDefault([]() {
- return Medium::BLUETOOTH;
- });
-
- // Run DH key exchange; setup encryption contexts for channels. But only
- // encrypt |channel_b|.
- auto [context_a, context_b] = DoDhKeyExchange(&channel_a, &channel_b);
- ASSERT_NE(context_a, nullptr);
- ASSERT_NE(context_b, nullptr);
- channel_b.EnableEncryption(context_b);
-
- EXPECT_EQ(channel_a.GetType(), "BLUETOOTH");
- EXPECT_EQ(channel_b.GetType(), "ENCRYPTED_BLUETOOTH");
-
- // An unencrypted KeepAlive should succeed.
- ByteArray keep_alive_message = parser::ForKeepAlive();
- channel_a.Write(keep_alive_message);
- ExceptionOr<ByteArray> result = channel_b.Read();
- EXPECT_TRUE(result.ok());
- EXPECT_EQ(result.result(), keep_alive_message);
-
- // An unencrypted data frame should fail.
- ByteArray tx_message{"data message"};
- channel_a.Write(tx_message);
- result = channel_b.Read();
- EXPECT_FALSE(result.ok());
- EXPECT_EQ(result.exception(), Exception::kInvalidProtocolBuffer);
-
- // Shutdown test environment.
- channel_a.Close(DisconnectionReason::LOCAL_DISCONNECTION);
- channel_b.Close(DisconnectionReason::REMOTE_DISCONNECTION);
-}
-
-} // namespace
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/base_pcp_handler.cc b/chromium/third_party/nearby/src/cpp/core/internal/base_pcp_handler.cc
deleted file mode 100644
index 8e3bf3e9455..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/base_pcp_handler.cc
+++ /dev/null
@@ -1,1533 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/base_pcp_handler.h"
-
-#include <cassert>
-#include <cinttypes>
-#include <cstdlib>
-#include <limits>
-#include <memory>
-
-#include "securegcm/d2d_connection_context_v1.h"
-#include "securegcm/ukey2_handshake.h"
-#include "absl/container/flat_hash_set.h"
-#include "absl/strings/escaping.h"
-#include "absl/types/span.h"
-#include "core/internal/mediums/utils.h"
-#include "core/internal/offline_frames.h"
-#include "core/internal/pcp_handler.h"
-#include "core/options.h"
-#include "platform/base/base64_utils.h"
-#include "platform/base/bluetooth_utils.h"
-#include "platform/public/logging.h"
-#include "platform/public/system_clock.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-using ::location::nearby::proto::connections::Medium;
-using ::securegcm::UKey2Handshake;
-
-constexpr absl::Duration BasePcpHandler::kConnectionRequestReadTimeout;
-constexpr absl::Duration BasePcpHandler::kRejectedConnectionCloseDelay;
-
-BasePcpHandler::BasePcpHandler(Mediums* mediums,
- EndpointManager* endpoint_manager,
- EndpointChannelManager* channel_manager,
- BwuManager* bwu_manager, Pcp pcp)
- : mediums_(mediums),
- endpoint_manager_(endpoint_manager),
- channel_manager_(channel_manager),
- pcp_(pcp),
- bwu_manager_(bwu_manager) {}
-
-BasePcpHandler::~BasePcpHandler() {
- NEARBY_LOGS(INFO) << "Initiating shutdown of BasePcpHandler("
- << strategy_.GetName() << ")";
- DisconnectFromEndpointManager();
- // Stop all the ongoing Runnables (as gracefully as possible).
- NEARBY_LOGS(INFO) << "BasePcpHandler(" << strategy_.GetName()
- << ") is bringing down executors.";
- serial_executor_.Shutdown();
- alarm_executor_.Shutdown();
- NEARBY_LOGS(INFO) << "BasePcpHandler(" << strategy_.GetName()
- << ") has shut down.";
-}
-
-void BasePcpHandler::DisconnectFromEndpointManager() {
- if (stop_.Set(true)) return;
- NEARBY_LOGS(INFO) << "BasePcpHandler(" << strategy_.GetName()
- << ") unregister from EPM.";
- // Unregister ourselves from EPM message dispatcher.
- endpoint_manager_->UnregisterFrameProcessor(V1Frame::CONNECTION_RESPONSE,
- this);
-}
-
-Status BasePcpHandler::StartAdvertising(ClientProxy* client,
- const std::string& service_id,
- const ConnectionOptions& options,
- const ConnectionRequestInfo& info) {
- Future<Status> response;
- NEARBY_LOGS(INFO) << "StartAdvertising with supported mediums: "
- << GetStringValueOfSupportedMediums(options);
- ConnectionOptions advertising_options = options.CompatibleOptions();
- RunOnPcpHandlerThread(
- "start-advertising",
- [this, client, &service_id, &info, &advertising_options, &response]()
- RUN_ON_PCP_HANDLER_THREAD() {
- // The endpoint id inside of the advertisement is different to high
- // visibility and low visibility mode. In order to decide if client
- // should grab the high visibility or low visibility id, it needs to
- // tell client which one right now, before
- // client#StartedAdvertising.
- if (ShouldEnterHighVisibilityMode(advertising_options)) {
- client->EnterHighVisibilityMode();
- }
-
- auto result = StartAdvertisingImpl(
- client, service_id, client->GetLocalEndpointId(),
- info.endpoint_info, advertising_options);
- if (!result.status.Ok()) {
- client->ExitHighVisibilityMode();
- response.Set(result.status);
- return;
- }
-
- // Now that we've succeeded, mark the client as advertising.
- // Save the advertising options for local reference in later process
- // like upgrading bandwidth.
- advertising_listener_ = info.listener;
- client->StartedAdvertising(service_id, GetStrategy(), info.listener,
- absl::MakeSpan(result.mediums),
- advertising_options);
- response.Set({Status::kSuccess});
- });
- return WaitForResult(absl::StrCat("StartAdvertising(", service_id, ")"),
- client->GetClientId(), &response);
-}
-
-void BasePcpHandler::StopAdvertising(ClientProxy* client) {
- NEARBY_LOGS(INFO) << "StopAdvertising local_endpoint_id="
- << client->GetLocalEndpointId();
- CountDownLatch latch(1);
- RunOnPcpHandlerThread("stop-advertising",
- [this, client, &latch]() RUN_ON_PCP_HANDLER_THREAD() {
- StopAdvertisingImpl(client);
- client->StoppedAdvertising();
- latch.CountDown();
- });
- WaitForLatch("StopAdvertising", &latch);
-}
-
-std::string BasePcpHandler::GetStringValueOfSupportedMediums(
- const ConnectionOptions& options) const {
- std::ostringstream result;
- result << "{ ";
- if (options.allowed.bluetooth) {
- result << proto::connections::Medium_Name(Medium::BLUETOOTH) << " ";
- }
- if (options.allowed.ble) {
- result << proto::connections::Medium_Name(Medium::BLE) << " ";
- }
- if (options.allowed.web_rtc) {
- result << proto::connections::Medium_Name(Medium::WEB_RTC) << " ";
- }
- if (options.allowed.wifi_lan) {
- result << proto::connections::Medium_Name(Medium::WIFI_LAN) << " ";
- }
- result << "}";
- return result.str();
-}
-
-bool BasePcpHandler::ShouldEnterHighVisibilityMode(
- const ConnectionOptions& options) {
- return !options.low_power && options.allowed.bluetooth;
-}
-
-BooleanMediumSelector BasePcpHandler::ComputeIntersectionOfSupportedMediums(
- const PendingConnectionInfo& connection_info) {
- absl::flat_hash_set<Medium> intersection;
- auto their_mediums = connection_info.supported_mediums;
-
- // If no supported mediums were set, use the default upgrade medium.
- if (their_mediums.empty()) {
- their_mediums.push_back(GetDefaultUpgradeMedium());
- }
-
- for (Medium my_medium : GetConnectionMediumsByPriority()) {
- if (std::find(their_mediums.begin(), their_mediums.end(), my_medium) !=
- their_mediums.end()) {
- // We use advertising options as a proxy to whether or not the local
- // client does want to enable a WebRTC upgrade.
- if (my_medium == location::nearby::proto::connections::Medium::WEB_RTC) {
- ConnectionOptions advertising_options =
- connection_info.client->GetAdvertisingOptions();
-
- if (!advertising_options.enable_webrtc_listening &&
- !advertising_options.allowed.web_rtc) {
- // The local client does not allow WebRTC for listening or upgrades,
- // ignore.
- continue;
- }
- }
-
- intersection.emplace(my_medium);
- }
- }
-
- // Not using designated initializers here since the VS C++ compiler errors
- // out indicating that MediumSelector<bool> is not an aggregate
- MediumSelector<bool> mediumSelector{};
- mediumSelector.bluetooth = intersection.contains(Medium::BLUETOOTH);
- mediumSelector.ble = intersection.contains(Medium::BLE);
- mediumSelector.web_rtc = intersection.contains(Medium::WEB_RTC);
- mediumSelector.wifi_lan = intersection.contains(Medium::WIFI_LAN);
- return mediumSelector;
-}
-
-Status BasePcpHandler::StartDiscovery(ClientProxy* client,
- const std::string& service_id,
- const ConnectionOptions& options,
- const DiscoveryListener& listener) {
- Future<Status> response;
- ConnectionOptions discovery_options = options.CompatibleOptions();
-
- NEARBY_LOGS(INFO) << "StartDiscovery with supported mediums:"
- << GetStringValueOfSupportedMediums(options);
- RunOnPcpHandlerThread(
- "start-discovery", [this, client, service_id, discovery_options,
- &listener, &response]() RUN_ON_PCP_HANDLER_THREAD() {
- // Ask the implementation to attempt to start discovery.
- auto result = StartDiscoveryImpl(client, service_id, discovery_options);
- if (!result.status.Ok()) {
- response.Set(result.status);
- return;
- }
-
- // Now that we've succeeded, mark the client as discovering and clear
- // out any old endpoints we had discovered.
- discovered_endpoints_.clear();
- client->StartedDiscovery(service_id, GetStrategy(), listener,
- absl::MakeSpan(result.mediums),
- discovery_options);
- response.Set({Status::kSuccess});
- });
- return WaitForResult(absl::StrCat("StartDiscovery(", service_id, ")"),
- client->GetClientId(), &response);
-}
-
-void BasePcpHandler::StopDiscovery(ClientProxy* client) {
- CountDownLatch latch(1);
- RunOnPcpHandlerThread("stop-discovery",
- [this, client, &latch]() RUN_ON_PCP_HANDLER_THREAD() {
- StopDiscoveryImpl(client);
- client->StoppedDiscovery();
- latch.CountDown();
- });
-
- WaitForLatch("StopDiscovery", &latch);
-}
-
-void BasePcpHandler::InjectEndpoint(
- ClientProxy* client, const std::string& service_id,
- const OutOfBandConnectionMetadata& metadata) {
- CountDownLatch latch(1);
- RunOnPcpHandlerThread("inject-endpoint",
- [this, client, service_id, metadata, &latch]()
- RUN_ON_PCP_HANDLER_THREAD() {
- InjectEndpointImpl(client, service_id, metadata);
- latch.CountDown();
- });
-
- WaitForLatch(absl::StrCat("InjectEndpoint(", service_id, ")"), &latch);
-}
-
-void BasePcpHandler::WaitForLatch(const std::string& method_name,
- CountDownLatch* latch) {
- Exception await_exception = latch->Await();
- if (!await_exception.Ok()) {
- if (await_exception.Raised(Exception::kTimeout)) {
- NEARBY_LOGS(INFO) << "Blocked in " << method_name;
- }
- }
-}
-
-Status BasePcpHandler::WaitForResult(const std::string& method_name,
- std::int64_t client_id,
- Future<Status>* future) {
- if (!future) {
- NEARBY_LOGS(INFO) << "No future to wait for; return with error";
- return {Status::kError};
- }
- NEARBY_LOGS(INFO) << "Waiting for future to complete: " << method_name;
- ExceptionOr<Status> result = future->Get();
- if (!result.ok()) {
- NEARBY_LOGS(INFO) << "Future:[" << method_name
- << "] completed with exception:" << result.exception();
- return {Status::kError};
- }
- NEARBY_LOGS(INFO) << "Future:[" << method_name
- << "] completed with status:" << result.result().value;
- return result.result();
-}
-
-void BasePcpHandler::RunOnPcpHandlerThread(const std::string& name,
- Runnable runnable) {
- serial_executor_.Execute(name, std::move(runnable));
-}
-
-EncryptionRunner::ResultListener BasePcpHandler::GetResultListener() {
- return {
- .on_success_cb =
- [this](const std::string& endpoint_id,
- std::unique_ptr<UKey2Handshake> ukey2,
- const std::string& auth_token,
- const ByteArray& raw_auth_token) {
- RunOnPcpHandlerThread(
- "encryption-success",
- [this, endpoint_id, raw_ukey2 = ukey2.release(), auth_token,
- raw_auth_token]() RUN_ON_PCP_HANDLER_THREAD() mutable {
- OnEncryptionSuccessRunnable(
- endpoint_id, std::unique_ptr<UKey2Handshake>(raw_ukey2),
- auth_token, raw_auth_token);
- });
- },
- .on_failure_cb =
- [this](const std::string& endpoint_id, EndpointChannel* channel) {
- RunOnPcpHandlerThread(
- "encryption-failure",
- [this, endpoint_id, channel]() RUN_ON_PCP_HANDLER_THREAD() {
- NEARBY_LOGS(ERROR)
- << "Encryption failed for endpoint_id=" << endpoint_id
- << " on medium="
- << proto::connections::Medium_Name(channel->GetMedium());
- OnEncryptionFailureRunnable(endpoint_id, channel);
- });
- },
- };
-}
-
-void BasePcpHandler::OnEncryptionSuccessRunnable(
- const std::string& endpoint_id, std::unique_ptr<UKey2Handshake> ukey2,
- const std::string& auth_token, const ByteArray& raw_auth_token) {
- // Quick fail if we've been removed from pending connections while we were
- // busy running UKEY2.
- auto it = pending_connections_.find(endpoint_id);
- if (it == pending_connections_.end()) {
- NEARBY_LOGS(INFO)
- << "Connection not found on UKEY negotination complete; endpoint_id="
- << endpoint_id;
- return;
- }
-
- BasePcpHandler::PendingConnectionInfo& connection_info = it->second;
- Medium medium = connection_info.channel->GetMedium();
-
- if (!ukey2) {
- // Fail early, if there is no crypto context.
- ProcessPreConnectionInitiationFailure(
- connection_info.client, medium, endpoint_id,
- connection_info.channel.get(), connection_info.is_incoming,
- connection_info.start_time, {Status::kEndpointIoError},
- connection_info.result.lock().get());
- return;
- }
-
- connection_info.SetCryptoContext(std::move(ukey2));
- connection_info.connection_token = GetHashedConnectionToken(raw_auth_token);
- NEARBY_LOGS(INFO)
- << "Register encrypted connection; wait for response; endpoint_id="
- << endpoint_id;
-
- // Set ourselves up so that we receive all acceptance/rejection messages
- endpoint_manager_->RegisterFrameProcessor(V1Frame::CONNECTION_RESPONSE, this);
-
- // Now we register our endpoint so that we can listen for both sides to
- // accept.
- endpoint_manager_->RegisterEndpoint(
- connection_info.client, endpoint_id,
- {
- .remote_endpoint_info = connection_info.remote_endpoint_info,
- .authentication_token = auth_token,
- .raw_authentication_token = raw_auth_token,
- .is_incoming_connection = connection_info.is_incoming,
- },
- {
- .strategy = connection_info.options.strategy,
- .allowed = ComputeIntersectionOfSupportedMediums(connection_info),
- .auto_upgrade_bandwidth =
- connection_info.options.auto_upgrade_bandwidth,
- .enforce_topology_constraints =
- connection_info.options.enforce_topology_constraints,
- .low_power = connection_info.options.low_power,
- .enable_bluetooth_listening =
- connection_info.options.enable_bluetooth_listening,
- .enable_webrtc_listening =
- connection_info.options.enable_webrtc_listening,
- .is_out_of_band_connection =
- connection_info.options.is_out_of_band_connection,
- .remote_bluetooth_mac_address =
- connection_info.options.remote_bluetooth_mac_address,
- .fast_advertisement_service_uuid =
- connection_info.options.fast_advertisement_service_uuid,
- .keep_alive_interval_millis =
- connection_info.options.keep_alive_interval_millis,
- .keep_alive_timeout_millis =
- connection_info.options.keep_alive_timeout_millis,
- },
- std::move(connection_info.channel), connection_info.listener,
- connection_info.connection_token);
-
- if (connection_info.is_incoming) {
- connection_info.client->GetAnalyticsRecorder().OnIncomingConnectionAttempt(
- proto::connections::INITIAL, medium, proto::connections::RESULT_SUCCESS,
- SystemClock::ElapsedRealtime() - connection_info.start_time,
- connection_info.connection_token);
- } else {
- connection_info.client->GetAnalyticsRecorder().OnOutgoingConnectionAttempt(
- endpoint_id, proto::connections::INITIAL, medium,
- proto::connections::RESULT_SUCCESS,
- SystemClock::ElapsedRealtime() - connection_info.start_time,
- connection_info.connection_token);
- }
-
- if (auto future_status = connection_info.result.lock()) {
- NEARBY_LOGS(INFO) << "Connection established; Finalising future OK.";
- future_status->Set({Status::kSuccess});
- connection_info.result.reset();
- }
-}
-
-void BasePcpHandler::OnEncryptionFailureRunnable(
- const std::string& endpoint_id, EndpointChannel* endpoint_channel) {
- auto it = pending_connections_.find(endpoint_id);
- if (it == pending_connections_.end()) {
- NEARBY_LOGS(INFO)
- << "Connection not found on UKEY negotination complete; endpoint_id="
- << endpoint_id;
- return;
- }
-
- BasePcpHandler::PendingConnectionInfo& info = it->second;
- // We had a bug here, caused by a race with EncryptionRunner. We now verify
- // the EndpointChannel to avoid it. In a simultaneous connection, we clean
- // up one of the two EndpointChannels and then update our pendingConnections
- // with the winning channel's state. Closing a channel that was in the
- // middle of EncryptionRunner would trigger onEncryptionFailed, and, since
- // the map had already updated with the winning EndpointChannel, we closed
- // it too by accident.
- if (*endpoint_channel != *info.channel) {
- NEARBY_LOGS(INFO) << "Not destroying channel [mismatch]: passed="
- << endpoint_channel->GetName()
- << "; expected=" << info.channel->GetName();
- return;
- }
-
- ProcessPreConnectionInitiationFailure(
- info.client, info.channel->GetMedium(), endpoint_id, info.channel.get(),
- info.is_incoming, info.start_time, {Status::kEndpointIoError},
- info.result.lock().get());
-}
-
-Status BasePcpHandler::RequestConnection(ClientProxy* client,
- const std::string& endpoint_id,
- const ConnectionRequestInfo& info,
- const ConnectionOptions& options) {
- auto result = std::make_shared<Future<Status>>();
- RunOnPcpHandlerThread(
- "request-connection", [this, client, &info, options, endpoint_id,
- result]() RUN_ON_PCP_HANDLER_THREAD() {
- absl::Time start_time = SystemClock::ElapsedRealtime();
-
- // If we already have a pending connection, then we shouldn't allow any
- // more outgoing connections to this endpoint.
- if (pending_connections_.count(endpoint_id)) {
- NEARBY_LOGS(INFO)
- << "In requestConnection(), connection requested with "
- "endpoint(id="
- << endpoint_id
- << "), but we already have a pending connection with them.";
- result->Set({Status::kAlreadyConnectedToEndpoint});
- return;
- }
-
- // If our child class says we can't send any more outgoing connections,
- // listen to them.
- if (ShouldEnforceTopologyConstraints(client->GetAdvertisingOptions()) &&
- !CanSendOutgoingConnection(client)) {
- NEARBY_LOGS(INFO)
- << "In requestConnection(), client=" << client->GetClientId()
- << " attempted a connection with endpoint(id=" << endpoint_id
- << "), but outgoing connections are disallowed";
- result->Set({Status::kOutOfOrderApiCall});
- return;
- }
-
- DiscoveredEndpoint* endpoint = GetDiscoveredEndpoint(endpoint_id);
- if (endpoint == nullptr) {
- NEARBY_LOGS(INFO)
- << "Discovered endpoint not found: endpoint_id=" << endpoint_id;
- result->Set({Status::kEndpointUnknown});
- return;
- }
-
- auto remote_bluetooth_mac_address =
- BluetoothUtils::ToString(options.remote_bluetooth_mac_address);
- if (!remote_bluetooth_mac_address.empty()) {
- if (AppendRemoteBluetoothMacAddressEndpoint(
- endpoint_id, remote_bluetooth_mac_address,
- client->GetDiscoveryOptions()))
- NEARBY_LOGS(INFO)
- << "Appended remote Bluetooth MAC Address endpoint ["
- << remote_bluetooth_mac_address << "]";
- }
-
- if (AppendWebRTCEndpoint(endpoint_id, client->GetDiscoveryOptions()))
- NEARBY_LOGS(INFO) << "Appended Web RTC endpoint.";
-
- auto discovered_endpoints = GetDiscoveredEndpoints(endpoint_id);
- std::unique_ptr<EndpointChannel> channel;
- ConnectImplResult connect_impl_result;
-
- for (auto connect_endpoint : discovered_endpoints) {
- absl::Time connect_start_time = SystemClock::ElapsedRealtime();
- if (!MediumSupportedByClientOptions(connect_endpoint->medium,
- options))
- continue;
- connect_impl_result = ConnectImpl(client, connect_endpoint);
- if (connect_impl_result.status.Ok()) {
- channel = std::move(connect_impl_result.endpoint_channel);
- break;
- } else {
- LogConnectionAttempt(client, connect_endpoint->medium,
- connect_endpoint->endpoint_id,
- /* is_incoming = */ false, connect_start_time);
- }
- }
-
- Medium channel_medium =
- channel ? channel->GetMedium() : Medium::UNKNOWN_MEDIUM;
- if (channel == nullptr) {
- NEARBY_LOGS(INFO)
- << "Endpoint channel not available: endpoint_id=" << endpoint_id;
- ProcessPreConnectionInitiationFailure(
- client, channel_medium, endpoint_id, channel.get(),
- /* is_incoming = */ false, start_time, connect_impl_result.status,
- result.get());
- return;
- }
-
- NEARBY_LOGS(INFO)
- << "In requestConnection(), wrote ConnectionRequestFrame "
- "to endpoint_id="
- << endpoint_id;
- // Generate the nonce to use for this connection.
- std::int32_t nonce = prng_.NextInt32();
-
- // The first message we have to send, after connecting, is to tell the
- // endpoint about ourselves.
- Exception write_exception = WriteConnectionRequestFrame(
- channel.get(), client->GetLocalEndpointId(), info.endpoint_info,
- nonce, GetSupportedConnectionMediumsByPriority(options),
- options.keep_alive_interval_millis,
- options.keep_alive_timeout_millis);
- if (!write_exception.Ok()) {
- NEARBY_LOGS(INFO) << "Failed to send connection request: endpoint_id="
- << endpoint_id;
- ProcessPreConnectionInitiationFailure(
- client, channel_medium, endpoint_id, channel.get(),
- /* is_incoming = */ false, start_time, {Status::kEndpointIoError},
- result.get());
- return;
- }
-
- NEARBY_LOGS(INFO) << "Adding connection to pending set: endpoint_id="
- << endpoint_id;
-
- // We've successfully connected to the device, and are now about to jump
- // on to the EncryptionRunner thread to start running our encryption
- // protocol. We'll mark ourselves as pending in case we get another call
- // to RequestConnection or OnIncomingConnection, so that we can cancel
- // the connection if needed.
- // Not using designated initializers here since the VS C++ compiler
- // errors out indicating that MediumSelector<bool> is not an aggregate
- PendingConnectionInfo pendingConnectionInfo{};
- pendingConnectionInfo.client = client;
- pendingConnectionInfo.remote_endpoint_info = endpoint->endpoint_info;
- pendingConnectionInfo.nonce = nonce;
- pendingConnectionInfo.is_incoming = false;
- pendingConnectionInfo.start_time = start_time;
- pendingConnectionInfo.listener = info.listener;
- pendingConnectionInfo.options = options;
- pendingConnectionInfo.result = result;
- pendingConnectionInfo.channel = std::move(channel);
-
- EndpointChannel* endpoint_channel =
- pending_connections_
- .emplace(endpoint_id, std::move(pendingConnectionInfo))
- .first->second.channel.get();
-
- NEARBY_LOGS(INFO) << "Initiating secure connection: endpoint_id="
- << endpoint_id;
- // Next, we'll set up encryption. When it's done, our future will return
- // and RequestConnection() will finish.
- encryption_runner_.StartClient(client, endpoint_id, endpoint_channel,
- GetResultListener());
- });
- NEARBY_LOGS(INFO) << "Waiting for connection to complete: endpoint_id="
- << endpoint_id;
- auto status =
- WaitForResult(absl::StrCat("RequestConnection(", endpoint_id, ")"),
- client->GetClientId(), result.get());
- NEARBY_LOGS(INFO) << "Wait is complete: endpoint_id=" << endpoint_id
- << "; status=" << status.value;
- return status;
-}
-
-bool BasePcpHandler::MediumSupportedByClientOptions(
- const proto::connections::Medium& medium,
- const ConnectionOptions& client_options) const {
- for (auto supported_medium : client_options.GetMediums()) {
- if (medium == supported_medium) {
- return true;
- }
- }
- return false;
-}
-
-// Get ordered supported connection medium based on local advertising/discovery
-// option.
-std::vector<proto::connections::Medium>
-BasePcpHandler::GetSupportedConnectionMediumsByPriority(
- const ConnectionOptions& local_option) {
- std::vector<proto::connections::Medium> supported_mediums_by_priority;
- for (auto medium_by_priority : GetConnectionMediumsByPriority()) {
- if (MediumSupportedByClientOptions(medium_by_priority, local_option)) {
- supported_mediums_by_priority.push_back(medium_by_priority);
- }
- }
- return supported_mediums_by_priority;
-}
-
-// Get any single discovered endpoint for a given endpoint_id.
-BasePcpHandler::DiscoveredEndpoint* BasePcpHandler::GetDiscoveredEndpoint(
- const std::string& endpoint_id) {
- auto it = discovered_endpoints_.find(endpoint_id);
- if (it == discovered_endpoints_.end()) {
- return nullptr;
- }
- return it->second.get();
-}
-
-std::vector<BasePcpHandler::DiscoveredEndpoint*>
-BasePcpHandler::GetDiscoveredEndpoints(const std::string& endpoint_id) {
- std::vector<BasePcpHandler::DiscoveredEndpoint*> result;
- auto it = discovered_endpoints_.equal_range(endpoint_id);
- for (auto item = it.first; item != it.second; item++) {
- result.push_back(item->second.get());
- }
- std::sort(result.begin(), result.end(),
- [this](DiscoveredEndpoint* a, DiscoveredEndpoint* b) -> bool {
- return IsPreferred(*a, *b);
- });
-
- return result;
-}
-
-std::vector<BasePcpHandler::DiscoveredEndpoint*>
-BasePcpHandler::GetDiscoveredEndpoints(
- const proto::connections::Medium medium) {
- std::vector<BasePcpHandler::DiscoveredEndpoint*> result;
- for (const auto& item : discovered_endpoints_) {
- if (item.second->medium == medium) {
- result.push_back(item.second.get());
- }
- }
- return result;
-}
-
-mediums::WebrtcPeerId BasePcpHandler::CreatePeerIdFromAdvertisement(
- const std::string& service_id, const std::string& endpoint_id,
- const ByteArray& endpoint_info) {
- std::string seed =
- absl::StrCat(service_id, endpoint_id, std::string(endpoint_info));
- return mediums::WebrtcPeerId::FromSeed(ByteArray(std::move(seed)));
-}
-
-bool BasePcpHandler::HasOutgoingConnections(ClientProxy* client) const {
- for (const auto& item : pending_connections_) {
- auto& connection = item.second;
- if (!connection.is_incoming) {
- return true;
- }
- }
- return client->GetNumOutgoingConnections() > 0;
-}
-
-bool BasePcpHandler::HasIncomingConnections(ClientProxy* client) const {
- for (const auto& item : pending_connections_) {
- auto& connection = item.second;
- if (connection.is_incoming) {
- return true;
- }
- }
- return client->GetNumIncomingConnections() > 0;
-}
-
-bool BasePcpHandler::CanSendOutgoingConnection(ClientProxy* client) const {
- return true;
-}
-
-bool BasePcpHandler::CanReceiveIncomingConnection(ClientProxy* client) const {
- return true;
-}
-
-Exception BasePcpHandler::WriteConnectionRequestFrame(
- EndpointChannel* endpoint_channel, const std::string& local_endpoint_id,
- const ByteArray& local_endpoint_info, std::int32_t nonce,
- const std::vector<proto::connections::Medium>& supported_mediums,
- std::int32_t keep_alive_interval_millis,
- std::int32_t keep_alive_timeout_millis) {
- return endpoint_channel->Write(parser::ForConnectionRequest(
- local_endpoint_id, local_endpoint_info, nonce, /*supports_5_ghz =*/false,
- /*bssid=*/std::string{}, supported_mediums, keep_alive_interval_millis,
- keep_alive_timeout_millis));
-}
-
-void BasePcpHandler::ProcessPreConnectionInitiationFailure(
- ClientProxy* client, Medium medium, const std::string& endpoint_id,
- EndpointChannel* channel, bool is_incoming, absl::Time start_time,
- Status status, Future<Status>* result) {
- if (channel != nullptr) {
- channel->Close();
- }
-
- if (result != nullptr) {
- NEARBY_LOGS(INFO) << "Connection failed; aborting future";
- result->Set(status);
- }
-
- LogConnectionAttempt(client, medium, endpoint_id, is_incoming, start_time);
- // result is hold inside a swapper, and saved in PendingConnectionInfo.
- // PendingConnectionInfo destructor will clear the memory of SettableFuture
- // shared_ptr for result.
- pending_connections_.erase(endpoint_id);
-}
-
-void BasePcpHandler::ProcessPreConnectionResultFailure(
- ClientProxy* client, const std::string& endpoint_id) {
- auto item = pending_connections_.extract(endpoint_id);
- endpoint_manager_->DiscardEndpoint(client, endpoint_id);
- client->OnConnectionRejected(endpoint_id, {Status::kError});
-}
-
-bool BasePcpHandler::ShouldEnforceTopologyConstraints(
- const ConnectionOptions& local_advertising_options) const {
- // Topology constraints only matter for the advertiser.
- // For discoverers, we'll always enforce them.
- if (local_advertising_options.strategy.IsNone()) {
- return true;
- }
-
- return local_advertising_options.enforce_topology_constraints;
-}
-
-bool BasePcpHandler::AutoUpgradeBandwidth(
- const ConnectionOptions& local_advertising_options) const {
- if (local_advertising_options.strategy.IsNone()) {
- return true;
- }
-
- return local_advertising_options.auto_upgrade_bandwidth;
-}
-
-Status BasePcpHandler::AcceptConnection(
- ClientProxy* client, const std::string& endpoint_id,
- const PayloadListener& payload_listener) {
- Future<Status> response;
- RunOnPcpHandlerThread(
- "accept-connection", [this, client, endpoint_id, payload_listener,
- &response]() RUN_ON_PCP_HANDLER_THREAD() {
- NEARBY_LOGS(INFO) << "AcceptConnection: endpoint_id=" << endpoint_id;
- if (!pending_connections_.count(endpoint_id)) {
- NEARBY_LOGS(INFO)
- << "AcceptConnection: no pending connection for endpoint_id="
- << endpoint_id;
-
- response.Set({Status::kEndpointUnknown});
- return;
- }
- auto& connection_info = pending_connections_[endpoint_id];
-
- // By this point in the flow, connection_info.channel has been
- // nulled out because ownership of that EndpointChannel was passed on to
- // EndpointChannelManager via a call to
- // EndpointManager::registerEndpoint(), so we now need to get access to
- // the EndpointChannel from the authoritative owner.
- std::shared_ptr<EndpointChannel> channel =
- channel_manager_->GetChannelForEndpoint(endpoint_id);
- if (channel == nullptr) {
- NEARBY_LOGS(ERROR) << "Channel destroyed before Accept; bring down "
- "connection: endpoint_id="
- << endpoint_id;
- ProcessPreConnectionResultFailure(client, endpoint_id);
- response.Set({Status::kEndpointUnknown});
- return;
- }
-
- Exception write_exception =
- channel->Write(parser::ForConnectionResponse(Status::kSuccess));
- if (!write_exception.Ok()) {
- NEARBY_LOGS(INFO)
- << "AcceptConnection: failed to send response: endpoint_id="
- << endpoint_id;
- ProcessPreConnectionResultFailure(client, endpoint_id);
- response.Set({Status::kEndpointIoError});
- return;
- }
-
- NEARBY_LOGS(INFO) << "AcceptConnection: accepting locally: endpoint_id="
- << endpoint_id;
- connection_info.LocalEndpointAcceptedConnection(endpoint_id,
- payload_listener);
- EvaluateConnectionResult(client, endpoint_id,
- false /* can_close_immediately */);
- response.Set({Status::kSuccess});
- });
-
- return WaitForResult(absl::StrCat("AcceptConnection(", endpoint_id, ")"),
- client->GetClientId(), &response);
-}
-
-Status BasePcpHandler::RejectConnection(ClientProxy* client,
- const std::string& endpoint_id) {
- Future<Status> response;
- RunOnPcpHandlerThread(
- "reject-connection",
- [this, client, endpoint_id, &response]() RUN_ON_PCP_HANDLER_THREAD() {
- NEARBY_LOG(INFO, "RejectConnection: id=%s", endpoint_id.c_str());
- if (!pending_connections_.count(endpoint_id)) {
- NEARBY_LOGS(INFO)
- << "RejectConnection: no pending connection for endpoint_id="
- << endpoint_id;
- response.Set({Status::kEndpointUnknown});
- return;
- }
- auto& connection_info = pending_connections_[endpoint_id];
-
- // By this point in the flow, connection_info->endpoint_channel_ has
- // been nulled out because ownership of that EndpointChannel was passed
- // on to EndpointChannelManager via a call to
- // EndpointManager::registerEndpoint(), so we now need to get access to
- // the EndpointChannel from the authoritative owner.
- std::shared_ptr<EndpointChannel> channel =
- channel_manager_->GetChannelForEndpoint(endpoint_id);
- if (channel == nullptr) {
- NEARBY_LOGS(ERROR)
- << "Channel destroyed before Reject; bring down connection: "
- "endpoint_id="
- << endpoint_id;
- ProcessPreConnectionResultFailure(client, endpoint_id);
- response.Set({Status::kEndpointUnknown});
- return;
- }
-
- Exception write_exception = channel->Write(
- parser::ForConnectionResponse(Status::kConnectionRejected));
- if (!write_exception.Ok()) {
- NEARBY_LOGS(INFO)
- << "RejectConnection: failed to send response: endpoint_id="
- << endpoint_id;
- ProcessPreConnectionResultFailure(client, endpoint_id);
- response.Set({Status::kEndpointIoError});
- return;
- }
-
- NEARBY_LOGS(INFO) << "RejectConnection: rejecting locally: endpoint_id="
- << endpoint_id;
- connection_info.LocalEndpointRejectedConnection(endpoint_id);
- EvaluateConnectionResult(client, endpoint_id,
- false /* can_close_immediately */);
- response.Set({Status::kSuccess});
- });
-
- return WaitForResult(absl::StrCat("RejectConnection(", endpoint_id, ")"),
- client->GetClientId(), &response);
-}
-
-void BasePcpHandler::OnIncomingFrame(OfflineFrame& frame,
- const std::string& endpoint_id,
- ClientProxy* client,
- proto::connections::Medium medium) {
- CountDownLatch latch(1);
- RunOnPcpHandlerThread(
- "incoming-frame",
- [this, client, endpoint_id, frame, &latch]() RUN_ON_PCP_HANDLER_THREAD() {
- NEARBY_LOGS(INFO) << "OnConnectionResponse: endpoint_id="
- << endpoint_id;
-
- if (client->HasRemoteEndpointResponded(endpoint_id)) {
- NEARBY_LOGS(INFO)
- << "OnConnectionResponse: already handled; endpoint_id="
- << endpoint_id;
- return;
- }
-
- const ConnectionResponseFrame& connection_response =
- frame.v1().connection_response();
-
- // For backward compatible, here still check both status and
- // response parameters until the response feature is roll out in all
- // supported devices.
- bool accepted = false;
- if (connection_response.has_response()) {
- accepted =
- connection_response.response() == ConnectionResponseFrame::ACCEPT;
- } else {
- accepted = connection_response.status() == Status::kSuccess;
- }
- if (accepted) {
- NEARBY_LOGS(INFO)
- << "OnConnectionResponse: remote accepted; endpoint_id="
- << endpoint_id;
- client->RemoteEndpointAcceptedConnection(endpoint_id);
- } else {
- NEARBY_LOGS(INFO)
- << "OnConnectionResponse: remote rejected; endpoint_id="
- << endpoint_id << "; status=" << connection_response.status();
- client->RemoteEndpointRejectedConnection(endpoint_id);
- }
-
- EvaluateConnectionResult(client, endpoint_id,
- /* can_close_immediately= */ true);
-
- latch.CountDown();
- });
- WaitForLatch("OnIncomingFrame()", &latch);
-}
-
-void BasePcpHandler::OnEndpointDisconnect(ClientProxy* client,
- const std::string& endpoint_id,
- CountDownLatch barrier) {
- if (stop_.Get()) {
- barrier.CountDown();
- return;
- }
- RunOnPcpHandlerThread("on-endpoint-disconnect",
- [this, client, endpoint_id, barrier]()
- RUN_ON_PCP_HANDLER_THREAD() mutable {
- auto item = pending_alarms_.find(endpoint_id);
- if (item != pending_alarms_.end()) {
- auto& alarm = item->second;
- alarm.Cancel();
- pending_alarms_.erase(item);
- }
- ProcessPreConnectionResultFailure(client,
- endpoint_id);
- barrier.CountDown();
- });
-}
-
-BluetoothDevice BasePcpHandler::GetRemoteBluetoothDevice(
- const std::string& remote_bluetooth_mac_address) {
- return mediums_->GetBluetoothClassic().GetRemoteDevice(
- remote_bluetooth_mac_address);
-}
-
-void BasePcpHandler::OnEndpointFound(
- ClientProxy* client, std::shared_ptr<DiscoveredEndpoint> endpoint) {
- // Check if we've seen this endpoint ID before.
- std::string& endpoint_id = endpoint->endpoint_id;
- NEARBY_LOGS(INFO) << "OnEndpointFound: id=" << endpoint_id << " [enter]";
-
- auto range = discovered_endpoints_.equal_range(endpoint->endpoint_id);
-
- DiscoveredEndpoint* owned_endpoint = nullptr;
- for (auto& item = range.first; item != range.second; ++item) {
- auto& discovered_endpoint = item->second;
- if (discovered_endpoint->medium != endpoint->medium) continue;
- // Check if there was a info change. If there was, report the previous
- // endpoint as lost.
- if (discovered_endpoint->endpoint_info != endpoint->endpoint_info) {
- OnEndpointLost(client, *discovered_endpoint);
- discovered_endpoint = endpoint; // Replace endpoint.
- OnEndpointFound(client, std::move(endpoint));
- return;
- } else {
- owned_endpoint = endpoint.get();
- break;
- }
- }
-
- if (!owned_endpoint) {
- owned_endpoint =
- discovered_endpoints_.emplace(endpoint_id, std::move(endpoint))
- ->second.get();
- }
-
- // Range is empty: this is the first endpoint we discovered so far.
- // Report this endpoint_id to client.
- if (range.first == range.second) {
- NEARBY_LOGS(INFO) << "Adding new endpoint: endpoint_id=" << endpoint_id;
- // And, as it's the first time, report it to the client.
- client->OnEndpointFound(
- owned_endpoint->service_id, owned_endpoint->endpoint_id,
- owned_endpoint->endpoint_info, owned_endpoint->medium);
- } else {
- NEARBY_LOGS(INFO) << "Adding new medium for endpoint: endpoint_id="
- << endpoint_id << "; medium=" << owned_endpoint->medium;
- }
-}
-
-void BasePcpHandler::OnEndpointLost(
- ClientProxy* client, const BasePcpHandler::DiscoveredEndpoint& endpoint) {
- // Look up the DiscoveredEndpoint we have in our cache.
- const auto* discovered_endpoint = GetDiscoveredEndpoint(endpoint.endpoint_id);
- if (discovered_endpoint == nullptr) {
- NEARBY_LOGS(INFO) << "No previous endpoint (nothing to lose): endpoint_id="
- << endpoint.endpoint_id;
- return;
- }
-
- // Validate that the cached endpoint has the same info as the one reported as
- // onLost. If the info differs, then no-op. This likely means that the remote
- // device changed their info. We reported onFound for the new info and are
- // just now figuring out that we lost the old info.
- if (discovered_endpoint->endpoint_info != endpoint.endpoint_info) {
- NEARBY_LOGS(INFO) << "Previous endpoint name mismatch; passed="
- << absl::BytesToHexString(endpoint.endpoint_info.data())
- << "; expected="
- << absl::BytesToHexString(
- discovered_endpoint->endpoint_info.data());
- return;
- }
-
- auto item = discovered_endpoints_.extract(endpoint.endpoint_id);
- if (!discovered_endpoints_.count(endpoint.endpoint_id)) {
- client->OnEndpointLost(endpoint.service_id, endpoint.endpoint_id);
- }
-}
-
-bool BasePcpHandler::IsPreferred(
- const BasePcpHandler::DiscoveredEndpoint& new_endpoint,
- const BasePcpHandler::DiscoveredEndpoint& old_endpoint) {
- std::vector<proto::connections::Medium> mediums =
- GetConnectionMediumsByPriority();
- // As we iterate through the list of mediums, we see if we run into the new
- // endpoint's medium or the old endpoint's medium first.
- for (const auto& medium : mediums) {
- if (medium == new_endpoint.medium) {
- // The new endpoint's medium came first. It's preferred!
- return true;
- }
-
- if (medium == old_endpoint.medium) {
- // The old endpoint's medium came first. Stick with the old endpoint!
- return false;
- }
- }
- std::string medium_string;
- for (const auto& medium : mediums) {
- absl::StrAppend(&medium_string, medium, "; ");
- }
- NEARBY_LOGS(ERROR) << "Failed to find either " << new_endpoint.medium
- << " or " << old_endpoint.medium
- << " in the list of locally supported mediums despite "
- "expecting to find both, when deciding which medium "
- << medium_string << " is preferred.";
- return false;
-}
-
-Exception BasePcpHandler::OnIncomingConnection(
- ClientProxy* client, const ByteArray& remote_endpoint_info,
- std::unique_ptr<EndpointChannel> channel,
- proto::connections::Medium medium) {
- absl::Time start_time = SystemClock::ElapsedRealtime();
-
- // Fixes an NPE in ClientProxy.OnConnectionAccepted. The crash happened when
- // the client stopped advertising and we nulled out state, followed by an
- // incoming connection where we attempted to check that state.
- if (!client->IsAdvertising()) {
- NEARBY_LOGS(WARNING) << "Ignoring incoming connection on medium "
- << proto::connections::Medium_Name(
- channel->GetMedium())
- << " because client=" << client->GetClientId()
- << " is no longer advertising.";
- return {Exception::kIo};
- }
-
- // Endpoints connecting to us will always tell us about themselves first.
- ExceptionOr<OfflineFrame> wrapped_frame =
- ReadConnectionRequestFrame(channel.get());
-
- if (!wrapped_frame.ok()) {
- if (wrapped_frame.exception()) {
- NEARBY_LOGS(ERROR)
- << "Failed to parse incoming connection request; client="
- << client->GetClientId()
- << "; device=" << absl::BytesToHexString(remote_endpoint_info.data());
- ProcessPreConnectionInitiationFailure(client, medium, "", channel.get(),
- /* is_incoming= */ false,
- start_time, {Status::kError},
- nullptr);
- return {Exception::kSuccess};
- }
- return wrapped_frame.GetException();
- }
-
- OfflineFrame& frame = wrapped_frame.result();
- const ConnectionRequestFrame& connection_request =
- frame.v1().connection_request();
- NEARBY_LOGS(INFO) << "In onIncomingConnection("
- << proto::connections::Medium_Name(channel->GetMedium())
- << ") for client=" << client->GetClientId()
- << ", read ConnectionRequestFrame from endpoint(id="
- << connection_request.endpoint_id() << ")";
- if (client->IsConnectedToEndpoint(connection_request.endpoint_id())) {
- NEARBY_LOGS(ERROR) << "Incoming connection on medium "
- << proto::connections::Medium_Name(channel->GetMedium())
- << " was denied because we're "
- "already connected to endpoint(id="
- << connection_request.endpoint_id() << ").";
- return {Exception::kIo};
- }
-
- // If we've already sent out a connection request to this endpoint, then this
- // is where we need to decide which connection to break.
- if (BreakTie(client, connection_request.endpoint_id(),
- connection_request.nonce(), channel.get())) {
- return {Exception::kSuccess};
- }
-
- // If our child class says we can't accept any more incoming connections,
- // listen to them.
- if (ShouldEnforceTopologyConstraints(client->GetAdvertisingOptions()) &&
- !CanReceiveIncomingConnection(client)) {
- NEARBY_LOGS(ERROR) << "Incoming connections are currently disallowed.";
- return {Exception::kIo};
- }
-
- // The ConnectionRequest frame has two fields that both contain the
- // EndpointInfo. The legacy field stores it as a string while the newer field
- // stores it as a byte array. We'll attempt to grab from the newer field, but
- // will accept the older string if it's all that exists.
- const ByteArray endpoint_info{connection_request.has_endpoint_info()
- ? connection_request.endpoint_info()
- : connection_request.endpoint_name()};
-
- // Retrieve the keep-alive frame interval and timeout fields. If the frame
- // doesn't have those fields, we need to get them as default from feature
- // flags to prevent 0-values causing thread ill.
- ConnectionOptions options = {.keep_alive_interval_millis = 0,
- .keep_alive_timeout_millis = 0};
- if (connection_request.has_keep_alive_interval_millis() &&
- connection_request.has_keep_alive_timeout_millis()) {
- options.keep_alive_interval_millis =
- connection_request.keep_alive_interval_millis();
- options.keep_alive_timeout_millis =
- connection_request.keep_alive_timeout_millis();
- }
- if (options.keep_alive_interval_millis == 0 ||
- options.keep_alive_timeout_millis == 0 ||
- options.keep_alive_interval_millis >= options.keep_alive_timeout_millis) {
- NEARBY_LOGS(WARNING)
- << "Incoming connection has wrong keep-alive frame interval="
- << options.keep_alive_interval_millis
- << ", timeout=" << options.keep_alive_timeout_millis
- << " values; correct them as default.",
- options.keep_alive_interval_millis =
- FeatureFlags::GetInstance().GetFlags().keep_alive_interval_millis;
- options.keep_alive_timeout_millis =
- FeatureFlags::GetInstance().GetFlags().keep_alive_timeout_millis;
- }
-
- // We've successfully connected to the device, and are now about to jump on to
- // the EncryptionRunner thread to start running our encryption protocol. We'll
- // mark ourselves as pending in case we get another call to RequestConnection
- // or OnIncomingConnection, so that we can cancel the connection if needed.
- // Not using designated initializers here since the VS C++ compiler errors
- // out indicating that MediumSelector<bool> is not an aggregate
- PendingConnectionInfo pendingConnectionInfo{};
- pendingConnectionInfo.client = client;
- pendingConnectionInfo.remote_endpoint_info = endpoint_info;
- pendingConnectionInfo.nonce = connection_request.nonce();
- pendingConnectionInfo.is_incoming = true;
- pendingConnectionInfo.start_time = start_time;
- pendingConnectionInfo.listener = advertising_listener_;
- pendingConnectionInfo.options = options;
- pendingConnectionInfo.supported_mediums =
- parser::ConnectionRequestMediumsToMediums(connection_request);
- pendingConnectionInfo.channel = std::move(channel);
-
- auto* owned_channel = pending_connections_
- .emplace(connection_request.endpoint_id(),
- std::move(pendingConnectionInfo))
- .first->second.channel.get();
-
- // Next, we'll set up encryption.
- encryption_runner_.StartServer(client, connection_request.endpoint_id(),
- owned_channel, GetResultListener());
- return {Exception::kSuccess};
-}
-
-bool BasePcpHandler::BreakTie(ClientProxy* client,
- const std::string& endpoint_id,
- std::int32_t incoming_nonce,
- EndpointChannel* endpoint_channel) {
- auto it = pending_connections_.find(endpoint_id);
- if (it != pending_connections_.end()) {
- BasePcpHandler::PendingConnectionInfo& info = it->second;
-
- NEARBY_LOGS(INFO)
- << "In onIncomingConnection("
- << proto::connections::Medium_Name(endpoint_channel->GetMedium())
- << ") for client=" << client->GetClientId()
- << ", found a collision with endpoint " << endpoint_id
- << ". We've already sent a connection request to them with nonce "
- << info.nonce
- << ", but they're also trying to connect to us with nonce "
- << incoming_nonce;
- // Break the lowest connection. In the (extremely) rare case of a tie, break
- // both.
- if (info.nonce > incoming_nonce) {
- // Our connection won! Clean up their connection.
- endpoint_channel->Close();
-
- NEARBY_LOGS(INFO) << "In onIncomingConnection("
- << proto::connections::Medium_Name(
- endpoint_channel->GetMedium())
- << ") for client=" << client->GetClientId()
- << ", cleaned up the collision with endpoint "
- << endpoint_id << " by closing their channel.";
- return true;
- } else if (info.nonce < incoming_nonce) {
- // Aw, we lost. Clean up our connection, and then we'll let their
- // connection continue on.
- ProcessTieBreakLoss(client, endpoint_id, &info);
- NEARBY_LOGS(INFO)
- << "In onIncomingConnection("
- << proto::connections::Medium_Name(endpoint_channel->GetMedium())
- << ") for client=" << client->GetClientId()
- << ", cleaned up the collision with endpoint " << endpoint_id
- << " by closing our channel and notifying our client of the failure.";
- } else {
- // Oh. Huh. We both lost. Well, that's awkward. We'll clean up both and
- // just force the devices to retry.
- endpoint_channel->Close();
-
- ProcessTieBreakLoss(client, endpoint_id, &info);
-
- NEARBY_LOGS(INFO)
- << "In onIncomingConnection("
- << proto::connections::Medium_Name(endpoint_channel->GetMedium())
- << ") for client=" << client->GetClientId()
- << ", cleaned up the collision with endpoint " << endpoint_id
- << " by closing both channels. Our nonces were identical, so we "
- "couldn't decide which channel to use.";
- return true;
- }
- }
-
- return false;
-}
-
-void BasePcpHandler::ProcessTieBreakLoss(
- ClientProxy* client, const std::string& endpoint_id,
- BasePcpHandler::PendingConnectionInfo* info) {
- ProcessPreConnectionInitiationFailure(
- client, info->channel->GetMedium(), endpoint_id, info->channel.get(),
- info->is_incoming, info->start_time, {Status::kEndpointIoError},
- info->result.lock().get());
- ProcessPreConnectionResultFailure(client, endpoint_id);
-}
-
-bool BasePcpHandler::AppendRemoteBluetoothMacAddressEndpoint(
- const std::string& endpoint_id,
- const std::string& remote_bluetooth_mac_address,
- const ConnectionOptions& local_discovery_options) {
- if (!local_discovery_options.allowed.bluetooth) {
- return false;
- }
-
- auto it = discovered_endpoints_.equal_range(endpoint_id);
- if (it.first == it.second) {
- return false;
- }
- auto endpoint = it.first->second.get();
- for (auto item = it.first; item != it.second; item++) {
- if (item->second->medium == proto::connections::Medium::BLUETOOTH) {
- NEARBY_LOGS(INFO)
- << "Cannot append remote Bluetooth MAC Address endpoint, because "
- "the endpoint has already been found over Bluetooth ["
- << remote_bluetooth_mac_address << "]";
- return false;
- }
- }
-
- auto remote_bluetooth_device =
- GetRemoteBluetoothDevice(remote_bluetooth_mac_address);
- if (!remote_bluetooth_device.IsValid()) {
- NEARBY_LOGS(INFO)
- << "Cannot append remote Bluetooth MAC Address endpoint, because a "
- "valid Bluetooth device could not be derived ["
- << remote_bluetooth_mac_address << "]";
- return false;
- }
-
- auto bluetooth_endpoint =
- std::make_shared<BluetoothEndpoint>(BluetoothEndpoint{
- {endpoint_id, endpoint->endpoint_info, endpoint->service_id,
- proto::connections::Medium::BLUETOOTH, WebRtcState::kUnconnectable},
- remote_bluetooth_device,
- });
-
- discovered_endpoints_.emplace(endpoint_id, std::move(bluetooth_endpoint));
- return true;
-}
-
-bool BasePcpHandler::AppendWebRTCEndpoint(
- const std::string& endpoint_id,
- const ConnectionOptions& local_discovery_options) {
- if (!local_discovery_options.allowed.web_rtc) {
- return false;
- }
-
- bool should_connect_web_rtc = false;
- auto it = discovered_endpoints_.equal_range(endpoint_id);
- if (it.first == it.second) return false;
- auto endpoint = it.first->second.get();
- for (auto item = it.first; item != it.second; item++) {
- if (item->second->web_rtc_state != WebRtcState::kUnconnectable) {
- should_connect_web_rtc = true;
- break;
- }
- }
- if (!should_connect_web_rtc) return false;
-
- auto webrtc_endpoint = std::make_shared<WebRtcEndpoint>(WebRtcEndpoint{
- {endpoint_id, endpoint->endpoint_info, endpoint->service_id,
- proto::connections::Medium::WEB_RTC, WebRtcState::kConnectable},
- CreatePeerIdFromAdvertisement(endpoint->service_id, endpoint->endpoint_id,
- endpoint->endpoint_info),
- });
-
- discovered_endpoints_.emplace(endpoint_id, std::move(webrtc_endpoint));
- return true;
-}
-
-void BasePcpHandler::EvaluateConnectionResult(ClientProxy* client,
- const std::string& endpoint_id,
- bool can_close_immediately) {
- // Short-circuit immediately if we're not in an actionable state yet. We will
- // be called again once the other side has made their decision.
- if (!client->IsConnectionAccepted(endpoint_id) &&
- !client->IsConnectionRejected(endpoint_id)) {
- if (!client->HasLocalEndpointResponded(endpoint_id)) {
- NEARBY_LOGS(INFO)
- << "ConnectionResult: local client did not respond; endpoint_id="
- << endpoint_id;
- } else if (!client->HasRemoteEndpointResponded(endpoint_id)) {
- NEARBY_LOGS(INFO)
- << "ConnectionResult: remote client did not respond; endpoint_id="
- << endpoint_id;
- }
- return;
- }
-
- // Clean up the endpoint channel from our list of 'pending' connections. It's
- // no longer pending.
- auto it = pending_connections_.find(endpoint_id);
- if (it == pending_connections_.end()) {
- NEARBY_LOGS(INFO) << "No pending connection to evaluate; endpoint_id="
- << endpoint_id;
- return;
- }
-
- auto pair = pending_connections_.extract(it);
- BasePcpHandler::PendingConnectionInfo& connection_info = pair.mapped();
- bool is_connection_accepted = client->IsConnectionAccepted(endpoint_id);
-
- Status response_code;
- if (is_connection_accepted) {
- NEARBY_LOGS(INFO) << "Pending connection accepted; endpoint_id="
- << endpoint_id;
- response_code = {Status::kSuccess};
-
- // Both sides have accepted, so we can now start talking over encrypted
- // channels
- // Now, after both parties accepted connection (presumably after verifying &
- // matching security tokens), we are allowed to extract the shared key.
- auto ukey2 = std::move(connection_info.ukey2);
- bool succeeded = ukey2->VerifyHandshake();
- CHECK(succeeded); // If this fails, it's a UKEY2 protocol bug.
- auto context = ukey2->ToConnectionContext();
- CHECK(context); // there is no way how this can fail, if Verify succeeded.
- // If it did, it's a UKEY2 protocol bug.
-
- channel_manager_->EncryptChannelForEndpoint(endpoint_id,
- std::move(context));
-
- client->GetAnalyticsRecorder().OnConnectionEstablished(
- endpoint_id,
- channel_manager_->GetChannelForEndpoint(endpoint_id)->GetMedium(),
- connection_info.connection_token);
- } else {
- NEARBY_LOGS(INFO) << "Pending connection rejected; endpoint_id="
- << endpoint_id;
- response_code = {Status::kConnectionRejected};
- }
-
- // Invoke the client callback to let it know of the connection result.
- if (response_code.Ok()) {
- client->OnConnectionAccepted(endpoint_id);
- } else {
- client->OnConnectionRejected(endpoint_id, response_code);
- }
-
- // If the connection failed, clean everything up and short circuit.
- if (!is_connection_accepted) {
- // Clean up the channel in EndpointManager if it's no longer required.
- if (can_close_immediately) {
- endpoint_manager_->DiscardEndpoint(client, endpoint_id);
- } else {
- pending_alarms_.emplace(
- endpoint_id,
- CancelableAlarm(
- "BasePcpHandler.evaluateConnectionResult() delayed close",
- [this, client, endpoint_id]() {
- endpoint_manager_->DiscardEndpoint(client, endpoint_id);
- },
- kRejectedConnectionCloseDelay, &alarm_executor_));
- }
-
- return;
- }
-
- // Kick off the bandwidth upgrade for incoming connections.
- if (connection_info.is_incoming &&
- AutoUpgradeBandwidth(client->GetAdvertisingOptions())) {
- bwu_manager_->InitiateBwuForEndpoint(client, endpoint_id);
- }
-}
-
-ExceptionOr<OfflineFrame> BasePcpHandler::ReadConnectionRequestFrame(
- EndpointChannel* endpoint_channel) {
- if (endpoint_channel == nullptr) {
- return ExceptionOr<OfflineFrame>(Exception::kIo);
- }
-
- // To avoid a device connecting but never sending their introductory frame, we
- // time out the connection after a certain amount of time.
- CancelableAlarm timeout_alarm(
- absl::StrCat("PcpHandler(", this->GetStrategy().GetName(),
- ")::ReadConnectionRequestFrame"),
- [endpoint_channel]() { endpoint_channel->Close(); },
- kConnectionRequestReadTimeout, &alarm_executor_);
- // Do a blocking read to try and find the ConnectionRequestFrame
- ExceptionOr<ByteArray> wrapped_bytes = endpoint_channel->Read();
- timeout_alarm.Cancel();
-
- if (!wrapped_bytes.ok()) {
- return ExceptionOr<OfflineFrame>(wrapped_bytes.exception());
- }
-
- ByteArray bytes = std::move(wrapped_bytes.result());
- ExceptionOr<OfflineFrame> wrapped_frame = parser::FromBytes(bytes);
- if (wrapped_frame.GetException().Raised(Exception::kInvalidProtocolBuffer)) {
- return ExceptionOr<OfflineFrame>(Exception::kIo);
- }
-
- OfflineFrame& frame = wrapped_frame.result();
- if (V1Frame::CONNECTION_REQUEST != parser::GetFrameType(frame)) {
- return ExceptionOr<OfflineFrame>(Exception::kIo);
- }
-
- return wrapped_frame;
-}
-
-std::string BasePcpHandler::GetHashedConnectionToken(
- const ByteArray& token_bytes) {
- auto token = std::string(token_bytes);
- return location::nearby::Base64Utils::Encode(
- Utils::Sha256Hash(token, token.size()))
- .substr(0, kConnectionTokenLength);
-}
-
-void BasePcpHandler::LogConnectionAttempt(ClientProxy* client, Medium medium,
- const std::string& endpoint_id,
- bool is_incoming,
- absl::Time start_time) {
- proto::connections::ConnectionAttemptResult result =
- Cancelled(client, endpoint_id) ? proto::connections::RESULT_CANCELLED
- : proto::connections::RESULT_ERROR;
- if (is_incoming) {
- client->GetAnalyticsRecorder().OnIncomingConnectionAttempt(
- proto::connections::INITIAL, medium, result,
- SystemClock::ElapsedRealtime() - start_time,
- /* connection_token= */ "");
- } else {
- client->GetAnalyticsRecorder().OnOutgoingConnectionAttempt(
- endpoint_id, proto::connections::INITIAL, medium, result,
- SystemClock::ElapsedRealtime() - start_time,
- /* connection_token= */ "");
- }
-}
-
-bool BasePcpHandler::Cancelled(ClientProxy* client,
- const std::string& endpoint_id) {
- if (endpoint_id.empty()) {
- return false;
- }
-
- return client->GetCancellationFlag(endpoint_id)->Cancelled();
-}
-
-///////////////////// BasePcpHandler::PendingConnectionInfo ///////////////////
-
-void BasePcpHandler::PendingConnectionInfo::SetCryptoContext(
- std::unique_ptr<UKey2Handshake> ukey2) {
- this->ukey2 = std::move(ukey2);
-}
-
-BasePcpHandler::PendingConnectionInfo::~PendingConnectionInfo() {
- auto future_status = result.lock();
- if (future_status && !future_status->IsSet()) {
- NEARBY_LOG(INFO, "Future was not set; destroying info");
- future_status->Set({Status::kError});
- }
-
- if (channel != nullptr) {
- channel->Close(proto::connections::DisconnectionReason::SHUTDOWN);
- }
-
- // Destroy crypto context now; for some reason, crypto context destructor
- // segfaults if it is not destroyed here.
- this->ukey2.reset();
-}
-
-void BasePcpHandler::PendingConnectionInfo::LocalEndpointAcceptedConnection(
- const std::string& endpoint_id, const PayloadListener& payload_listener) {
- client->LocalEndpointAcceptedConnection(endpoint_id, payload_listener);
-}
-
-void BasePcpHandler::PendingConnectionInfo::LocalEndpointRejectedConnection(
- const std::string& endpoint_id) {
- client->LocalEndpointRejectedConnection(endpoint_id);
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/base_pcp_handler.h b/chromium/third_party/nearby/src/cpp/core/internal/base_pcp_handler.h
deleted file mode 100644
index 896d03c4bb2..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/base_pcp_handler.h
+++ /dev/null
@@ -1,524 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_BASE_PCP_HANDLER_H_
-#define CORE_INTERNAL_BASE_PCP_HANDLER_H_
-
-#include <cstdint>
-#include <memory>
-#include <string>
-#include <vector>
-
-#include "securegcm/d2d_connection_context_v1.h"
-#include "securegcm/ukey2_handshake.h"
-#include "absl/container/btree_map.h"
-#include "absl/container/flat_hash_map.h"
-#include "absl/time/time.h"
-#include "core/internal/bwu_manager.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/encryption_runner.h"
-#include "core/internal/endpoint_channel_manager.h"
-#include "core/internal/endpoint_manager.h"
-#include "core/internal/mediums/mediums.h"
-#include "core/internal/mediums/webrtc.h"
-#include "core/internal/pcp.h"
-#include "core/internal/pcp_handler.h"
-#include "core/listeners.h"
-#include "core/options.h"
-#include "core/status.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/prng.h"
-#include "platform/public/atomic_boolean.h"
-#include "platform/public/atomic_reference.h"
-#include "platform/public/cancelable_alarm.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/future.h"
-#include "platform/public/scheduled_executor.h"
-#include "platform/public/single_thread_executor.h"
-#include "platform/public/system_clock.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Represents the WebRtc state that mediums are connectable or not.
-enum class WebRtcState {
- kUndefined = 0,
- kConnectable = 1,
- kUnconnectable = 2,
-};
-
-// Annotations for methods that need to run on PCP handler thread.
-// Use only in BasePcpHandler and derived classes.
-#define RUN_ON_PCP_HANDLER_THREAD() \
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(GetPcpHandlerThread())
-
-// A base implementation of the PcpHandler interface that takes care of all
-// bookkeeping and handshake protocols that are common across all PcpHandler
-// implementations -- thus, every concrete PcpHandler implementation must extend
-// this class, so that they can focus exclusively on the medium-specific
-// operations.
-class BasePcpHandler : public PcpHandler,
- public EndpointManager::FrameProcessor {
- public:
- using FrameProcessor = EndpointManager::FrameProcessor;
-
- // TODO(apolyudov): Add SecureRandom.
- BasePcpHandler(Mediums* mediums, EndpointManager* endpoint_manager,
- EndpointChannelManager* channel_manager,
- BwuManager* bwu_manager, Pcp pcp);
- ~BasePcpHandler() override;
- BasePcpHandler(BasePcpHandler&&) = delete;
- BasePcpHandler& operator=(BasePcpHandler&&) = delete;
-
- // Starts advertising. Once successfully started, changes ClientProxy's state.
- // Notifies ConnectionListener (info.listener) in case of any event.
- // See
- // cpp/core/listeners.h
- Status StartAdvertising(ClientProxy* client, const std::string& service_id,
- const ConnectionOptions& options,
- const ConnectionRequestInfo& info) override;
-
- // Stops Advertising is active, and changes CLientProxy state,
- // otherwise does nothing.
- void StopAdvertising(ClientProxy* client) override;
-
- // Starts discovery of endpoints that may be advertising.
- // Updates ClientProxy state once discovery started.
- // DiscoveryListener will get called in case of any event.
- Status StartDiscovery(ClientProxy* client, const std::string& service_id,
- const ConnectionOptions& options,
- const DiscoveryListener& listener) override;
-
- // Stops Discovery if it is active, and changes CLientProxy state,
- // otherwise does nothing.
- void StopDiscovery(ClientProxy* client) override;
-
- void InjectEndpoint(ClientProxy* client, const std::string& service_id,
- const OutOfBandConnectionMetadata& metadata) override;
-
- // Requests a newly discovered remote endpoint it to form a connection.
- // Updates state on ClientProxy.
- Status RequestConnection(ClientProxy* client, const std::string& endpoint_id,
- const ConnectionRequestInfo& info,
- const ConnectionOptions& options) override;
-
- // Called by either party to accept connection on their part.
- // Until both parties call it, connection will not reach a data phase.
- // Updates state in ClientProxy.
- Status AcceptConnection(ClientProxy* client, const std::string& endpoint_id,
- const PayloadListener& payload_listener) override;
-
- // Called by either party to reject connection on their part.
- // If either party does call it, connection will terminate.
- // Updates state in ClientProxy.
- Status RejectConnection(ClientProxy* client,
- const std::string& endpoint_id) override;
-
- // @EndpointManagerReaderThread
- void OnIncomingFrame(OfflineFrame& frame, const std::string& endpoint_id,
- ClientProxy* client,
- proto::connections::Medium medium) override;
-
- // Called when an endpoint disconnects while we're waiting for both sides to
- // approve/reject the connection.
- // @EndpointManagerThread
- void OnEndpointDisconnect(ClientProxy* client, const std::string& endpoint_id,
- CountDownLatch barrier) override;
-
- Pcp GetPcp() const override { return pcp_; }
- Strategy GetStrategy() const override { return strategy_; }
- void DisconnectFromEndpointManager();
-
- protected:
- // The result of a call to startAdvertisingImpl() or startDiscoveryImpl().
- struct StartOperationResult {
- Status status;
- // If success, the mediums on which we are now advertising/discovering, for
- // analytics.
- std::vector<proto::connections::Medium> mediums;
- };
-
- // Represents an endpoint that we've discovered. Typically, the implementation
- // will know how to connect to this endpoint if asked. (eg. It holds on to a
- // BluetoothDevice)
- //
- // NOTE(DiscoveredEndpoint):
- // Specific protocol is expected to derive from it, as follows:
- // struct ProtocolEndpoint : public DiscoveredEndpoint {
- // ProtocolContext context;
- // };
- // Protocol then allocates instance with std::make_shared<ProtocolEndpoint>(),
- // and passes this instance to OnEndpointFound() method.
- // When calling OnEndpointLost(), protocol does not need to pass the same
- // instance (but it can if implementation desires to do so).
- // BasePcpHandler will hold on to the shared_ptr<DiscoveredEndpoint>.
- struct DiscoveredEndpoint {
- DiscoveredEndpoint(std::string endpoint_id, ByteArray endpoint_info,
- std::string service_id,
- proto::connections::Medium medium,
- WebRtcState web_rtc_state)
- : endpoint_id(std::move(endpoint_id)),
- endpoint_info(std::move(endpoint_info)),
- service_id(std::move(service_id)),
- medium(medium),
- web_rtc_state(web_rtc_state) {}
- virtual ~DiscoveredEndpoint() = default;
-
- std::string endpoint_id;
- ByteArray endpoint_info;
- std::string service_id;
- proto::connections::Medium medium;
- WebRtcState web_rtc_state;
- };
-
- struct BluetoothEndpoint : public DiscoveredEndpoint {
- BluetoothEndpoint(DiscoveredEndpoint endpoint, BluetoothDevice device)
- : DiscoveredEndpoint(std::move(endpoint)),
- bluetooth_device(std::move(device)) {}
-
- BluetoothDevice bluetooth_device;
- };
-
- struct BleEndpoint : public BasePcpHandler::DiscoveredEndpoint {
- BleEndpoint(DiscoveredEndpoint endpoint, BlePeripheral peripheral)
- : DiscoveredEndpoint(std::move(endpoint)),
- ble_peripheral(std::move(peripheral)) {}
- BlePeripheral ble_peripheral;
- };
-
- struct WifiLanEndpoint : public DiscoveredEndpoint {
- WifiLanEndpoint(DiscoveredEndpoint endpoint,
- const NsdServiceInfo& service_info)
- : DiscoveredEndpoint(std::move(endpoint)), service_info(service_info) {}
-
- NsdServiceInfo service_info;
- };
-
- struct WebRtcEndpoint : public DiscoveredEndpoint {
- WebRtcEndpoint(DiscoveredEndpoint endpoint, mediums::WebrtcPeerId peer_id)
- : DiscoveredEndpoint(std::move(endpoint)),
- peer_id(std::move(peer_id)) {}
-
- mediums::WebrtcPeerId peer_id;
- };
-
- struct ConnectImplResult {
- proto::connections::Medium medium =
- proto::connections::Medium::UNKNOWN_MEDIUM;
- Status status = {Status::kError};
- std::unique_ptr<EndpointChannel> endpoint_channel;
- };
-
- void RunOnPcpHandlerThread(const std::string& name, Runnable runnable);
-
- BluetoothDevice GetRemoteBluetoothDevice(
- const std::string& remote_bluetooth_mac_address);
-
- ConnectionOptions GetConnectionOptions() const;
- ConnectionOptions GetDiscoveryOptions() const;
-
- void OnEndpointFound(ClientProxy* client,
- std::shared_ptr<DiscoveredEndpoint> endpoint)
- RUN_ON_PCP_HANDLER_THREAD();
-
- void OnEndpointLost(ClientProxy* client, const DiscoveredEndpoint& endpoint)
- RUN_ON_PCP_HANDLER_THREAD();
-
- Exception OnIncomingConnection(
- ClientProxy* client, const ByteArray& remote_endpoint_info,
- std::unique_ptr<EndpointChannel> endpoint_channel,
- proto::connections::Medium medium); // throws Exception::IO
-
- virtual bool HasOutgoingConnections(ClientProxy* client) const;
- virtual bool HasIncomingConnections(ClientProxy* client) const;
-
- virtual bool CanSendOutgoingConnection(ClientProxy* client) const;
- virtual bool CanReceiveIncomingConnection(ClientProxy* client) const;
-
- virtual StartOperationResult StartAdvertisingImpl(
- ClientProxy* client, const std::string& service_id,
- const std::string& local_endpoint_id,
- const ByteArray& local_endpoint_info, const ConnectionOptions& options)
- RUN_ON_PCP_HANDLER_THREAD() = 0;
-
- virtual Status StopAdvertisingImpl(ClientProxy* client)
- RUN_ON_PCP_HANDLER_THREAD() = 0;
-
- virtual StartOperationResult StartDiscoveryImpl(
- ClientProxy* client, const std::string& service_id,
- const ConnectionOptions& options) RUN_ON_PCP_HANDLER_THREAD() = 0;
-
- virtual Status StopDiscoveryImpl(ClientProxy* client)
- RUN_ON_PCP_HANDLER_THREAD() = 0;
-
- virtual Status InjectEndpointImpl(ClientProxy* client,
- const std::string& service_id,
- const OutOfBandConnectionMetadata& metadata)
- RUN_ON_PCP_HANDLER_THREAD() = 0;
-
- virtual ConnectImplResult ConnectImpl(ClientProxy* client,
- DiscoveredEndpoint* endpoint)
- RUN_ON_PCP_HANDLER_THREAD() = 0;
-
- virtual std::vector<proto::connections::Medium>
- GetConnectionMediumsByPriority() = 0;
- virtual proto::connections::Medium GetDefaultUpgradeMedium() = 0;
-
- // Returns the first discovered endpoint for the given endpoint_id.
- DiscoveredEndpoint* GetDiscoveredEndpoint(const std::string& endpoint_id);
-
- // Returns a vector of discovered endpoints, sorted in order of decreasing
- // preference.
- std::vector<BasePcpHandler::DiscoveredEndpoint*> GetDiscoveredEndpoints(
- const std::string& endpoint_id);
-
- // Returns a vector of discovered endpoints that share a given Medium.
- std::vector<BasePcpHandler::DiscoveredEndpoint*> GetDiscoveredEndpoints(
- const proto::connections::Medium medium);
-
- mediums::WebrtcPeerId CreatePeerIdFromAdvertisement(
- const string& service_id, const string& endpoint_id,
- const ByteArray& endpoint_info);
-
- SingleThreadExecutor* GetPcpHandlerThread()
- ABSL_LOCK_RETURNED(serial_executor_) {
- return &serial_executor_;
- }
-
- Mediums* mediums_;
- EndpointManager* endpoint_manager_;
- EndpointChannelManager* channel_manager_;
-
- private:
- struct PendingConnectionInfo {
- PendingConnectionInfo() = default;
- PendingConnectionInfo(PendingConnectionInfo&& other) = default;
- PendingConnectionInfo& operator=(PendingConnectionInfo&&) = default;
- ~PendingConnectionInfo();
-
- // Passes crypto context that we acquired in DH session for temporary
- // ownership here.
- void SetCryptoContext(std::unique_ptr<securegcm::UKey2Handshake> ukey2);
-
- // Pass Accept notification to client.
- void LocalEndpointAcceptedConnection(
- const std::string& endpoint_id,
- const PayloadListener& payload_listener);
-
- // Pass Reject notification to client.
- void LocalEndpointRejectedConnection(const std::string& endpoint_id);
-
- // Client state tracker to report events to. Never changes. Always valid.
- ClientProxy* client = nullptr;
- // Peer endpoint info, or empty, if not discovered yet. May change.
- ByteArray remote_endpoint_info;
- std::int32_t nonce = 0;
- bool is_incoming = false;
- absl::Time start_time{absl::InfinitePast()};
- // Client callbacks. Always valid.
- ConnectionListener listener;
- ConnectionOptions options;
-
- // Only set for outgoing connections. If set, we must call
- // result->Set() when connection is established, or rejected.
- std::weak_ptr<Future<Status>> result;
-
- // Only (possibly) vector for incoming connections.
- std::vector<proto::connections::Medium> supported_mediums;
-
- // Keep track of a channel before we pass it to EndpointChannelManager.
- std::unique_ptr<EndpointChannel> channel;
-
- // Crypto context; initially empty; established first thing after channel
- // creation by running UKey2 session. While it is in progress, we keep track
- // of channel ourselves. Once it is done, we pass channel over to
- // EndpointChannelManager. We keep crypto context until connection is
- // accepted. Crypto context is passed over to channel_manager_ before
- // switching to connected state, where Payload may be exchanged.
- std::unique_ptr<securegcm::UKey2Handshake> ukey2;
-
- // Used in AnalyticsRecorder for devices connection tracking.
- std::string connection_token;
- };
-
- // @EncryptionRunnerThread
- // Called internally when DH session has negotiated a key successfully.
- void OnEncryptionSuccessImpl(const std::string& endpoint_id,
- std::unique_ptr<securegcm::UKey2Handshake> ukey2,
- const std::string& auth_token,
- const ByteArray& raw_auth_token);
-
- // @EncryptionRunnerThread
- // Called internally when DH session was not able to negotiate a key.
- void OnEncryptionFailureImpl(const std::string& endpoint_id,
- EndpointChannel* channel);
-
- EncryptionRunner::ResultListener GetResultListener();
-
- void OnEncryptionSuccessRunnable(
- const std::string& endpoint_id,
- std::unique_ptr<securegcm::UKey2Handshake> ukey2,
- const std::string& auth_token, const ByteArray& raw_auth_token);
- void OnEncryptionFailureRunnable(const std::string& endpoint_id,
- EndpointChannel* endpoint_channel);
-
- static Exception WriteConnectionRequestFrame(
- EndpointChannel* endpoint_channel, const std::string& local_endpoint_id,
- const ByteArray& local_endpoint_info, std::int32_t nonce,
- const std::vector<proto::connections::Medium>& supported_mediums,
- std::int32_t keep_alive_interval_millis,
- std::int32_t keep_alive_timeout_millis);
-
- static constexpr absl::Duration kConnectionRequestReadTimeout =
- absl::Seconds(2);
- static constexpr absl::Duration kRejectedConnectionCloseDelay =
- absl::Seconds(2);
- static constexpr int kConnectionTokenLength = 8;
-
- void OnConnectionResponse(ClientProxy* client, const std::string& endpoint_id,
- const OfflineFrame& frame);
-
- // Returns true if the new endpoint is preferred over the old endpoint.
- bool IsPreferred(const BasePcpHandler::DiscoveredEndpoint& new_endpoint,
- const BasePcpHandler::DiscoveredEndpoint& old_endpoint);
-
- // Returns true, if connection party should respect the specified topology.
- bool ShouldEnforceTopologyConstraints(
- const ConnectionOptions& local_advertising_options) const;
-
- // Returns true, if connection party should attempt to upgrade itself to
- // use a higher bandwidth medium, if it is available.
- bool AutoUpgradeBandwidth(
- const ConnectionOptions& local_advertising_options) const;
-
- // Returns true if the incoming connection should be killed. This only
- // happens when an incoming connection arrives while we have an outgoing
- // connection to the same endpoint and we need to stop one connection.
- bool BreakTie(ClientProxy* client, const std::string& endpoint_id,
- std::int32_t incoming_nonce, EndpointChannel* channel);
- // We're not sure how far our outgoing connection has gotten. We may (or may
- // not) have called ClientProxy::OnConnectionInitiated. Therefore, we'll
- // call both preInit and preResult failures.
- void ProcessTieBreakLoss(ClientProxy* client, const std::string& endpoint_id,
- PendingConnectionInfo* info);
-
- // Returns true if the bluetooth endpoint based on remote bluetooth mac
- // address is created and appended into discovered_endpoints_ with key
- // endpoint_id.
- bool AppendRemoteBluetoothMacAddressEndpoint(
- const std::string& endpoint_id,
- const std::string& remote_bluetooth_mac_address,
- const ConnectionOptions& local_discovery_options);
-
- // Returns true if the webrtc endpoint is created and appended into
- // discovered_endpoints_ with key endpoint_id.
- bool AppendWebRTCEndpoint(const std::string& endpoint_id,
- const ConnectionOptions& local_discovery_options);
-
- void ProcessPreConnectionInitiationFailure(
- ClientProxy* client, Medium medium, const std::string& endpoint_id,
- EndpointChannel* channel, bool is_incoming, absl::Time start_time,
- Status status, Future<Status>* result);
- void ProcessPreConnectionResultFailure(ClientProxy* client,
- const std::string& endpoint_id);
-
- // Called when either side accepts/rejects the connection, but only takes
- // effect after both have accepted or one side has rejected.
- //
- // NOTE: We also take in a 'can_close_immediately' variable. This is because
- // any writes in transit are dropped when we close. To avoid having a reject
- // write being dropped (which causes the other side to report
- // onResult(DISCONNECTED) instead of onResult(REJECTED)), we delay our
- // close. If the other side behaves properly, we shouldn't even see the
- // delay (because they will also close the connection).
- void EvaluateConnectionResult(ClientProxy* client,
- const std::string& endpoint_id,
- bool can_close_immediately);
-
- ExceptionOr<OfflineFrame> ReadConnectionRequestFrame(
- EndpointChannel* channel);
-
- // Returns an 8 characters length hashed string generated via a token byte
- // array.
- std::string GetHashedConnectionToken(const ByteArray& token_bytes);
-
- static void LogConnectionAttempt(ClientProxy* client, Medium medium,
- const std::string& endpoint_id,
- bool is_incoming, absl::Time start_time);
-
- // Returns true if the client cancels the operation in progress through the
- // endpoint id. This is done by CancellationFlag.
- static bool Cancelled(ClientProxy* client, const std::string& endpoint_id);
-
- void WaitForLatch(const std::string& method_name, CountDownLatch* latch);
- Status WaitForResult(const std::string& method_name, std::int64_t client_id,
- Future<Status>* future);
- bool MediumSupportedByClientOptions(
- const proto::connections::Medium& medium,
- const ConnectionOptions& client_options) const;
- std::vector<proto::connections::Medium>
- GetSupportedConnectionMediumsByPriority(
- const ConnectionOptions& local_option);
- std::string GetStringValueOfSupportedMediums(
- const ConnectionOptions& options) const;
-
- // The endpoint id in high visibility mode is stable for 30 seconds, while in
- // low visibility mode it always rotates. We assume a client is trying to
- // rotate endpoint id when the options is "low power" (3P) or "disable
- // Bluetooth classic" (1P).
- bool ShouldEnterHighVisibilityMode(const ConnectionOptions& options);
-
- // Returns the intersection of supported mediums based on the mediums reported
- // by the remote client and the local client's advertising options.
- BooleanMediumSelector ComputeIntersectionOfSupportedMediums(
- const PendingConnectionInfo& connection_info);
-
- ScheduledExecutor alarm_executor_;
- SingleThreadExecutor serial_executor_;
-
- // A map of endpoint id -> PendingConnectionInfo. Entries in this map imply
- // that there is an active connection to the endpoint and we're waiting for
- // both sides to accept before allowing payloads through. Once the fate of
- // the connection is decided (either accepted or rejected), it should be
- // removed from this map.
- absl::flat_hash_map<std::string, PendingConnectionInfo> pending_connections_;
- // A map of endpoint id -> DiscoveredEndpoint.
- absl::btree_multimap<std::string, std::shared_ptr<DiscoveredEndpoint>>
- discovered_endpoints_;
- // A map of endpoint id -> alarm. These alarms delay closing the
- // EndpointChannel to give the other side enough time to read the rejection
- // message. It's expected that the other side will close the connection
- // after reading the message (in which case, this alarm should be cancelled
- // as it's no longer needed), but this alarm is the fallback in case that
- // doesn't happen.
- absl::flat_hash_map<std::string, CancelableAlarm> pending_alarms_;
-
- // The active ClientProxy's connection lifecycle listener. Non-null while
- // advertising.
- ConnectionListener advertising_listener_;
-
- AtomicBoolean stop_{false};
- Pcp pcp_;
- Strategy strategy_{PcpToStrategy(pcp_)};
- Prng prng_;
- EncryptionRunner encryption_runner_;
- BwuManager* bwu_manager_;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_BASE_PCP_HANDLER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/base_pcp_handler_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/base_pcp_handler_test.cc
deleted file mode 100644
index b916cbf39b7..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/base_pcp_handler_test.cc
+++ /dev/null
@@ -1,785 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/base_pcp_handler.h"
-
-#include <array>
-#include <atomic>
-#include <memory>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/time/time.h"
-#include "core/internal/base_endpoint_channel.h"
-#include "core/internal/bwu_manager.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/encryption_runner.h"
-#include "core/internal/offline_frames.h"
-#include "core/listeners.h"
-#include "core/options.h"
-#include "core/params.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/exception.h"
-#include "platform/base/medium_environment.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/pipe.h"
-#include "proto/connections/offline_wire_formats.pb.h"
-#include "proto/connections_enums.pb.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-
-using ::location::nearby::proto::connections::Medium;
-using ::testing::_;
-using ::testing::AtLeast;
-using ::testing::Invoke;
-using ::testing::MockFunction;
-using ::testing::Return;
-using ::testing::StrictMock;
-
-constexpr std::array<char, 6> kFakeMacAddress = {'a', 'b', 'c', 'd', 'e', 'f'};
-
-constexpr BooleanMediumSelector kTestCases[] = {
- BooleanMediumSelector{},
- BooleanMediumSelector{
- .bluetooth = true,
- },
- BooleanMediumSelector{
- .wifi_lan = true,
- },
- BooleanMediumSelector{
- .bluetooth = true,
- .wifi_lan = true,
- },
-};
-
-class MockEndpointChannel : public BaseEndpointChannel {
- public:
- explicit MockEndpointChannel(Pipe* reader, Pipe* writer)
- : BaseEndpointChannel("channel", &reader->GetInputStream(),
- &writer->GetOutputStream()) {}
-
- ExceptionOr<ByteArray> DoRead() { return BaseEndpointChannel::Read(); }
- Exception DoWrite(const ByteArray& data) {
- if (broken_write_) {
- return {Exception::kFailed};
- }
- return BaseEndpointChannel::Write(data);
- }
- absl::Time DoGetLastReadTimestamp() {
- return BaseEndpointChannel::GetLastReadTimestamp();
- }
-
- MOCK_METHOD(ExceptionOr<ByteArray>, Read, (), (override));
- MOCK_METHOD(Exception, Write, (const ByteArray& data), (override));
- MOCK_METHOD(void, CloseImpl, (), (override));
- MOCK_METHOD(proto::connections::Medium, GetMedium, (), (const override));
- MOCK_METHOD(std::string, GetType, (), (const override));
- MOCK_METHOD(std::string, GetName, (), (const override));
- MOCK_METHOD(bool, IsPaused, (), (const override));
- MOCK_METHOD(void, Pause, (), (override));
- MOCK_METHOD(void, Resume, (), (override));
- MOCK_METHOD(absl::Time, GetLastReadTimestamp, (), (const override));
-
- bool broken_write_{false};
-};
-
-class MockPcpHandler : public BasePcpHandler {
- public:
- using DiscoveredEndpoint = BasePcpHandler::DiscoveredEndpoint;
-
- MockPcpHandler(Mediums* m, EndpointManager* em, EndpointChannelManager* ecm,
- BwuManager* bwu)
- : BasePcpHandler(m, em, ecm, bwu, Pcp::kP2pCluster) {}
-
- // Expose protected inner types of a base type for mocking.
- using BasePcpHandler::ConnectImplResult;
- using BasePcpHandler::DiscoveredEndpoint;
- using BasePcpHandler::StartOperationResult;
-
- MOCK_METHOD(Strategy, GetStrategy, (), (const override));
- MOCK_METHOD(Pcp, GetPcp, (), (const override));
-
- MOCK_METHOD(bool, HasOutgoingConnections, (ClientProxy * client),
- (const, override));
- MOCK_METHOD(bool, HasIncomingConnections, (ClientProxy * client),
- (const, override));
-
- MOCK_METHOD(bool, CanSendOutgoingConnection, (ClientProxy * client),
- (const, override));
- MOCK_METHOD(bool, CanReceiveIncomingConnection, (ClientProxy * client),
- (const, override));
-
- MOCK_METHOD(StartOperationResult, StartAdvertisingImpl,
- (ClientProxy * client, const std::string& service_id,
- const std::string& local_endpoint_id,
- const ByteArray& local_endpoint_info,
- const ConnectionOptions& options),
- (override));
- MOCK_METHOD(Status, StopAdvertisingImpl, (ClientProxy * client), (override));
- MOCK_METHOD(StartOperationResult, StartDiscoveryImpl,
- (ClientProxy * client, const std::string& service_id,
- const ConnectionOptions& options),
- (override));
- MOCK_METHOD(Status, StopDiscoveryImpl, (ClientProxy * client), (override));
- MOCK_METHOD(Status, InjectEndpointImpl,
- (ClientProxy * client, const std::string& service_id,
- const OutOfBandConnectionMetadata& metadata),
- (override));
- MOCK_METHOD(ConnectImplResult, ConnectImpl,
- (ClientProxy * client, DiscoveredEndpoint* endpoint), (override));
- MOCK_METHOD(proto::connections::Medium, GetDefaultUpgradeMedium, (),
- (override));
-
- std::vector<proto::connections::Medium> GetConnectionMediumsByPriority()
- override {
- return std::vector<proto::connections::Medium>{
- proto::connections::WIFI_LAN, proto::connections::WEB_RTC,
- proto::connections::BLUETOOTH, proto::connections::BLE};
- }
-
- // Mock adapters for protected non-virtual methods of a base class.
- void OnEndpointFound(ClientProxy* client,
- std::shared_ptr<DiscoveredEndpoint> endpoint)
- ABSL_NO_THREAD_SAFETY_ANALYSIS {
- BasePcpHandler::OnEndpointFound(client, std::move(endpoint));
- }
- void OnEndpointLost(ClientProxy* client, const DiscoveredEndpoint& endpoint)
- ABSL_NO_THREAD_SAFETY_ANALYSIS {
- BasePcpHandler::OnEndpointLost(client, endpoint);
- }
- std::vector<BasePcpHandler::DiscoveredEndpoint*> GetDiscoveredEndpoints(
- const std::string& endpoint_id) {
- return BasePcpHandler::GetDiscoveredEndpoints(endpoint_id);
- }
-
- std::vector<proto::connections::Medium> GetDiscoveryMediums(
- ClientProxy* client) {
- auto allowed = client->GetDiscoveryOptions().CompatibleOptions().allowed;
- return GetMediumsFromSelector(allowed);
- }
-
- std::vector<proto::connections::Medium> GetMediumsFromSelector(
- BooleanMediumSelector allowed) {
- return allowed.GetMediums(true);
- }
-};
-
-class MockContext {
- public:
- explicit MockContext(std::atomic_int* destroyed = nullptr)
- : destroyed_{destroyed} {}
- MockContext(MockContext&& other) { *this = std::move(other); }
- MockContext& operator=(MockContext&& other) {
- destroyed_ = other.destroyed_;
- other.destroyed_ = nullptr;
- return *this;
- }
-
- ~MockContext() {
- if (destroyed_) (*destroyed_)++;
- }
-
- private:
- std::atomic_int* destroyed_;
-};
-
-struct MockDiscoveredEndpoint : public MockPcpHandler::DiscoveredEndpoint {
- MockDiscoveredEndpoint(DiscoveredEndpoint endpoint, MockContext context)
- : DiscoveredEndpoint(std::move(endpoint)), context(std::move(context)) {}
-
- MockContext context;
-};
-
-class BasePcpHandlerTest
- : public ::testing::TestWithParam<BooleanMediumSelector> {
- protected:
- struct MockConnectionListener {
- StrictMock<MockFunction<void(const std::string& endpoint_id,
- const ConnectionResponseInfo& info)>>
- initiated_cb;
- StrictMock<MockFunction<void(const std::string& endpoint_id)>> accepted_cb;
- StrictMock<MockFunction<void(const std::string& endpoint_id,
- const Status& status)>>
- rejected_cb;
- StrictMock<MockFunction<void(const std::string& endpoint_id)>>
- disconnected_cb;
- StrictMock<MockFunction<void(const std::string& endpoint_id,
- std::int32_t quality)>>
- bandwidth_changed_cb;
- };
- struct MockDiscoveryListener {
- StrictMock<MockFunction<void(const std::string& endpoint_id,
- const ByteArray& endpoint_info,
- const std::string& service_id)>>
- endpoint_found_cb;
- StrictMock<MockFunction<void(const std::string& endpoint_id)>>
- endpoint_lost_cb;
- StrictMock<
- MockFunction<void(const std::string& endpoint_id, DistanceInfo info)>>
- endpoint_distance_changed_cb;
- };
-
- void StartAdvertising(ClientProxy* client, MockPcpHandler* pcp_handler,
- BooleanMediumSelector allowed = GetParam()) {
- std::string service_id{"service"};
- ConnectionOptions options{
- .strategy = Strategy::kP2pCluster,
- .allowed = allowed,
- .auto_upgrade_bandwidth = true,
- .enforce_topology_constraints = true,
- };
- ConnectionRequestInfo info{
- .endpoint_info = ByteArray{"remote_endpoint_name"},
- .listener = connection_listener_,
- };
- EXPECT_CALL(*pcp_handler, StartAdvertisingImpl(client, service_id, _,
- info.endpoint_info, _))
- .WillOnce(Return(MockPcpHandler::StartOperationResult{
- .status = {Status::kSuccess},
- .mediums = pcp_handler->GetMediumsFromSelector(allowed),
- }));
- EXPECT_EQ(pcp_handler->StartAdvertising(client, service_id, options, info),
- Status{Status::kSuccess});
- EXPECT_TRUE(client->IsAdvertising());
- }
-
- void StartDiscovery(ClientProxy* client, MockPcpHandler* pcp_handler,
- BooleanMediumSelector allowed = GetParam()) {
- std::string service_id{"service"};
- ConnectionOptions options{
- .strategy = Strategy::kP2pCluster,
- .allowed = allowed,
- .auto_upgrade_bandwidth = true,
- .enforce_topology_constraints = true,
- .keep_alive_interval_millis = 5000,
- .keep_alive_timeout_millis = 3000,
- };
- EXPECT_CALL(*pcp_handler, StartDiscoveryImpl(client, service_id, _))
- .WillOnce(Return(MockPcpHandler::StartOperationResult{
- .status = {Status::kSuccess},
- .mediums = pcp_handler->GetMediumsFromSelector(allowed),
- }));
- EXPECT_EQ(pcp_handler->StartDiscovery(client, service_id, options,
- discovery_listener_),
- Status{Status::kSuccess});
- EXPECT_TRUE(client->IsDiscovering());
- }
-
- std::pair<std::unique_ptr<MockEndpointChannel>,
- std::unique_ptr<MockEndpointChannel>>
- SetupConnection(Pipe& pipe_a, Pipe& pipe_b,
- proto::connections::Medium medium) { // NOLINT
- auto channel_a = std::make_unique<MockEndpointChannel>(&pipe_b, &pipe_a);
- auto channel_b = std::make_unique<MockEndpointChannel>(&pipe_a, &pipe_b);
- // On initiator (A) side, we drop the first write, since this is a
- // connection establishment packet, and we don't have the peer entity, just
- // the peer channel. The rest of the exchange must happen for the benefit of
- // DH key exchange.
- EXPECT_CALL(*channel_a, Read())
- .WillRepeatedly(Invoke(
- [channel = channel_a.get()]() { return channel->DoRead(); }));
- EXPECT_CALL(*channel_a, Write(_))
- .WillOnce(Return(Exception{Exception::kSuccess}))
- .WillRepeatedly(
- Invoke([channel = channel_a.get()](const ByteArray& data) {
- return channel->DoWrite(data);
- }));
- EXPECT_CALL(*channel_a, GetMedium).WillRepeatedly(Return(medium));
- EXPECT_CALL(*channel_a, GetLastReadTimestamp)
- .WillRepeatedly(Return(absl::Now()));
- EXPECT_CALL(*channel_a, IsPaused).WillRepeatedly(Return(false));
- EXPECT_CALL(*channel_b, Read())
- .WillRepeatedly(Invoke(
- [channel = channel_b.get()]() { return channel->DoRead(); }));
- EXPECT_CALL(*channel_b, Write(_))
- .WillRepeatedly(
- Invoke([channel = channel_b.get()](const ByteArray& data) {
- return channel->DoWrite(data);
- }));
- EXPECT_CALL(*channel_b, GetMedium).WillRepeatedly(Return(medium));
- EXPECT_CALL(*channel_b, GetLastReadTimestamp)
- .WillRepeatedly(Return(absl::Now()));
- EXPECT_CALL(*channel_b, IsPaused).WillRepeatedly(Return(false));
- return std::make_pair(std::move(channel_a), std::move(channel_b));
- }
-
- void RequestConnection(const std::string& endpoint_id,
- std::unique_ptr<MockEndpointChannel> channel_a,
- MockEndpointChannel* channel_b, ClientProxy* client,
- MockPcpHandler* pcp_handler,
- proto::connections::Medium connect_medium,
- std::atomic_int* flag = nullptr,
- Status expected_result = {Status::kSuccess}) {
- ConnectionRequestInfo info{
- .endpoint_info = ByteArray{"ABCD"},
- .listener = connection_listener_,
- };
- ConnectionOptions options{
- .remote_bluetooth_mac_address =
- ByteArray{std::string("\x12\x34\x56\x78\x9a\xbc")},
- .keep_alive_interval_millis =
- FeatureFlags::GetInstance().GetFlags().keep_alive_interval_millis,
- .keep_alive_timeout_millis =
- FeatureFlags::GetInstance().GetFlags().keep_alive_timeout_millis,
- };
- EXPECT_CALL(mock_discovery_listener_.endpoint_found_cb, Call);
- EXPECT_CALL(*pcp_handler, CanSendOutgoingConnection)
- .WillRepeatedly(Return(true));
- EXPECT_CALL(*pcp_handler, GetStrategy)
- .WillRepeatedly(Return(Strategy::kP2pCluster));
- if (expected_result == Status{Status::kSuccess}) {
- EXPECT_CALL(mock_connection_listener_.initiated_cb, Call).Times(1);
- }
- // Simulate successful discovery.
- auto encryption_runner = std::make_unique<EncryptionRunner>();
- auto allowed_mediums = pcp_handler->GetDiscoveryMediums(client);
-
- EXPECT_CALL(*pcp_handler, ConnectImpl)
- .WillOnce(Invoke([&channel_a, connect_medium](
- ClientProxy* client,
- MockPcpHandler::DiscoveredEndpoint* endpoint) {
- return MockPcpHandler::ConnectImplResult{
- .medium = connect_medium,
- .status = {Status::kSuccess},
- .endpoint_channel = std::move(channel_a),
- };
- }));
-
- for (const auto& discovered_medium : allowed_mediums) {
- pcp_handler->OnEndpointFound(
- client,
- std::make_shared<MockDiscoveredEndpoint>(MockDiscoveredEndpoint{
- {
- endpoint_id,
- info.endpoint_info,
- "service",
- discovered_medium,
- WebRtcState::kUndefined,
- },
- MockContext{flag},
- }));
- }
- auto other_client = std::make_unique<ClientProxy>();
-
- // Run peer crypto in advance, if channel_b is provided.
- // Otherwise stay in not-encrypted state.
- if (channel_b != nullptr) {
- encryption_runner->StartServer(other_client.get(), endpoint_id, channel_b,
- {});
- }
- EXPECT_EQ(
- pcp_handler->RequestConnection(client, endpoint_id, info, options),
- expected_result);
- NEARBY_LOG(INFO, "Stopping Encryption Runner");
- }
-
- Pipe pipe_a_;
- Pipe pipe_b_;
- MockConnectionListener mock_connection_listener_;
- MockDiscoveryListener mock_discovery_listener_;
- ConnectionListener connection_listener_{
- .initiated_cb = mock_connection_listener_.initiated_cb.AsStdFunction(),
- .accepted_cb = mock_connection_listener_.accepted_cb.AsStdFunction(),
- .rejected_cb = mock_connection_listener_.rejected_cb.AsStdFunction(),
- .disconnected_cb =
- mock_connection_listener_.disconnected_cb.AsStdFunction(),
- .bandwidth_changed_cb =
- mock_connection_listener_.bandwidth_changed_cb.AsStdFunction(),
- };
- DiscoveryListener discovery_listener_{
- .endpoint_found_cb =
- mock_discovery_listener_.endpoint_found_cb.AsStdFunction(),
- .endpoint_lost_cb =
- mock_discovery_listener_.endpoint_lost_cb.AsStdFunction(),
- .endpoint_distance_changed_cb =
- mock_discovery_listener_.endpoint_distance_changed_cb.AsStdFunction(),
- };
- MediumEnvironment& env_ = MediumEnvironment::Instance();
-};
-
-TEST_P(BasePcpHandlerTest, ConstructorDestructorWorks) {
- env_.Start();
- Mediums m;
- EndpointChannelManager ecm;
- EndpointManager em(&ecm);
- BwuManager bwu(m, em, ecm, {}, {});
- MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
- SUCCEED();
- bwu.Shutdown();
- env_.Stop();
-}
-
-TEST_P(BasePcpHandlerTest, StartAdvertisingChangesState) {
- env_.Start();
- ClientProxy client;
- Mediums m;
- EndpointChannelManager ecm;
- EndpointManager em(&ecm);
- BwuManager bwu(m, em, ecm, {}, {});
- MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
- StartAdvertising(&client, &pcp_handler);
- bwu.Shutdown();
- env_.Stop();
-}
-
-TEST_P(BasePcpHandlerTest, StopAdvertisingChangesState) {
- env_.Start();
- ClientProxy client;
- Mediums m;
- EndpointChannelManager ecm;
- EndpointManager em(&ecm);
- BwuManager bwu(m, em, ecm, {}, {});
- MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
- StartAdvertising(&client, &pcp_handler);
- EXPECT_CALL(pcp_handler, StopAdvertisingImpl(&client)).Times(1);
- EXPECT_TRUE(client.IsAdvertising());
- pcp_handler.StopAdvertising(&client);
- EXPECT_FALSE(client.IsAdvertising());
- bwu.Shutdown();
- env_.Stop();
-}
-
-TEST_P(BasePcpHandlerTest, StartDiscoveryChangesState) {
- env_.Start();
- ClientProxy client;
- Mediums m;
- EndpointChannelManager ecm;
- EndpointManager em(&ecm);
- BwuManager bwu(m, em, ecm, {}, {});
- MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
- StartDiscovery(&client, &pcp_handler);
- bwu.Shutdown();
- env_.Stop();
-}
-
-TEST_P(BasePcpHandlerTest, StopDiscoveryChangesState) {
- env_.Start();
- ClientProxy client;
- Mediums m;
- EndpointChannelManager ecm;
- EndpointManager em(&ecm);
- BwuManager bwu(m, em, ecm, {}, {});
- MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
- StartDiscovery(&client, &pcp_handler);
- EXPECT_CALL(pcp_handler, StopDiscoveryImpl(&client)).Times(1);
- EXPECT_TRUE(client.IsDiscovering());
- pcp_handler.StopDiscovery(&client);
- EXPECT_FALSE(client.IsDiscovering());
- bwu.Shutdown();
- env_.Stop();
-}
-
-TEST_P(BasePcpHandlerTest, RequestConnectionChangesState) {
- env_.Start();
- std::string endpoint_id{"1234"};
- ClientProxy client;
- Mediums m;
- EndpointChannelManager ecm;
- EndpointManager em(&ecm);
- BwuManager bwu(m, em, ecm, {}, {});
- MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
- StartDiscovery(&client, &pcp_handler);
- auto mediums = pcp_handler.GetDiscoveryMediums(&client);
- auto connect_medium = mediums[mediums.size() - 1];
- auto channel_pair = SetupConnection(pipe_a_, pipe_b_, connect_medium);
- auto& channel_a = channel_pair.first;
- auto& channel_b = channel_pair.second;
- EXPECT_CALL(*channel_a, CloseImpl).Times(1);
- EXPECT_CALL(*channel_b, CloseImpl).Times(1);
- EXPECT_CALL(mock_connection_listener_.rejected_cb, Call).Times(AtLeast(0));
- RequestConnection(endpoint_id, std::move(channel_a), channel_b.get(), &client,
- &pcp_handler, connect_medium);
- NEARBY_LOG(INFO, "RequestConnection complete");
- channel_b->Close();
- bwu.Shutdown();
- pcp_handler.DisconnectFromEndpointManager();
- env_.Stop();
-}
-
-TEST_P(BasePcpHandlerTest, IoError_RequestConnectionFails) {
- env_.Start();
- std::string endpoint_id{"1234"};
- ClientProxy client;
- Mediums m;
- EndpointChannelManager ecm;
- EndpointManager em(&ecm);
- BwuManager bwu(m, em, ecm, {}, {});
- MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
- StartDiscovery(&client, &pcp_handler);
- auto mediums = pcp_handler.GetDiscoveryMediums(&client);
- auto connect_medium = mediums[mediums.size() - 1];
- auto channel_pair = SetupConnection(pipe_a_, pipe_b_, connect_medium);
- auto& channel_a = channel_pair.first;
- auto& channel_b = channel_pair.second;
- EXPECT_CALL(*channel_a, CloseImpl).Times(AtLeast(1));
- EXPECT_CALL(*channel_b, CloseImpl).Times(AtLeast(1));
- channel_b->broken_write_ = true;
- EXPECT_CALL(mock_connection_listener_.rejected_cb, Call).Times(AtLeast(0));
- RequestConnection(endpoint_id, std::move(channel_a), channel_b.get(), &client,
- &pcp_handler, connect_medium, nullptr,
- {Status::kEndpointIoError});
- NEARBY_LOG(INFO, "RequestConnection complete");
- channel_b->Close();
- bwu.Shutdown();
- pcp_handler.DisconnectFromEndpointManager();
- env_.Stop();
-}
-
-TEST_P(BasePcpHandlerTest, AcceptConnectionChangesState) {
- env_.Start();
- std::string endpoint_id{"1234"};
- ClientProxy client;
- Mediums m;
- EndpointChannelManager ecm;
- EndpointManager em(&ecm);
- BwuManager bwu(m, em, ecm, {}, {});
- MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
- StartDiscovery(&client, &pcp_handler);
- auto mediums = pcp_handler.GetDiscoveryMediums(&client);
- auto connect_medium = mediums[mediums.size() - 1];
- auto channel_pair = SetupConnection(pipe_a_, pipe_b_, connect_medium);
- auto& channel_a = channel_pair.first;
- auto& channel_b = channel_pair.second;
- EXPECT_CALL(*channel_a, CloseImpl).Times(1);
- EXPECT_CALL(*channel_b, CloseImpl).Times(1);
- RequestConnection(endpoint_id, std::move(channel_a), channel_b.get(), &client,
- &pcp_handler, connect_medium);
- NEARBY_LOG(INFO, "Attempting to accept connection: id=%s",
- endpoint_id.c_str());
- EXPECT_EQ(pcp_handler.AcceptConnection(&client, endpoint_id, {}),
- Status{Status::kSuccess});
- EXPECT_CALL(mock_connection_listener_.rejected_cb, Call).Times(AtLeast(0));
- NEARBY_LOGS(INFO) << "Closing connection: id=" << endpoint_id;
- channel_b->Close();
- bwu.Shutdown();
- pcp_handler.DisconnectFromEndpointManager();
- env_.Stop();
-}
-
-TEST_P(BasePcpHandlerTest, RejectConnectionChangesState) {
- env_.Start();
- std::string endpoint_id{"1234"};
- ClientProxy client;
- Mediums m;
- EndpointChannelManager ecm;
- EndpointManager em(&ecm);
- BwuManager bwu(m, em, ecm, {}, {});
- MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
- StartDiscovery(&client, &pcp_handler);
- auto mediums = pcp_handler.GetDiscoveryMediums(&client);
- auto connect_medium = mediums[mediums.size() - 1];
- auto channel_pair = SetupConnection(pipe_a_, pipe_b_, connect_medium);
- auto& channel_b = channel_pair.second;
- EXPECT_CALL(mock_connection_listener_.rejected_cb, Call).Times(1);
- RequestConnection(endpoint_id, std::move(channel_pair.first), channel_b.get(),
- &client, &pcp_handler, connect_medium);
- NEARBY_LOGS(INFO) << "Attempting to reject connection: id=" << endpoint_id;
- EXPECT_EQ(pcp_handler.RejectConnection(&client, endpoint_id),
- Status{Status::kSuccess});
- NEARBY_LOGS(INFO) << "Closing connection: id=" << endpoint_id;
- channel_b->Close();
- bwu.Shutdown();
- pcp_handler.DisconnectFromEndpointManager();
- env_.Stop();
-}
-
-TEST_P(BasePcpHandlerTest, OnIncomingFrameChangesState) {
- env_.Start();
- std::string endpoint_id{"1234"};
- ClientProxy client;
- Mediums m;
- EndpointChannelManager ecm;
- EndpointManager em(&ecm);
- BwuManager bwu(m, em, ecm, {}, {});
- MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
- StartDiscovery(&client, &pcp_handler);
- auto mediums = pcp_handler.GetDiscoveryMediums(&client);
- auto connect_medium = mediums[mediums.size() - 1];
- auto channel_pair = SetupConnection(pipe_a_, pipe_b_, connect_medium);
- auto& channel_a = channel_pair.first;
- auto& channel_b = channel_pair.second;
- EXPECT_CALL(*channel_a, CloseImpl).Times(1);
- EXPECT_CALL(*channel_b, CloseImpl).Times(1);
- RequestConnection(endpoint_id, std::move(channel_a), channel_b.get(), &client,
- &pcp_handler, connect_medium);
- NEARBY_LOGS(INFO) << "Attempting to accept connection: id=" << endpoint_id;
- EXPECT_CALL(mock_connection_listener_.accepted_cb, Call).Times(1);
- EXPECT_CALL(mock_connection_listener_.disconnected_cb, Call)
- .Times(AtLeast(0));
- EXPECT_EQ(pcp_handler.AcceptConnection(&client, endpoint_id, {}),
- Status{Status::kSuccess});
- NEARBY_LOG(INFO, "Simulating remote accept: id=%s", endpoint_id.c_str());
- auto frame =
- parser::FromBytes(parser::ForConnectionResponse(Status::kSuccess));
- pcp_handler.OnIncomingFrame(frame.result(), endpoint_id, &client,
- connect_medium);
- NEARBY_LOGS(INFO) << "Closing connection: id=" << endpoint_id;
- channel_b->Close();
- bwu.Shutdown();
- pcp_handler.DisconnectFromEndpointManager();
- env_.Stop();
-}
-
-TEST_P(BasePcpHandlerTest, DestructorIsCalledOnProtocolEndpoint) {
- env_.Start();
- std::atomic_int destroyed_flag = 0;
- int mediums_count = 0;
- {
- std::string endpoint_id{"1234"};
- ClientProxy client;
- Mediums m;
- EndpointChannelManager ecm;
- EndpointManager em(&ecm);
- BwuManager bwu(m, em, ecm, {}, {});
- MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
- StartDiscovery(&client, &pcp_handler);
- auto mediums = pcp_handler.GetDiscoveryMediums(&client);
- auto connect_medium = mediums[mediums.size() - 1];
- auto channel_pair = SetupConnection(pipe_a_, pipe_b_, connect_medium);
- auto& channel_a = channel_pair.first;
- auto& channel_b = channel_pair.second;
- EXPECT_CALL(*channel_a, CloseImpl).Times(1);
- EXPECT_CALL(*channel_b, CloseImpl).Times(1);
- RequestConnection(endpoint_id, std::move(channel_a), channel_b.get(),
- &client, &pcp_handler, connect_medium, &destroyed_flag);
- mediums_count = mediums.size();
- NEARBY_LOG(INFO, "Attempting to accept connection: id=%s",
- endpoint_id.c_str());
- EXPECT_EQ(pcp_handler.AcceptConnection(&client, endpoint_id, {}),
- Status{Status::kSuccess});
- EXPECT_CALL(mock_connection_listener_.rejected_cb, Call).Times(AtLeast(0));
- NEARBY_LOG(INFO, "Closing connection: id=%s", endpoint_id.c_str());
- channel_b->Close();
- bwu.Shutdown();
- pcp_handler.DisconnectFromEndpointManager();
- }
- EXPECT_EQ(destroyed_flag.load(), mediums_count);
- env_.Stop();
-}
-
-TEST_P(BasePcpHandlerTest, MultipleMediumsProduceSingleEndpointLostEvent) {
- env_.Start();
- BooleanMediumSelector allowed = GetParam();
- if (allowed.Count(true) < 2) {
- // Ignore single-medium test cases, and implicit "all mediums" case.
- SUCCEED();
- return;
- }
- std::atomic_int destroyed_flag = 0;
- int mediums_count = 0;
- {
- std::string endpoint_id{"1234"};
- ClientProxy client;
- Mediums m;
- EndpointChannelManager ecm;
- EndpointManager em(&ecm);
- BwuManager bwu(m, em, ecm, {}, {});
- MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
- StartDiscovery(&client, &pcp_handler);
- auto mediums = pcp_handler.GetDiscoveryMediums(&client);
- auto connect_medium = mediums[mediums.size() - 1];
- auto channel_pair = SetupConnection(pipe_a_, pipe_b_, connect_medium);
- auto& channel_a = channel_pair.first;
- auto& channel_b = channel_pair.second;
- EXPECT_CALL(*channel_a, CloseImpl).Times(1);
- EXPECT_CALL(*channel_b, CloseImpl).Times(1);
- EXPECT_CALL(mock_discovery_listener_.endpoint_lost_cb, Call).Times(1);
- RequestConnection(endpoint_id, std::move(channel_a), channel_b.get(),
- &client, &pcp_handler, connect_medium, &destroyed_flag);
- auto allowed_mediums = pcp_handler.GetDiscoveryMediums(&client);
- mediums_count = allowed_mediums.size();
- NEARBY_LOG(INFO, "Attempting to accept connection: id=%s",
- endpoint_id.c_str());
- EXPECT_EQ(pcp_handler.AcceptConnection(&client, endpoint_id, {}),
- Status{Status::kSuccess});
- EXPECT_CALL(mock_connection_listener_.rejected_cb, Call).Times(AtLeast(0));
- for (const auto* endpoint :
- pcp_handler.GetDiscoveredEndpoints(endpoint_id)) {
- pcp_handler.OnEndpointLost(&client, *endpoint);
- }
- NEARBY_LOG(INFO, "Closing connection: id=%s", endpoint_id.c_str());
- channel_b->Close();
- bwu.Shutdown();
- pcp_handler.DisconnectFromEndpointManager();
- }
- EXPECT_EQ(destroyed_flag.load(), mediums_count);
- env_.Stop();
-}
-
-INSTANTIATE_TEST_SUITE_P(ParameterizedBasePcpHandlerTest, BasePcpHandlerTest,
- ::testing::ValuesIn(kTestCases));
-
-TEST_F(BasePcpHandlerTest, InjectEndpoint) {
- env_.Start();
- std::string service_id{"service"};
- std::string endpoint_id{"ABCD"};
- ClientProxy client;
- Mediums m;
- EndpointChannelManager ecm;
- EndpointManager em(&ecm);
- BwuManager bwu(m, em, ecm, {}, {});
- MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
- BooleanMediumSelector allowed{
- .bluetooth = true,
- };
- ConnectionOptions options{
- .allowed = allowed,
- .is_out_of_band_connection = true,
- };
- EXPECT_CALL(mock_discovery_listener_.endpoint_found_cb, Call);
- EXPECT_CALL(pcp_handler, StartDiscoveryImpl(&client, service_id, _))
- .WillOnce(Return(MockPcpHandler::StartOperationResult{
- .status = {Status::kSuccess},
- .mediums = allowed.GetMediums(true),
- }));
- EXPECT_EQ(pcp_handler.StartDiscovery(&client, service_id, options,
- discovery_listener_),
- Status{Status::kSuccess});
- EXPECT_TRUE(client.IsDiscovering());
-
- EXPECT_CALL(pcp_handler, InjectEndpointImpl(&client, service_id, _))
- .WillOnce(Invoke([&pcp_handler, &endpoint_id](
- ClientProxy* client, const std::string& service_id,
- const OutOfBandConnectionMetadata& metadata) {
- pcp_handler.OnEndpointFound(
- client,
- std::make_shared<MockDiscoveredEndpoint>(MockDiscoveredEndpoint{
- {
- endpoint_id,
- /*endpoint_info=*/ByteArray{"ABCD"},
- service_id,
- Medium::BLUETOOTH,
- WebRtcState::kUndefined,
- },
- MockContext{nullptr},
- }));
- return Status{Status::kSuccess};
- }));
- pcp_handler.InjectEndpoint(
- &client, service_id,
- OutOfBandConnectionMetadata{
- .medium = Medium::BLUETOOTH,
- .remote_bluetooth_mac_address = ByteArray(kFakeMacAddress),
- });
- bwu.Shutdown();
- env_.Stop();
-}
-
-} // namespace
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/ble_advertisement.cc b/chromium/third_party/nearby/src/cpp/core/internal/ble_advertisement.cc
deleted file mode 100644
index ba856d8eee8..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/ble_advertisement.cc
+++ /dev/null
@@ -1,278 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/ble_advertisement.h"
-
-#include <inttypes.h>
-
-#include "absl/strings/escaping.h"
-#include "core/internal/base_pcp_handler.h"
-#include "platform/base/base_input_stream.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-BleAdvertisement::BleAdvertisement(Version version, Pcp pcp,
- const ByteArray& service_id_hash,
- const std::string& endpoint_id,
- const ByteArray& endpoint_info,
- const std::string& bluetooth_mac_address,
- const ByteArray& uwb_address,
- WebRtcState web_rtc_state) {
- DoInitialize(/*fast_advertisement=*/false, version, pcp, service_id_hash,
- endpoint_id, endpoint_info, bluetooth_mac_address, uwb_address,
- web_rtc_state);
-}
-
-BleAdvertisement::BleAdvertisement(Version version, Pcp pcp,
- const std::string& endpoint_id,
- const ByteArray& endpoint_info,
- const ByteArray& uwb_address) {
- DoInitialize(/*fast_advertisement=*/true, version, pcp, {}, endpoint_id,
- endpoint_info, {}, uwb_address, WebRtcState::kUndefined);
-}
-
-void BleAdvertisement::DoInitialize(bool fast_advertisement, Version version,
- Pcp pcp, const ByteArray& service_id_hash,
- const std::string& endpoint_id,
- const ByteArray& endpoint_info,
- const std::string& bluetooth_mac_address,
- const ByteArray& uwb_address,
- WebRtcState web_rtc_state) {
- fast_advertisement_ = fast_advertisement;
- if (!fast_advertisement_) {
- if (service_id_hash.size() != kServiceIdHashLength) return;
- }
- int max_endpoint_info_length =
- fast_advertisement_ ? kMaxFastEndpointInfoLength : kMaxEndpointInfoLength;
- if (version != Version::kV1 || endpoint_id.empty() ||
- endpoint_id.length() != kEndpointIdLength ||
- endpoint_info.size() > max_endpoint_info_length) {
- return;
- }
-
- switch (pcp) {
- case Pcp::kP2pCluster: // Fall through
- case Pcp::kP2pStar: // Fall through
- case Pcp::kP2pPointToPoint:
- break;
- default:
- return;
- }
-
- version_ = version;
- pcp_ = pcp;
- service_id_hash_ = service_id_hash;
- endpoint_id_ = endpoint_id;
- endpoint_info_ = endpoint_info;
- uwb_address_ = uwb_address;
- if (!fast_advertisement_) {
- if (!BluetoothUtils::FromString(bluetooth_mac_address).Empty()) {
- bluetooth_mac_address_ = bluetooth_mac_address;
- }
-
- web_rtc_state_ = web_rtc_state;
- }
-}
-
-BleAdvertisement::BleAdvertisement(bool fast_advertisement,
- const ByteArray& ble_advertisement_bytes) {
- fast_advertisement_ = fast_advertisement;
-
- if (ble_advertisement_bytes.Empty()) {
- NEARBY_LOG(ERROR,
- "Cannot deserialize BleAdvertisement: null bytes passed in.");
- return;
- }
-
- int min_advertisement_length = fast_advertisement_
- ? kMinFastAdvertisementLength
- : kMinAdvertisementLength;
-
- if (ble_advertisement_bytes.size() < min_advertisement_length) {
- NEARBY_LOG(ERROR,
- "Cannot deserialize BleAdvertisement: expecting min %d raw "
- "bytes, got %" PRIu64,
- kMinAdvertisementLength, ble_advertisement_bytes.size());
- return;
- }
-
- ByteArray advertisement_bytes{ble_advertisement_bytes};
- BaseInputStream base_input_stream{advertisement_bytes};
- // The first 1 byte is supposed to be the version and pcp.
- auto version_and_pcp_byte = static_cast<char>(base_input_stream.ReadUint8());
- // The upper 3 bits are supposed to be the version.
- version_ =
- static_cast<Version>((version_and_pcp_byte & kVersionBitmask) >> 5);
- if (version_ != Version::kV1) {
- NEARBY_LOG(INFO,
- "Cannot deserialize BleAdvertisement: unsupported Version %d",
- version_);
- return;
- }
- // The lower 5 bits are supposed to be the Pcp.
- pcp_ = static_cast<Pcp>(version_and_pcp_byte & kPcpBitmask);
- switch (pcp_) {
- case Pcp::kP2pCluster: // Fall through
- case Pcp::kP2pStar: // Fall through
- case Pcp::kP2pPointToPoint:
- break;
- default:
- NEARBY_LOG(INFO,
- "Cannot deserialize BleAdvertisement: uunsupported V1 PCP %d",
- pcp_);
- }
-
- // The next 3 bytes are supposed to be the service_id_hash if not fast
- // advertisment.
- if (!fast_advertisement_)
- service_id_hash_ = base_input_stream.ReadBytes(kServiceIdHashLength);
-
- // The next 4 bytes are supposed to be the endpoint_id.
- endpoint_id_ = std::string{base_input_stream.ReadBytes(kEndpointIdLength)};
-
- // The next 1 byte is supposed to be the length of the endpoint_info.
- std::uint32_t expected_endpoint_info_length = base_input_stream.ReadUint8();
-
- // The next x bytes are the endpoint info. (Max length is 131 bytes or 17
- // bytes as fast_advertisement being true).
- endpoint_info_ = base_input_stream.ReadBytes(expected_endpoint_info_length);
- const int max_endpoint_info_length =
- fast_advertisement_ ? kMaxFastEndpointInfoLength : kMaxEndpointInfoLength;
- if (endpoint_info_.Empty() ||
- endpoint_info_.size() != expected_endpoint_info_length ||
- endpoint_info_.size() > max_endpoint_info_length) {
- NEARBY_LOG(INFO,
- "Cannot deserialize BleAdvertisement(fast advertisement=%d): "
- "expected endpointInfo to be %d bytes, got %" PRIu64,
- fast_advertisement_, expected_endpoint_info_length,
- endpoint_info_.size());
-
- // Clear enpoint_id for validity.
- endpoint_id_.clear();
- return;
- }
-
- // The next 6 bytes are the bluetooth mac address if not fast advertisment.
- if (!fast_advertisement_) {
- auto bluetooth_mac_address_bytes =
- base_input_stream.ReadBytes(BluetoothUtils::kBluetoothMacAddressLength);
- bluetooth_mac_address_ =
- BluetoothUtils::ToString(bluetooth_mac_address_bytes);
- }
-
- // The next 1 byte is supposed to be the length of the uwb_address. If the
- // next byte is not available then it should be a fast advertisement and skip
- // it for remaining bytes.
- if (base_input_stream.IsAvailable(1)) {
- std::uint32_t expected_uwb_address_length = base_input_stream.ReadUint8();
- // If the length of uwb_address is not zero, then retrieve it.
- if (expected_uwb_address_length != 0) {
- uwb_address_ = base_input_stream.ReadBytes(expected_uwb_address_length);
- if (uwb_address_.Empty() ||
- uwb_address_.size() != expected_uwb_address_length) {
- NEARBY_LOG(INFO,
- "Cannot deserialize BleAdvertisement: "
- "expected uwbAddress size to be %d bytes, got %" PRIu64,
- expected_uwb_address_length, uwb_address_.size());
-
- // Clear enpoint_id for validity.
- endpoint_id_.clear();
- return;
- }
- }
-
- // The next 1 byte is extra field.
- if (!fast_advertisement_) {
- if (base_input_stream.IsAvailable(kExtraFieldLength)) {
- auto extra_field = static_cast<char>(base_input_stream.ReadUint8());
- web_rtc_state_ = (extra_field & kWebRtcConnectableFlagBitmask) == 1
- ? WebRtcState::kConnectable
- : WebRtcState::kUnconnectable;
- }
- }
- }
-
- base_input_stream.Close();
-}
-
-BleAdvertisement::operator ByteArray() const {
- if (!IsValid()) {
- return ByteArray();
- }
-
- // The first 3 bits are the Version.
- char version_and_pcp_byte =
- (static_cast<char>(version_) << 5) & kVersionBitmask;
- // The next 5 bits are the Pcp.
- version_and_pcp_byte |= static_cast<char>(pcp_) & kPcpBitmask;
-
- std::string out;
- if (fast_advertisement_) {
- // clang-format off
- out = absl::StrCat(std::string(1, version_and_pcp_byte),
- endpoint_id_,
- std::string(1, endpoint_info_.size()),
- std::string(endpoint_info_));
- // clang-format on
- } else {
- // clang-format off
- out = absl::StrCat(std::string(1, version_and_pcp_byte),
- std::string(service_id_hash_),
- endpoint_id_,
- std::string(1, endpoint_info_.size()),
- std::string(endpoint_info_));
- // clang-format on
-
- // The next 6 bytes are the bluetooth mac address. If bluetooth_mac_address
- // is invalid or empty, we get back an empty byte array.
- auto bluetooth_mac_address_bytes{
- BluetoothUtils::FromString(bluetooth_mac_address_)};
- if (!bluetooth_mac_address_bytes.Empty()) {
- absl::StrAppend(&out, std::string(bluetooth_mac_address_bytes));
- } else {
- // If bluetooth MAC address is invalid, then reserve the bytes.
- auto fake_bt_mac_address_bytes =
- ByteArray(BluetoothUtils::kBluetoothMacAddressLength);
- absl::StrAppend(&out, std::string(fake_bt_mac_address_bytes));
- }
- }
-
- // The next bytes are UWB address field.
- if (!uwb_address_.Empty()) {
- absl::StrAppend(&out, std::string(1, uwb_address_.size()));
- absl::StrAppend(&out, std::string(uwb_address_));
- } else if (!fast_advertisement_) {
- // Write UWB address with length 0 to be able to read the next field when
- // decode.
- absl::StrAppend(&out, std::string(1, uwb_address_.size()));
- }
-
- // The next 1 byte is extra field.
- if (!fast_advertisement_) {
- int web_rtc_connectable_flag =
- (web_rtc_state_ == WebRtcState::kConnectable) ? 1 : 0;
- char extra_field_byte = static_cast<char>(web_rtc_connectable_flag) &
- kWebRtcConnectableFlagBitmask;
- absl::StrAppend(&out, std::string(1, extra_field_byte));
- }
-
- return ByteArray(std::move(out));
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/ble_advertisement.h b/chromium/third_party/nearby/src/cpp/core/internal/ble_advertisement.h
deleted file mode 100644
index a47bbbd8bd2..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/ble_advertisement.h
+++ /dev/null
@@ -1,126 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_BLE_ADVERTISEMENT_H_
-#define CORE_INTERNAL_BLE_ADVERTISEMENT_H_
-
-#include "core/internal/base_pcp_handler.h"
-#include "core/internal/pcp.h"
-#include "platform/base/bluetooth_utils.h"
-#include "platform/base/byte_array.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Represents the format of the Connections Ble Advertisement used in
-// Advertising + Discovery.
-//
-// <p>[VERSION][PCP][SERVICE_ID_HASH][ENDPOINT_ID][ENDPOINT_INFO_SIZE]
-// [ENDPOINT_INFO][BLUETOOTH_MAC][UWB_ADDRESS_SIZE][UWB_ADDRESS][EXTRA_FIELD]
-//
-// <p>The fast version of this advertisement simply omits SERVICE_ID_HASH and
-// the Bluetooth MAC address.
-//
-// <p>See go/connections-ble-advertisement for more information.
-class BleAdvertisement {
- public:
- // Versions of the BleAdvertisement.
- enum class Version {
- kUndefined = 0,
- kV1 = 1,
- // Version is only allocated 3 bits in the BleAdvertisement, so this
- // can never go beyond V7.
- };
-
- static constexpr int kVersionAndPcpLength = 1;
- static constexpr int kVersionBitmask = 0x0E0;
- static constexpr int kPcpBitmask = 0x01F;
- static constexpr int kServiceIdHashLength = 3;
- static constexpr int kEndpointIdLength = 4;
- static constexpr int kEndpointInfoSizeLength = 1;
- static constexpr int kBluetoothMacAddressLength =
- BluetoothUtils::kBluetoothMacAddressLength;
- static constexpr int kUwbAddressSizeLength = 1;
- static constexpr int kExtraFieldLength = 1;
- static constexpr int kEndpointInfoLengthBitmask = 0x0FF;
- static constexpr int kWebRtcConnectableFlagBitmask = 0x01;
- static constexpr int kMinAdvertisementLength =
- kVersionAndPcpLength + kServiceIdHashLength + kEndpointIdLength +
- kEndpointInfoSizeLength + kBluetoothMacAddressLength;
-
- // The difference between normal and fast advertisements is that the fast one
- // omits the SERVICE_ID_HASH and Bluetooth MAC address. This is done to save
- // space.
- static constexpr int kMinFastAdvertisementLength = kMinAdvertisementLength -
- kServiceIdHashLength -
- kBluetoothMacAddressLength;
- static constexpr int kMaxEndpointInfoLength = 131;
- static constexpr int kMaxFastEndpointInfoLength = 17;
-
- BleAdvertisement() = default;
- BleAdvertisement(Version version, Pcp pcp, const std::string& endpoint_id,
- const ByteArray& endpoint_info,
- const ByteArray& uwb_address);
- BleAdvertisement(Version version, Pcp pcp, const ByteArray& service_id_hash,
- const std::string& endpoint_id,
- const ByteArray& endpoint_info,
- const std::string& bluetooth_mac_address,
- const ByteArray& uwb_address, WebRtcState web_rtc_state);
- BleAdvertisement(bool fast_advertisement,
- const ByteArray& ble_advertisement_bytes);
- BleAdvertisement(const BleAdvertisement&) = default;
- BleAdvertisement& operator=(const BleAdvertisement&) = default;
- BleAdvertisement(BleAdvertisement&&) = default;
- BleAdvertisement& operator=(BleAdvertisement&&) = default;
- ~BleAdvertisement() = default;
-
- explicit operator ByteArray() const;
-
- bool IsValid() const { return !endpoint_id_.empty(); }
- bool IsFastAdvertisement() const { return fast_advertisement_; }
- Version GetVersion() const { return version_; }
- Pcp GetPcp() const { return pcp_; }
- ByteArray GetServiceIdHash() const { return service_id_hash_; }
- std::string GetEndpointId() const { return endpoint_id_; }
- ByteArray GetEndpointInfo() const { return endpoint_info_; }
- std::string GetBluetoothMacAddress() const { return bluetooth_mac_address_; }
- ByteArray GetUwbAddress() const { return uwb_address_; }
- WebRtcState GetWebRtcState() const { return web_rtc_state_; }
-
- private:
- void DoInitialize(bool fast_advertisement, Version version, Pcp pcp,
- const ByteArray& service_id_hash,
- const std::string& endpoint_id,
- const ByteArray& endpoint_info,
- const std::string& bluetooth_mac_address,
- const ByteArray& uwb_address, WebRtcState web_rtc_state);
-
- bool fast_advertisement_ = false;
- Version version_{Version::kUndefined};
- Pcp pcp_{Pcp::kUnknown};
- ByteArray service_id_hash_;
- std::string endpoint_id_;
- ByteArray endpoint_info_;
- std::string bluetooth_mac_address_;
- // TODO(b/169550050): Define UWB address field.
- ByteArray uwb_address_;
- WebRtcState web_rtc_state_{WebRtcState::kUndefined};
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_BLE_ADVERTISEMENT_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/ble_advertisement_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/ble_advertisement_test.cc
deleted file mode 100644
index 61871d536f9..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/ble_advertisement_test.cc
+++ /dev/null
@@ -1,436 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/ble_advertisement.h"
-
-#include "gtest/gtest.h"
-#include "core/internal/base_pcp_handler.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-
-constexpr BleAdvertisement::Version kVersion = BleAdvertisement::Version::kV1;
-constexpr Pcp kPcp = Pcp::kP2pCluster;
-constexpr absl::string_view kServiceIdHashBytes{"\x0a\x0b\x0c"};
-constexpr absl::string_view kEndpointId{"AB12"};
-constexpr absl::string_view kEndpointName{
- "How much wood can a woodchuck chuck if a wood chuck would chuck wood?"};
-constexpr absl::string_view kFastAdvertisementEndpointName{"Fast Advertise"};
-constexpr absl::string_view kBluetoothMacAddress{"00:00:E6:88:64:13"};
-constexpr WebRtcState kWebRtcState = WebRtcState::kConnectable;
-
-// TODO(b/169550050): Implement UWBAddress.
-TEST(BleAdvertisementTest, ConstructionWorks) {
- ByteArray service_id_hash{std::string(kServiceIdHashBytes)};
- ByteArray endpoint_info{std::string(kEndpointName)};
- BleAdvertisement ble_advertisement{
- kVersion, kPcp,
- service_id_hash, std::string(kEndpointId),
- endpoint_info, std::string(kBluetoothMacAddress),
- ByteArray{}, kWebRtcState};
-
- EXPECT_TRUE(ble_advertisement.IsValid());
- EXPECT_FALSE(ble_advertisement.IsFastAdvertisement());
- EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
- EXPECT_EQ(kPcp, ble_advertisement.GetPcp());
- EXPECT_EQ(service_id_hash, ble_advertisement.GetServiceIdHash());
- EXPECT_EQ(kEndpointId, ble_advertisement.GetEndpointId());
- EXPECT_EQ(endpoint_info, ble_advertisement.GetEndpointInfo());
- EXPECT_EQ(kBluetoothMacAddress, ble_advertisement.GetBluetoothMacAddress());
- EXPECT_EQ(kWebRtcState, ble_advertisement.GetWebRtcState());
-}
-
-TEST(BleAdvertisementTest, ConstructionWorksForFastAdvertisement) {
- ByteArray fast_endpoint_info{std::string(kFastAdvertisementEndpointName)};
- BleAdvertisement ble_advertisement{kVersion, kPcp, std::string(kEndpointId),
- fast_endpoint_info, ByteArray{}};
-
- EXPECT_TRUE(ble_advertisement.IsValid());
- EXPECT_TRUE(ble_advertisement.IsFastAdvertisement());
- EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
- EXPECT_EQ(kPcp, ble_advertisement.GetPcp());
- EXPECT_EQ(kEndpointId, ble_advertisement.GetEndpointId());
- EXPECT_EQ(fast_endpoint_info, ble_advertisement.GetEndpointInfo());
- EXPECT_EQ(WebRtcState::kUndefined, ble_advertisement.GetWebRtcState());
-}
-
-TEST(BleAdvertisementTest, ConstructionWorksWithEmptyEndpointInfo) {
- ByteArray empty_endpoint_info;
-
- ByteArray service_id_hash{std::string(kServiceIdHashBytes)};
- BleAdvertisement ble_advertisement{kVersion,
- kPcp,
- service_id_hash,
- std::string(kEndpointId),
- empty_endpoint_info,
- std::string(kBluetoothMacAddress),
- ByteArray{},
- kWebRtcState};
-
- EXPECT_TRUE(ble_advertisement.IsValid());
- EXPECT_FALSE(ble_advertisement.IsFastAdvertisement());
- EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
- EXPECT_EQ(kPcp, ble_advertisement.GetPcp());
- EXPECT_EQ(service_id_hash, ble_advertisement.GetServiceIdHash());
- EXPECT_EQ(kEndpointId, ble_advertisement.GetEndpointId());
- EXPECT_EQ(empty_endpoint_info, ble_advertisement.GetEndpointInfo());
- EXPECT_EQ(kBluetoothMacAddress, ble_advertisement.GetBluetoothMacAddress());
- EXPECT_EQ(kWebRtcState, ble_advertisement.GetWebRtcState());
-}
-
-TEST(BleAdvertisementTest,
- ConstructionWorksWithEmptyEndpointInfoForFastAdvertisement) {
- ByteArray empty_endpoint_info;
-
- BleAdvertisement ble_advertisement{kVersion, kPcp, std::string(kEndpointId),
- empty_endpoint_info, ByteArray{}};
-
- EXPECT_TRUE(ble_advertisement.IsValid());
- EXPECT_TRUE(ble_advertisement.IsFastAdvertisement());
- EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
- EXPECT_EQ(kPcp, ble_advertisement.GetPcp());
- EXPECT_EQ(kEndpointId, ble_advertisement.GetEndpointId());
- EXPECT_EQ(empty_endpoint_info, ble_advertisement.GetEndpointInfo());
- EXPECT_EQ(WebRtcState::kUndefined, ble_advertisement.GetWebRtcState());
-}
-
-TEST(BleAdvertisementTest, ConstructionWorksWithEmojiEndpointInfo) {
- ByteArray emoji_endpoint_info{std::string("\u0001F450 \u0001F450")};
-
- ByteArray service_id_hash{std::string(kServiceIdHashBytes)};
- BleAdvertisement ble_advertisement{kVersion,
- kPcp,
- service_id_hash,
- std::string(kEndpointId),
- emoji_endpoint_info,
- std::string(kBluetoothMacAddress),
- ByteArray{},
- kWebRtcState};
-
- EXPECT_TRUE(ble_advertisement.IsValid());
- EXPECT_FALSE(ble_advertisement.IsFastAdvertisement());
- EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
- EXPECT_EQ(kPcp, ble_advertisement.GetPcp());
- EXPECT_EQ(service_id_hash, ble_advertisement.GetServiceIdHash());
- EXPECT_EQ(kEndpointId, ble_advertisement.GetEndpointId());
- EXPECT_EQ(emoji_endpoint_info, ble_advertisement.GetEndpointInfo());
- EXPECT_EQ(kBluetoothMacAddress, ble_advertisement.GetBluetoothMacAddress());
- EXPECT_EQ(kWebRtcState, ble_advertisement.GetWebRtcState());
-}
-
-TEST(BleAdvertisementTest,
- ConstructionWorksWithEmojiEndpointInfoForFastAdvertisement) {
- ByteArray emoji_endpoint_info{std::string("\u0001F450 \u0001F450")};
-
- BleAdvertisement ble_advertisement{kVersion, kPcp, std::string(kEndpointId),
- emoji_endpoint_info, ByteArray{}};
-
- EXPECT_TRUE(ble_advertisement.IsValid());
- EXPECT_TRUE(ble_advertisement.IsFastAdvertisement());
- EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
- EXPECT_EQ(kPcp, ble_advertisement.GetPcp());
- EXPECT_EQ(kEndpointId, ble_advertisement.GetEndpointId());
- EXPECT_EQ(emoji_endpoint_info, ble_advertisement.GetEndpointInfo());
- EXPECT_EQ(WebRtcState::kUndefined, ble_advertisement.GetWebRtcState());
-}
-
-TEST(BleAdvertisementTest, ConstructionFailsWithLongEndpointInfo) {
- std::string long_endpoint_name(BleAdvertisement::kMaxEndpointInfoLength + 1,
- 'x');
- ByteArray long_endpoint_info{long_endpoint_name};
-
- ByteArray service_id_hash{std::string(kServiceIdHashBytes)};
- BleAdvertisement ble_advertisement{
- kVersion, kPcp,
- service_id_hash, std::string(kEndpointId),
- long_endpoint_info, std::string(kBluetoothMacAddress),
- ByteArray{}, kWebRtcState};
-
- EXPECT_FALSE(ble_advertisement.IsValid());
-}
-
-TEST(BleAdvertisementTest,
- ConstructionFailsWithLongEndpointInfoForFastAdvertisement) {
- std::string long_endpoint_name(
- BleAdvertisement::kMaxFastEndpointInfoLength + 1, 'x');
- ByteArray long_endpoint_info{long_endpoint_name};
-
- BleAdvertisement ble_advertisement{kVersion, kPcp, std::string(kEndpointId),
- long_endpoint_info, ByteArray{}};
-
- EXPECT_FALSE(ble_advertisement.IsValid());
-}
-
-TEST(BleAdvertisementTest, ConstructionFailsWithBadVersion) {
- auto bad_version = static_cast<BleAdvertisement::Version>(666);
-
- ByteArray service_id_hash{std::string(kServiceIdHashBytes)};
- ByteArray endpoint_info{std::string(kEndpointName)};
- BleAdvertisement ble_advertisement{
- bad_version, kPcp,
- service_id_hash, std::string(kEndpointId),
- endpoint_info, std::string(kBluetoothMacAddress),
- ByteArray{}, kWebRtcState};
-
- EXPECT_FALSE(ble_advertisement.IsValid());
-}
-
-TEST(BleAdvertisementTest,
- ConstructionFailsWithBadVersionForFastAdvertisement) {
- auto bad_version = static_cast<BleAdvertisement::Version>(666);
-
- ByteArray fast_endpoint_info{std::string(kFastAdvertisementEndpointName)};
- BleAdvertisement ble_advertisement{bad_version, kPcp,
- std::string(kEndpointId),
- fast_endpoint_info, ByteArray{}};
-
- EXPECT_FALSE(ble_advertisement.IsValid());
-}
-
-TEST(BleAdvertisementTest, ConstructionFailsWithBadPCP) {
- auto bad_pcp = static_cast<Pcp>(666);
-
- ByteArray service_id_hash{std::string(kServiceIdHashBytes)};
- ByteArray endpoint_info{std::string(kEndpointName)};
- BleAdvertisement ble_advertisement{
- kVersion, bad_pcp,
- service_id_hash, std::string(kEndpointId),
- endpoint_info, std::string(kBluetoothMacAddress),
- ByteArray{}, kWebRtcState};
-
- EXPECT_FALSE(ble_advertisement.IsValid());
-}
-
-TEST(BleAdvertisementTest, ConstructionFailsWithBadPCPForFastAdvertisement) {
- auto bad_pcp = static_cast<Pcp>(666);
-
- ByteArray fast_endpoint_info{std::string(kFastAdvertisementEndpointName)};
- BleAdvertisement ble_advertisement{kVersion, bad_pcp,
- std::string(kEndpointId),
- fast_endpoint_info, ByteArray{}};
-
- EXPECT_FALSE(ble_advertisement.IsValid());
-}
-
-TEST(BleAdvertisementTest, ConstructionSucceedsWithEmptyBluetoothMacAddress) {
- std::string empty_bluetooth_mac_address = "";
-
- ByteArray service_id_hash{std::string(kServiceIdHashBytes)};
- ByteArray endpoint_info{std::string(kEndpointName)};
- BleAdvertisement ble_advertisement{
- kVersion, kPcp,
- service_id_hash, std::string(kEndpointId),
- endpoint_info, empty_bluetooth_mac_address,
- ByteArray{}, kWebRtcState};
-
- EXPECT_TRUE(ble_advertisement.IsValid());
-}
-
-TEST(BleAdvertisementTest, ConstructionSucceedsWithInvalidBluetoothMacAddress) {
- std::string bad_bluetooth_mac_address = "022:00";
-
- ByteArray service_id_hash{std::string(kServiceIdHashBytes)};
- ByteArray endpoint_info{std::string(kEndpointName)};
- BleAdvertisement ble_advertisement{kVersion, kPcp,
- service_id_hash, std::string(kEndpointId),
- endpoint_info, bad_bluetooth_mac_address,
- ByteArray{}, kWebRtcState};
-
- EXPECT_TRUE(ble_advertisement.IsValid());
- EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
- EXPECT_EQ(kPcp, ble_advertisement.GetPcp());
- EXPECT_EQ(service_id_hash, ble_advertisement.GetServiceIdHash());
- EXPECT_EQ(kEndpointId, ble_advertisement.GetEndpointId());
- EXPECT_EQ(endpoint_info, ble_advertisement.GetEndpointInfo());
- EXPECT_TRUE(ble_advertisement.GetBluetoothMacAddress().empty());
- EXPECT_EQ(kWebRtcState, ble_advertisement.GetWebRtcState());
-}
-
-TEST(BleAdvertisementTest, ConstructionFromBytesWorks) {
- // Serialize good data into a good Ble Advertisement.
- ByteArray service_id_hash{std::string(kServiceIdHashBytes)};
- ByteArray endpoint_info{std::string(kEndpointName)};
- BleAdvertisement org_ble_advertisement{
- kVersion, kPcp,
- service_id_hash, std::string(kEndpointId),
- endpoint_info, std::string(kBluetoothMacAddress),
- ByteArray{}, kWebRtcState};
- ByteArray ble_advertisement_bytes(org_ble_advertisement);
-
- BleAdvertisement ble_advertisement{false, ble_advertisement_bytes};
-
- EXPECT_TRUE(ble_advertisement.IsValid());
- EXPECT_FALSE(ble_advertisement.IsFastAdvertisement());
- EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
- EXPECT_EQ(kPcp, ble_advertisement.GetPcp());
- EXPECT_EQ(service_id_hash, ble_advertisement.GetServiceIdHash());
- EXPECT_EQ(kEndpointId, ble_advertisement.GetEndpointId());
- EXPECT_EQ(endpoint_info, ble_advertisement.GetEndpointInfo());
- EXPECT_EQ(kBluetoothMacAddress, ble_advertisement.GetBluetoothMacAddress());
- EXPECT_EQ(kWebRtcState, ble_advertisement.GetWebRtcState());
-}
-
-TEST(BleAdvertisementTest, ConstructionFromBytesWorksForFastAdvertisement) {
- // Serialize good data into a good Ble Advertisement.
- ByteArray fast_endpoint_info{std::string(kFastAdvertisementEndpointName)};
- BleAdvertisement org_ble_advertisement{kVersion, kPcp,
- std::string(kEndpointId),
- fast_endpoint_info, ByteArray{}};
- ByteArray ble_advertisement_bytes(org_ble_advertisement);
-
- BleAdvertisement ble_advertisement{true, ble_advertisement_bytes};
-
- EXPECT_TRUE(ble_advertisement.IsValid());
- EXPECT_TRUE(ble_advertisement.IsFastAdvertisement());
- EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
- EXPECT_EQ(kPcp, ble_advertisement.GetPcp());
- EXPECT_EQ(kEndpointId, ble_advertisement.GetEndpointId());
- EXPECT_EQ(fast_endpoint_info, ble_advertisement.GetEndpointInfo());
- EXPECT_EQ(WebRtcState::kUndefined, ble_advertisement.GetWebRtcState());
-}
-
-// Bytes at the end should be ignored so that they can be used as reserve bytes
-// in the future.
-TEST(BleAdvertisementTest, ConstructionFromLongLengthBytesWorks) {
- // Serialize good data into a good Ble Advertisement.
- ByteArray service_id_hash{std::string(kServiceIdHashBytes)};
- ByteArray endpoint_info{std::string(kEndpointName)};
- BleAdvertisement ble_advertisement{
- kVersion, kPcp,
- service_id_hash, std::string(kEndpointId),
- endpoint_info, std::string(kBluetoothMacAddress),
- ByteArray{}, kWebRtcState};
- ByteArray ble_advertisement_bytes(ble_advertisement);
-
- // Add bytes to the end of the valid Ble advertisement.
- ByteArray long_ble_advertisement_bytes(
- BleAdvertisement::kMinAdvertisementLength + 1000);
- ASSERT_LE(ble_advertisement_bytes.size(),
- long_ble_advertisement_bytes.size());
- memcpy(long_ble_advertisement_bytes.data(), ble_advertisement_bytes.data(),
- ble_advertisement_bytes.size());
-
- BleAdvertisement long_ble_advertisement{false, long_ble_advertisement_bytes};
-
- EXPECT_TRUE(long_ble_advertisement.IsValid());
- EXPECT_EQ(kVersion, long_ble_advertisement.GetVersion());
- EXPECT_EQ(kPcp, long_ble_advertisement.GetPcp());
- EXPECT_EQ(service_id_hash, long_ble_advertisement.GetServiceIdHash());
- EXPECT_EQ(kEndpointId, long_ble_advertisement.GetEndpointId());
- EXPECT_EQ(endpoint_info, long_ble_advertisement.GetEndpointInfo());
- EXPECT_EQ(kBluetoothMacAddress,
- long_ble_advertisement.GetBluetoothMacAddress());
- EXPECT_EQ(kWebRtcState, ble_advertisement.GetWebRtcState());
-}
-
-TEST(BleAdvertisementTest, ConstructionFromNullBytesFails) {
- BleAdvertisement ble_advertisement{false, ByteArray{}};
-
- EXPECT_FALSE(ble_advertisement.IsValid());
-}
-
-TEST(BleAdvertisementTest, ConstructionFromNullBytesFailsForFastAdvertisement) {
- BleAdvertisement ble_advertisement{true, ByteArray{}};
-
- EXPECT_FALSE(ble_advertisement.IsValid());
-}
-
-TEST(BleAdvertisementTest, ConstructionFromShortLengthBytesFails) {
- // Serialize good data into a good Ble Advertisement.
- ByteArray service_id_hash{std::string(kServiceIdHashBytes)};
- ByteArray endpoint_info{std::string(kEndpointName)};
- BleAdvertisement ble_advertisement{
- kVersion, kPcp,
- service_id_hash, std::string(kEndpointId),
- endpoint_info, std::string(kBluetoothMacAddress),
- ByteArray{}, kWebRtcState};
- ByteArray ble_advertisement_bytes(ble_advertisement);
-
- // Shorten the valid Ble Advertisement.
- ByteArray short_ble_advertisement_bytes{
- ble_advertisement_bytes.data(),
- BleAdvertisement::kMinAdvertisementLength - 1};
-
- BleAdvertisement short_ble_advertisement{false,
- short_ble_advertisement_bytes};
-
- EXPECT_FALSE(short_ble_advertisement.IsValid());
-}
-
-TEST(BleAdvertisementTest,
- ConstructionFromShortLengthBytesFailsForFastAdvertisement) {
- // Serialize good data into a good Ble Advertisement.
- ByteArray fast_endpoint_info{std::string(kFastAdvertisementEndpointName)};
- BleAdvertisement ble_advertisement{kVersion, kPcp, std::string(kEndpointId),
- fast_endpoint_info, ByteArray{}};
- ByteArray ble_advertisement_bytes(ble_advertisement);
-
- // Shorten the valid Ble Advertisement.
- ByteArray short_ble_advertisement_bytes{
- ble_advertisement_bytes.data(),
- BleAdvertisement::kMinAdvertisementLength - 1};
-
- BleAdvertisement short_ble_advertisement{true, short_ble_advertisement_bytes};
-
- EXPECT_FALSE(short_ble_advertisement.IsValid());
-}
-
-TEST(BleAdvertisementTest,
- ConstructionFromByesWithWrongEndpointInfoLengthFails) {
- // Serialize good data into a good Ble Advertisement.
- ByteArray service_id_hash{std::string(kServiceIdHashBytes)};
- ByteArray endpoint_info{std::string(kEndpointName)};
- BleAdvertisement ble_advertisement{
- kVersion, kPcp,
- service_id_hash, std::string(kEndpointId),
- endpoint_info, std::string(kBluetoothMacAddress),
- ByteArray{}, kWebRtcState};
- ByteArray ble_advertisement_bytes(ble_advertisement);
-
- // Corrupt the EndpointNameLength bits.
- std::string corrupt_ble_advertisement_string(ble_advertisement_bytes);
- corrupt_ble_advertisement_string[8] ^= 0x0FF;
- ByteArray corrupt_ble_advertisement_bytes(corrupt_ble_advertisement_string);
-
- BleAdvertisement corrupt_ble_advertisement{false,
- corrupt_ble_advertisement_bytes};
-
- EXPECT_FALSE(corrupt_ble_advertisement.IsValid());
-}
-
-TEST(BleAdvertisementTest,
- ConstructionFromByesWithWrongEndpointInfoLengthFailsForFastAdvertisement) {
- // Serialize good data into a good Ble Advertisement.
- ByteArray fast_endpoint_info{std::string(kFastAdvertisementEndpointName)};
- BleAdvertisement ble_advertisement{kVersion, kPcp, std::string(kEndpointId),
- fast_endpoint_info, ByteArray{}};
- ByteArray ble_advertisement_bytes = ByteArray(ble_advertisement);
-
- // Corrupt the EndpointInfoLength bits.
- std::string corrupt_ble_advertisement_string(ble_advertisement_bytes);
- corrupt_ble_advertisement_string[5] ^= 0x0FF;
- ByteArray corrupt_ble_advertisement_bytes(corrupt_ble_advertisement_string);
-
- BleAdvertisement corrupt_ble_advertisement{true,
- corrupt_ble_advertisement_bytes};
-
- EXPECT_FALSE(corrupt_ble_advertisement.IsValid());
-}
-
-} // namespace
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/ble_endpoint_channel.cc b/chromium/third_party/nearby/src/cpp/core/internal/ble_endpoint_channel.cc
deleted file mode 100644
index 5cf3bc2bef0..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/ble_endpoint_channel.cc
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/ble_endpoint_channel.h"
-
-#include <string>
-
-#include "platform/public/ble.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-namespace {
-
-OutputStream* GetOutputStreamOrNull(BleSocket& socket) {
- if (socket.GetRemotePeripheral().IsValid()) return &socket.GetOutputStream();
- return nullptr;
-}
-
-InputStream* GetInputStreamOrNull(BleSocket& socket) {
- if (socket.GetRemotePeripheral().IsValid()) return &socket.GetInputStream();
- return nullptr;
-}
-
-} // namespace
-
-BleEndpointChannel::BleEndpointChannel(const std::string& channel_name,
- BleSocket socket)
- : BaseEndpointChannel(channel_name, GetInputStreamOrNull(socket),
- GetOutputStreamOrNull(socket)),
- ble_socket_(std::move(socket)) {}
-
-proto::connections::Medium BleEndpointChannel::GetMedium() const {
- return proto::connections::Medium::BLE;
-}
-
-int BleEndpointChannel::GetMaxTransmitPacketSize() const {
- return kDefaultBleMaxTransmitPacketSize;
-}
-
-void BleEndpointChannel::CloseImpl() {
- auto status = ble_socket_.Close();
- if (!status.Ok()) {
- NEARBY_LOGS(INFO)
- << "Failed to close underlying socket for BleEndpointChannel "
- << GetName() << ": exception=" << status.value;
- }
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/ble_endpoint_channel.h b/chromium/third_party/nearby/src/cpp/core/internal/ble_endpoint_channel.h
deleted file mode 100644
index 18c6954e4d9..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/ble_endpoint_channel.h
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_BLE_ENDPOINT_CHANNEL_H_
-#define CORE_INTERNAL_BLE_ENDPOINT_CHANNEL_H_
-
-#include "core/internal/base_endpoint_channel.h"
-#include "platform/public/ble.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-class BleEndpointChannel final : public BaseEndpointChannel {
- public:
- // Creates both outgoing and incoming Ble channels.
- BleEndpointChannel(const std::string& channel_name, BleSocket socket);
-
- proto::connections::Medium GetMedium() const override;
-
- int GetMaxTransmitPacketSize() const override;
-
- private:
- static constexpr int kDefaultBleMaxTransmitPacketSize = 512; // 512 bytes
-
- void CloseImpl() override;
-
- BleSocket ble_socket_;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_BLE_ENDPOINT_CHANNEL_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/bluetooth_bwu_handler.cc b/chromium/third_party/nearby/src/cpp/core/internal/bluetooth_bwu_handler.cc
deleted file mode 100644
index 24186c2dcfd..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/bluetooth_bwu_handler.cc
+++ /dev/null
@@ -1,165 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/bluetooth_bwu_handler.h"
-
-#include "absl/functional/bind_front.h"
-#include "core/internal/bluetooth_endpoint_channel.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/offline_frames.h"
-
-// Manages the Bluetooth-specific methods needed to upgrade an {@link
-// EndpointChannel}.
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-BluetoothBwuHandler::BluetoothBwuHandler(
- Mediums& mediums, EndpointChannelManager& channel_manager,
- BwuNotifications notifications)
- : BaseBwuHandler(channel_manager, std::move(notifications)),
- mediums_(mediums) {}
-
-void BluetoothBwuHandler::Revert() {
- for (const std::string& service_id : active_service_ids_) {
- bluetooth_medium_.StopAcceptingConnections(service_id);
- }
- active_service_ids_.clear();
- NEARBY_LOG(INFO,
- "BluetoothBwuHandler successfully reverted all Bluetooth state.");
-}
-
-// Accept Connection Callback.
-// Notifies that the remote party called BluetoothClassic::Connect()
-// for this socket.
-void BluetoothBwuHandler::OnIncomingBluetoothConnection(
- ClientProxy* client, const std::string& service_id,
- BluetoothSocket socket) {
- auto channel =
- absl::make_unique<BluetoothEndpointChannel>(service_id, socket);
- std::unique_ptr<IncomingSocketConnection> connection{
- new IncomingSocketConnection{
- .socket =
- std::make_unique<BluetoothIncomingSocket>(service_id, socket),
- .channel = std::move(channel),
- }};
- bwu_notifications_.incoming_connection_cb(client, std::move(connection));
-}
-
-// Called by BWU initiator. BT Medium is set up, and BWU request is prepared,
-// with necessary info (service_id, MAC address) for remote party to perform
-// discovery.
-ByteArray BluetoothBwuHandler::InitializeUpgradedMediumForEndpoint(
- ClientProxy* client, const std::string& service_id,
- const std::string& endpoint_id) {
- std::string upgrade_service_id = Utils::WrapUpgradeServiceId(service_id);
-
- std::string mac_address = bluetooth_medium_.GetMacAddress();
- if (mac_address.empty()) {
- return {};
- }
-
- if (!bluetooth_medium_.IsAcceptingConnections(upgrade_service_id)) {
- if (!bluetooth_medium_.StartAcceptingConnections(
- upgrade_service_id,
- {
- .accepted_cb = absl::bind_front(
- &BluetoothBwuHandler::OnIncomingBluetoothConnection, this,
- client, service_id),
- })) {
- NEARBY_LOGS(ERROR) << "BluetoothBwuHandler couldn't initiate the "
- "BLUETOOTH upgrade for endpoint "
- << endpoint_id
- << " because it failed to start listening for "
- "incoming Bluetooth connections.";
-
- return {};
- }
- NEARBY_LOGS(VERBOSE)
- << "BluetoothBwuHandler successfully started listening for incoming "
- "Bluetooth connections on serviceid="
- << upgrade_service_id << " while upgrading endpoint " << endpoint_id;
- }
- // cache service ID to revert
- active_service_ids_.emplace(upgrade_service_id);
-
- return parser::ForBwuBluetoothPathAvailable(upgrade_service_id, mac_address);
-}
-
-// Called by BWU target. Retrieves a new medium info from incoming message,
-// and establishes connection over BT using this info.
-// Returns a channel ready to exchange data or nullptr on error.
-std::unique_ptr<EndpointChannel>
-BluetoothBwuHandler::CreateUpgradedEndpointChannel(
- ClientProxy* client, const std::string& service_id,
- const std::string& endpoint_id, const UpgradePathInfo& upgrade_path_info) {
- const UpgradePathInfo::BluetoothCredentials& bluetooth_credentials =
- upgrade_path_info.bluetooth_credentials();
- if (!bluetooth_credentials.has_service_name() ||
- !bluetooth_credentials.has_mac_address()) {
- NEARBY_LOG(ERROR, "BluetoothBwuHandler failed to parse UpgradePathInfo.");
- return nullptr;
- }
-
- const std::string& service_name = bluetooth_credentials.service_name();
- const std::string& mac_address = bluetooth_credentials.mac_address();
-
- NEARBY_LOGS(VERBOSE) << "BluetoothBwuHandler is attempting to connect to "
- "available Bluetooth device "
- << service_name << ", " << mac_address
- << ") for endpoint " << endpoint_id;
-
- BluetoothDevice device = bluetooth_medium_.GetRemoteDevice(mac_address);
- if (!device.IsValid()) {
- NEARBY_LOGS(ERROR)
- << "BluetoothBwuHandler failed to derive a valid Bluetooth device "
- "from the MAC address ("
- << mac_address << ") for endpoint " << endpoint_id;
- return nullptr;
- }
-
- BluetoothSocket socket = bluetooth_medium_.Connect(
- device, service_name, client->GetCancellationFlag(endpoint_id));
- if (!socket.IsValid()) {
- NEARBY_LOGS(ERROR)
- << "BluetoothBwuHandler failed to connect to the Bluetooth device ("
- << service_name << ", " << mac_address << ") for endpoint "
- << endpoint_id;
- return nullptr;
- }
-
- NEARBY_LOGS(VERBOSE)
- << "BluetoothBwuHandler successfully connected to Bluetooth device ("
- << service_name << ", " << mac_address << ") while upgrading endpoint "
- << endpoint_id;
-
- auto channel =
- std::make_unique<BluetoothEndpointChannel>(service_name, socket);
- if (channel == nullptr) {
- NEARBY_LOGS(ERROR)
- << "BluetoothBwuHandler failed to create Bluetooth endpoint "
- "channel to the Bluetooth device ("
- << service_name << ", " << mac_address << ") for endpoint "
- << endpoint_id;
- socket.Close();
- return nullptr;
- }
-
- return channel;
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/bluetooth_bwu_handler.h b/chromium/third_party/nearby/src/cpp/core/internal/bluetooth_bwu_handler.h
deleted file mode 100644
index d39aa55df30..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/bluetooth_bwu_handler.h
+++ /dev/null
@@ -1,95 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_BLUETOOTH_BWU_HANDLER_H_
-#define CORE_INTERNAL_BLUETOOTH_BWU_HANDLER_H_
-
-#include <string>
-
-#include "core/internal/base_bwu_handler.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/mediums/mediums.h"
-#include "core/internal/mediums/utils.h"
-#include "platform/public/bluetooth_classic.h"
-#include "platform/public/count_down_latch.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Defines the set of methods that need to be implemented to handle the
-// per-Medium-specific operations needed to upgrade an EndpointChannel.
-class BluetoothBwuHandler : public BaseBwuHandler {
- public:
- BluetoothBwuHandler(Mediums& mediums, EndpointChannelManager& channel_manager,
- BwuNotifications notifications);
- ~BluetoothBwuHandler() override = default;
-
- private:
- constexpr static const int kServiceIdLength = 10;
-
- // Implements BaseBwuHandler:
- // Reverts any changes made to the device in the process of upgrading
- // endpoints.
- void Revert() override;
-
- // Cleans up in-progress upgrades after endpoint disconnection.
- void OnEndpointDisconnect(ClientProxy* client,
- const std::string& endpoint_id) override {}
-
- void OnIncomingBluetoothConnection(ClientProxy* client,
- const std::string& service_id,
- BluetoothSocket socket);
-
- class BluetoothIncomingSocket : public IncomingSocket {
- public:
- explicit BluetoothIncomingSocket(const std::string& name,
- BluetoothSocket socket)
- : name_(name), socket_(socket) {}
- ~BluetoothIncomingSocket() override = default;
- std::string ToString() override { return name_; }
- void Close() override { socket_.Close(); }
-
- private:
- std::string name_;
- BluetoothSocket socket_;
- };
-
- // First part of InitiateBwuForEndpoint implementation;
- // returns a BWU request to remote party as byte array.
- ByteArray InitializeUpgradedMediumForEndpoint(
- ClientProxy* client, const std::string& service_id,
- const std::string& endpoint_id) override;
-
- // Invoked from OnBwuNegotiationFrame.
- std::unique_ptr<EndpointChannel> CreateUpgradedEndpointChannel(
- ClientProxy* client, const std::string& service_id,
- const std::string& endpoint_id,
- const UpgradePathInfo& upgrade_path_info) override;
-
- // Returns the upgrade medium of the BwuHandler.
- // @BwuHandlerThread
- Medium GetUpgradeMedium() const override { return Medium::BLUETOOTH; }
-
- Mediums& mediums_;
- absl::flat_hash_set<std::string> active_service_ids_;
- BluetoothRadio& bluetooth_radio_{mediums_.GetBluetoothRadio()};
- BluetoothClassic& bluetooth_medium_{mediums_.GetBluetoothClassic()};
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_BLUETOOTH_BWU_HANDLER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/bluetooth_device_name.cc b/chromium/third_party/nearby/src/cpp/core/internal/bluetooth_device_name.cc
deleted file mode 100644
index 45f5a6cabd4..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/bluetooth_device_name.cc
+++ /dev/null
@@ -1,212 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/bluetooth_device_name.h"
-
-#include <inttypes.h>
-
-#include <cstring>
-#include <utility>
-
-#include "absl/strings/escaping.h"
-#include "absl/strings/str_cat.h"
-#include "platform/base/base64_utils.h"
-#include "platform/base/base_input_stream.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-BluetoothDeviceName::BluetoothDeviceName(Version version, Pcp pcp,
- absl::string_view endpoint_id,
- const ByteArray& service_id_hash,
- const ByteArray& endpoint_info,
- const ByteArray& uwb_address,
- WebRtcState web_rtc_state) {
- if (version != Version::kV1 || endpoint_id.empty() ||
- endpoint_id.length() != kEndpointIdLength ||
- service_id_hash.size() != kServiceIdHashLength) {
- return;
- }
- switch (pcp) {
- case Pcp::kP2pCluster: // Fall through
- case Pcp::kP2pStar: // Fall through
- case Pcp::kP2pPointToPoint:
- break;
- default:
- return;
- }
-
- version_ = version;
- pcp_ = pcp;
- endpoint_id_ = std::string(endpoint_id);
- service_id_hash_ = service_id_hash;
- endpoint_info_ = endpoint_info;
- uwb_address_ = uwb_address;
- web_rtc_state_ = web_rtc_state;
-}
-
-BluetoothDeviceName::BluetoothDeviceName(
- absl::string_view bluetooth_device_name_string) {
- ByteArray bluetooth_device_name_bytes =
- Base64Utils::Decode(bluetooth_device_name_string);
- if (bluetooth_device_name_bytes.Empty()) {
- return;
- }
-
- if (bluetooth_device_name_bytes.size() < kMinBluetoothDeviceNameLength) {
- NEARBY_LOG(INFO,
- "Cannot deserialize BluetoothDeviceName: expecting min %d raw "
- "bytes, got %" PRIu64,
- kMinBluetoothDeviceNameLength,
- bluetooth_device_name_bytes.size());
- return;
- }
-
- BaseInputStream base_input_stream{bluetooth_device_name_bytes};
- // The first 1 byte is supposed to be the version and pcp.
- auto version_and_pcp_byte = static_cast<char>(base_input_stream.ReadUint8());
- // The upper 3 bits are supposed to be the version.
- version_ =
- static_cast<Version>((version_and_pcp_byte & kVersionBitmask) >> 5);
- if (version_ != Version::kV1) {
- NEARBY_LOG(INFO,
- "Cannot deserialize BluetoothDeviceName: unsupported version=%d",
- version_);
- return;
- }
- // The lower 5 bits are supposed to be the Pcp.
- pcp_ = static_cast<Pcp>(version_and_pcp_byte & kPcpBitmask);
- switch (pcp_) {
- case Pcp::kP2pCluster: // Fall through
- case Pcp::kP2pStar: // Fall through
- case Pcp::kP2pPointToPoint:
- break;
- default:
- NEARBY_LOG(
- INFO, "Cannot deserialize BluetoothDeviceName: unsupported V1 PCP %d",
- pcp_);
- return;
- }
-
- // The next 4 bytes are supposed to be the endpoint_id.
- endpoint_id_ = std::string{base_input_stream.ReadBytes(kEndpointIdLength)};
-
- // The next 3 bytes are supposed to be the service_id_hash.
- service_id_hash_ = base_input_stream.ReadBytes(kServiceIdHashLength);
-
- // The next 1 byte is field containning WebRtc state.
- auto field_byte = static_cast<char>(base_input_stream.ReadUint8());
- web_rtc_state_ = (field_byte & kWebRtcConnectableFlagBitmask) == 1
- ? WebRtcState::kConnectable
- : WebRtcState::kUnconnectable;
-
- // The next 6 bytes are supposed to be reserved, and can be left
- // untouched.
- base_input_stream.ReadBytes(kReservedLength);
-
- // The next 1 byte is supposed to be the length of the endpoint_info.
- std::uint32_t expected_endpoint_info_length = base_input_stream.ReadUint8();
-
- // The rest bytes are supposed to be the endpoint_info
- endpoint_info_ = base_input_stream.ReadBytes(expected_endpoint_info_length);
- if (endpoint_info_.Empty() ||
- endpoint_info_.size() != expected_endpoint_info_length) {
- NEARBY_LOG(INFO,
- "Cannot deserialize BluetoothDeviceName: expected "
- "endpoint info to be %d bytes, got %" PRIu64,
- expected_endpoint_info_length, endpoint_info_.size());
-
- // Clear enpoint_id for validadity.
- endpoint_id_.clear();
- return;
- }
-
- // If the input stream has extra bytes, it's for UWB address. The first byte
- // is the address length. It can be 2-byte short address or 8-byte extended
- // address.
- if (base_input_stream.IsAvailable(1)) {
- // The next 1 byte is supposed to be the length of the uwb_address.
- std::uint32_t expected_uwb_address_length = base_input_stream.ReadUint8();
- // If the length of usb_address is not zero, then retrieve it.
- if (expected_uwb_address_length != 0) {
- uwb_address_ = base_input_stream.ReadBytes(expected_uwb_address_length);
- if (uwb_address_.Empty() ||
- uwb_address_.size() != expected_uwb_address_length) {
- NEARBY_LOG(INFO,
- "Cannot deserialize BluetoothDeviceName: "
- "expected uwbAddress size to be %d bytes, got %" PRIu64,
- expected_uwb_address_length, uwb_address_.size());
-
- // Clear enpoint_id for validadity.
- endpoint_id_.clear();
- return;
- }
- }
- }
-}
-
-BluetoothDeviceName::operator std::string() const {
- if (!IsValid()) {
- return "";
- }
-
- // The upper 3 bits are the Version.
- auto version_and_pcp_byte = static_cast<char>(
- (static_cast<uint32_t>(Version::kV1) << 5) & kVersionBitmask);
- // The lower 5 bits are the PCP.
- version_and_pcp_byte |=
- static_cast<char>(static_cast<uint32_t>(pcp_) & kPcpBitmask);
-
- // A byte contains WebRtcState state.
- int web_rtc_connectable_flag =
- (web_rtc_state_ == WebRtcState::kConnectable) ? 1 : 0;
- char field_byte = static_cast<char>(web_rtc_connectable_flag) &
- kWebRtcConnectableFlagBitmask;
-
- ByteArray reserved_bytes{kReservedLength};
-
- ByteArray usable_endpoint_info(endpoint_info_);
- if (endpoint_info_.size() > kMaxEndpointInfoLength) {
- NEARBY_LOG(INFO,
- "While serializing Advertisement, truncating Endpoint Name %s "
- "(%lu bytes) down to %d bytes",
- absl::BytesToHexString(endpoint_info_.data()).c_str(),
- endpoint_info_.size(), kMaxEndpointInfoLength);
- usable_endpoint_info.SetData(endpoint_info_.data(), kMaxEndpointInfoLength);
- }
-
- // clang-format off
- std::string out = absl::StrCat(std::string(1, version_and_pcp_byte),
- endpoint_id_,
- std::string(service_id_hash_),
- std::string(1, field_byte),
- std::string(reserved_bytes),
- std::string(1, usable_endpoint_info.size()),
- std::string(usable_endpoint_info));
- // clang-format on
-
- // If UWB address is available, attach it at the end.
- if (!uwb_address_.Empty()) {
- absl::StrAppend(&out, std::string(1, uwb_address_.size()));
- absl::StrAppend(&out, std::string(uwb_address_));
- }
-
- return Base64Utils::Encode(ByteArray{std::move(out)});
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/bluetooth_device_name.h b/chromium/third_party/nearby/src/cpp/core/internal/bluetooth_device_name.h
deleted file mode 100644
index 44e3c07d1cb..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/bluetooth_device_name.h
+++ /dev/null
@@ -1,93 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_BLUETOOTH_DEVICE_NAME_H_
-#define CORE_INTERNAL_BLUETOOTH_DEVICE_NAME_H_
-
-#include <cstdint>
-
-#include "absl/strings/string_view.h"
-#include "core/internal/base_pcp_handler.h"
-#include "core/internal/pcp.h"
-#include "platform/base/byte_array.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Represents the format of the Bluetooth device name used in Advertising +
-// Discovery.
-//
-// <p>See go/nearby-offline-data-interchange-formats for the specification.
-class BluetoothDeviceName {
- public:
- // Versions of the BluetoothDeviceName.
- enum class Version {
- kUndefined = 0,
- kV1 = 1,
- // Version is only allocated 3 bits in the BluetoothDeviceName, so this
- // can never go beyond V7.
- };
-
- static constexpr int kServiceIdHashLength = 3;
-
- BluetoothDeviceName() = default;
- BluetoothDeviceName(Version version, Pcp pcp, absl::string_view endpoint_id,
- const ByteArray& service_id_hash,
- const ByteArray& endpoint_info,
- const ByteArray& uwb_address, WebRtcState web_rtc_state);
- explicit BluetoothDeviceName(absl::string_view bluetooth_device_name_string);
- BluetoothDeviceName(const BluetoothDeviceName&) = default;
- BluetoothDeviceName& operator=(const BluetoothDeviceName&) = default;
- BluetoothDeviceName(BluetoothDeviceName&&) = default;
- BluetoothDeviceName& operator=(BluetoothDeviceName&&) = default;
- ~BluetoothDeviceName() = default;
-
- explicit operator std::string() const;
-
- bool IsValid() const { return !endpoint_id_.empty(); }
- Version GetVersion() const { return version_; }
- Pcp GetPcp() const { return pcp_; }
- std::string GetEndpointId() const { return endpoint_id_; }
- ByteArray GetServiceIdHash() const { return service_id_hash_; }
- ByteArray GetEndpointInfo() const { return endpoint_info_; }
- ByteArray GetUwbAddress() const { return uwb_address_; }
- WebRtcState GetWebRtcState() const { return web_rtc_state_; }
-
- private:
- static constexpr int kEndpointIdLength = 4;
- static constexpr int kReservedLength = 6;
- static constexpr int kMaxEndpointInfoLength = 131;
- static constexpr int kMinBluetoothDeviceNameLength = 16;
-
- static constexpr int kVersionBitmask = 0x0E0;
- static constexpr int kPcpBitmask = 0x01F;
- static constexpr int kEndpointNameLengthBitmask = 0x0FF;
- static constexpr int kWebRtcConnectableFlagBitmask = 0x01;
-
- Version version_{Version::kUndefined};
- Pcp pcp_{Pcp::kUnknown};
- std::string endpoint_id_;
- ByteArray service_id_hash_;
- ByteArray endpoint_info_;
- // TODO(b/169550050): Define UWB address field.
- ByteArray uwb_address_;
- WebRtcState web_rtc_state_{WebRtcState::kUndefined};
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_BLUETOOTH_DEVICE_NAME_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/bluetooth_device_name_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/bluetooth_device_name_test.cc
deleted file mode 100644
index f4b82b8891e..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/bluetooth_device_name_test.cc
+++ /dev/null
@@ -1,207 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/bluetooth_device_name.h"
-
-#include <cstring>
-#include <memory>
-
-#include "gtest/gtest.h"
-#include "platform/base/base64_utils.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-
-constexpr BluetoothDeviceName::Version kVersion =
- BluetoothDeviceName::Version::kV1;
-constexpr Pcp kPcp = Pcp::kP2pCluster;
-constexpr absl::string_view kEndPointID{"AB12"};
-constexpr absl::string_view kServiceIDHashBytes{"\x0a\x0b\x0c"};
-constexpr absl::string_view kEndPointName{"RAWK + ROWL!"};
-constexpr WebRtcState kWebRtcState = WebRtcState::kConnectable;
-
-// TODO(b/169550050): Implement UWBAddress.
-TEST(BluetoothDeviceNameTest, ConstructionWorks) {
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- ByteArray endpoint_info{std::string(kEndPointName)};
- BluetoothDeviceName bluetooth_device_name{
- kVersion, kPcp, kEndPointID, service_id_hash,
- endpoint_info, ByteArray{}, kWebRtcState};
-
- EXPECT_TRUE(bluetooth_device_name.IsValid());
- EXPECT_EQ(kVersion, bluetooth_device_name.GetVersion());
- EXPECT_EQ(kPcp, bluetooth_device_name.GetPcp());
- EXPECT_EQ(kEndPointID, bluetooth_device_name.GetEndpointId());
- EXPECT_EQ(service_id_hash, bluetooth_device_name.GetServiceIdHash());
- EXPECT_EQ(endpoint_info, bluetooth_device_name.GetEndpointInfo());
- EXPECT_EQ(kWebRtcState, bluetooth_device_name.GetWebRtcState());
-}
-
-TEST(BluetoothDeviceNameTest, ConstructionWorksWithEmptyEndpointName) {
- ByteArray empty_endpoint_info;
-
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- BluetoothDeviceName bluetooth_device_name{kVersion,
- kPcp,
- kEndPointID,
- service_id_hash,
- empty_endpoint_info,
- ByteArray{},
- kWebRtcState};
-
- EXPECT_TRUE(bluetooth_device_name.IsValid());
- EXPECT_EQ(kVersion, bluetooth_device_name.GetVersion());
- EXPECT_EQ(kPcp, bluetooth_device_name.GetPcp());
- EXPECT_EQ(kEndPointID, bluetooth_device_name.GetEndpointId());
- EXPECT_EQ(service_id_hash, bluetooth_device_name.GetServiceIdHash());
- EXPECT_EQ(empty_endpoint_info, bluetooth_device_name.GetEndpointInfo());
- EXPECT_EQ(kWebRtcState, bluetooth_device_name.GetWebRtcState());
-}
-
-TEST(BluetoothDeviceNameTest, ConstructionFailsWithBadVersion) {
- auto bad_version = static_cast<BluetoothDeviceName::Version>(666);
-
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- ByteArray endpoint_info{std::string(kEndPointName)};
- BluetoothDeviceName bluetooth_device_name{
- bad_version, kPcp, kEndPointID, service_id_hash,
- endpoint_info, ByteArray{}, kWebRtcState};
-
- EXPECT_FALSE(bluetooth_device_name.IsValid());
-}
-
-TEST(BluetoothDeviceNameTest, ConstructionFailsWithBadPcp) {
- auto bad_pcp = static_cast<Pcp>(666);
-
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- ByteArray endpoint_info{std::string(kEndPointName)};
- BluetoothDeviceName bluetooth_device_name{
- kVersion, bad_pcp, kEndPointID, service_id_hash,
- endpoint_info, ByteArray{}, kWebRtcState};
-
- EXPECT_FALSE(bluetooth_device_name.IsValid());
-}
-
-TEST(BluetoothDeviceNameTest, ConstructionFailsWithShortEndpointId) {
- std::string short_endpoint_id("AB1");
-
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- ByteArray endpoint_info{std::string(kEndPointName)};
- BluetoothDeviceName bluetooth_device_name{
- kVersion, kPcp, short_endpoint_id, service_id_hash,
- endpoint_info, ByteArray{}, kWebRtcState};
-
- EXPECT_FALSE(bluetooth_device_name.IsValid());
-}
-
-TEST(BluetoothDeviceNameTest, ConstructionFailsWithLongEndpointId) {
- std::string long_endpoint_id("AB12X");
-
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- ByteArray endpoint_info{std::string(kEndPointName)};
- BluetoothDeviceName bluetooth_device_name{
- kVersion, kPcp, long_endpoint_id, service_id_hash,
- endpoint_info, ByteArray{}, kWebRtcState};
-
- EXPECT_FALSE(bluetooth_device_name.IsValid());
-}
-
-TEST(BluetoothDeviceNameTest, ConstructionFailsWithShortServiceIdHash) {
- char short_service_id_hash_bytes[] = "\x0a\x0b";
-
- ByteArray short_service_id_hash{short_service_id_hash_bytes};
- ByteArray endpoint_info{std::string(kEndPointName)};
- BluetoothDeviceName bluetooth_device_name{
- kVersion, kPcp, kEndPointID, short_service_id_hash,
- endpoint_info, ByteArray{}, kWebRtcState};
-
- EXPECT_FALSE(bluetooth_device_name.IsValid());
-}
-
-TEST(BluetoothDeviceNameTest, ConstructionFailsWithLongServiceIdHash) {
- char long_service_id_hash_bytes[] = "\x0a\x0b\x0c\x0d";
-
- ByteArray long_service_id_hash{long_service_id_hash_bytes};
- ByteArray endpoint_info{std::string(kEndPointName)};
- BluetoothDeviceName bluetooth_device_name{
- kVersion, kPcp, kEndPointID, long_service_id_hash,
- endpoint_info, ByteArray{}, kWebRtcState};
-
- EXPECT_FALSE(bluetooth_device_name.IsValid());
-}
-
-TEST(BluetoothDeviceNameTest, ConstructionFailsWithShortStringLength) {
- char bluetooth_device_name_string[] = "X";
-
- ByteArray bluetooth_device_name_bytes{bluetooth_device_name_string};
- BluetoothDeviceName bluetooth_device_name{
- Base64Utils::Encode(bluetooth_device_name_bytes)};
-
- EXPECT_FALSE(bluetooth_device_name.IsValid());
-}
-
-TEST(BluetoothDeviceNameTest, ConstructionFailsWithWrongEndpointNameLength) {
- // Serialize good data into a good Bluetooth Device Name.
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- ByteArray endpoint_info{std::string(kEndPointName)};
- BluetoothDeviceName bluetooth_device_name{
- kVersion, kPcp, kEndPointID, service_id_hash,
- endpoint_info, ByteArray{}, kWebRtcState};
- auto bluetooth_device_name_string = std::string(bluetooth_device_name);
-
- // Base64-decode the good Bluetooth Device Name.
- ByteArray bluetooth_device_name_bytes =
- Base64Utils::Decode(bluetooth_device_name_string);
- // Corrupt the EndpointNameLength bits (120-127) by reversing all of them.
- std::string corrupt_string(bluetooth_device_name_bytes.data(),
- bluetooth_device_name_bytes.size());
- corrupt_string[15] ^= 0x0FF;
- // Base64-encode the corrupted bytes into a corrupt Bluetooth Device Name.
- ByteArray corrupt_bluetooth_device_name_bytes{corrupt_string.data(),
- corrupt_string.size()};
- std::string corrupt_bluetooth_device_name_string(
- Base64Utils::Encode(corrupt_bluetooth_device_name_bytes));
-
- // And deserialize the corrupt Bluetooth Device Name.
- BluetoothDeviceName corrupt_bluetooth_device_name(
- corrupt_bluetooth_device_name_string);
-
- EXPECT_FALSE(corrupt_bluetooth_device_name.IsValid());
-}
-
-TEST(BluetoothDeviceNameTest, CanParseGeneratedName) {
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- ByteArray endpoint_info{std::string(kEndPointName)};
- // Build name1 from scratch.
- BluetoothDeviceName name1{kVersion, kPcp, kEndPointID,
- service_id_hash, endpoint_info, ByteArray{},
- kWebRtcState};
- // Build name2 from string composed from name1.
- BluetoothDeviceName name2{std::string(name1)};
- EXPECT_TRUE(name1.IsValid());
- EXPECT_TRUE(name2.IsValid());
- EXPECT_EQ(name1.GetVersion(), name2.GetVersion());
- EXPECT_EQ(name1.GetPcp(), name2.GetPcp());
- EXPECT_EQ(name1.GetEndpointId(), name2.GetEndpointId());
- EXPECT_EQ(name1.GetServiceIdHash(), name2.GetServiceIdHash());
- EXPECT_EQ(name1.GetEndpointInfo(), name2.GetEndpointInfo());
- EXPECT_EQ(name1.GetWebRtcState(), name2.GetWebRtcState());
-}
-
-} // namespace
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/bluetooth_endpoint_channel.cc b/chromium/third_party/nearby/src/cpp/core/internal/bluetooth_endpoint_channel.cc
deleted file mode 100644
index 7e38e648f8d..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/bluetooth_endpoint_channel.cc
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/bluetooth_endpoint_channel.h"
-
-#include <string>
-
-#include "platform/public/bluetooth_classic.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-namespace {
-
-OutputStream* GetOutputStreamOrNull(BluetoothSocket& socket) {
- if (socket.GetRemoteDevice().IsValid()) return &socket.GetOutputStream();
- return nullptr;
-}
-
-InputStream* GetInputStreamOrNull(BluetoothSocket& socket) {
- if (socket.GetRemoteDevice().IsValid()) return &socket.GetInputStream();
- return nullptr;
-}
-
-} // namespace
-
-BluetoothEndpointChannel::BluetoothEndpointChannel(
- const std::string& channel_name, BluetoothSocket socket)
- : BaseEndpointChannel(channel_name, GetInputStreamOrNull(socket),
- GetOutputStreamOrNull(socket)),
- bluetooth_socket_(std::move(socket)) {}
-
-proto::connections::Medium BluetoothEndpointChannel::GetMedium() const {
- return proto::connections::Medium::BLUETOOTH;
-}
-
-int BluetoothEndpointChannel::GetMaxTransmitPacketSize() const {
- return kDefaultBTMaxTransmitPacketSize;
-}
-
-void BluetoothEndpointChannel::CloseImpl() {
- auto status = bluetooth_socket_.Close();
- if (!status.Ok()) {
- NEARBY_LOGS(INFO)
- << "Failed to close underlying socket for BluetoothEndpointChannel "
- << GetName() << ": exception=" << status.value;
- }
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/bluetooth_endpoint_channel.h b/chromium/third_party/nearby/src/cpp/core/internal/bluetooth_endpoint_channel.h
deleted file mode 100644
index f9059348056..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/bluetooth_endpoint_channel.h
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_BLUETOOTH_ENDPOINT_CHANNEL_H_
-#define CORE_INTERNAL_BLUETOOTH_ENDPOINT_CHANNEL_H_
-
-#include <string>
-
-#include "core/internal/base_endpoint_channel.h"
-#include "platform/public/bluetooth_classic.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-class BluetoothEndpointChannel final : public BaseEndpointChannel {
- public:
- // Creates both outgoing and incoming BT channels.
- BluetoothEndpointChannel(const std::string& channel_name,
- BluetoothSocket bluetooth_socket);
-
- proto::connections::Medium GetMedium() const override;
-
- int GetMaxTransmitPacketSize() const override;
-
- private:
- static constexpr int kDefaultBTMaxTransmitPacketSize = 1980; // 990 * 2 Bytes
-
- void CloseImpl() override;
-
- BluetoothSocket bluetooth_socket_;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_BLUETOOTH_ENDPOINT_CHANNEL_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/bwu_handler.h b/chromium/third_party/nearby/src/cpp/core/internal/bwu_handler.h
deleted file mode 100644
index c31fa731529..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/bwu_handler.h
+++ /dev/null
@@ -1,89 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_BWU_HANDLER_H_
-#define CORE_INTERNAL_BWU_HANDLER_H_
-
-#include "core/internal/client_proxy.h"
-#include "core/internal/endpoint_channel.h"
-#include "core/internal/offline_frames.h"
-#include "platform/public/count_down_latch.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-using BwuNegotiationFrame = BandwidthUpgradeNegotiationFrame;
-
-// Defines the set of methods that need to be implemented to handle the
-// per-Medium-specific operations needed to upgrade an EndpointChannel.
-class BwuHandler {
- public:
- using UpgradePathInfo = parser::UpgradePathInfo;
-
- virtual ~BwuHandler() = default;
-
- // Called by the Initiator to setup the upgraded medium for this endpoint (if
- // that hasn't already been done), and returns a serialized UpgradePathInfo
- // that can be sent to the Responder.
- // @BwuHandlerThread
- virtual ByteArray InitializeUpgradedMediumForEndpoint(
- ClientProxy* client, const std::string& service_id,
- const std::string& endpoint_id) = 0;
-
- // Called to revert any state changed by the Initiator to setup the upgraded
- // medium for an endpoint.
- // @BwuHandlerThread
- virtual void Revert() = 0;
-
- // Called by the Responder to setup the upgraded medium for this endpoint (if
- // that hasn't already been done) using the UpgradePathInfo sent by the
- // Initiator, and returns a new EndpointChannel for the upgraded medium.
- // @BwuHandlerThread
- virtual std::unique_ptr<EndpointChannel> CreateUpgradedEndpointChannel(
- ClientProxy* client, const std::string& service_id,
- const std::string& endpoint_id,
- const UpgradePathInfo& upgrade_path_info) = 0;
-
- // Returns the upgrade medium of the BwuHandler.
- // @BwuHandlerThread
- virtual Medium GetUpgradeMedium() const = 0;
- virtual void OnEndpointDisconnect(ClientProxy* client,
- const std::string& endpoint_id) = 0;
-
- class IncomingSocket {
- public:
- virtual ~IncomingSocket() = default;
-
- virtual std::string ToString() = 0;
- virtual void Close() = 0;
- };
-
- struct IncomingSocketConnection {
- std::unique_ptr<IncomingSocket> socket;
- std::unique_ptr<EndpointChannel> channel;
- };
-
- struct BwuNotifications {
- std::function<void(ClientProxy* client,
- std::unique_ptr<IncomingSocketConnection> connection)>
- incoming_connection_cb;
- };
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_BWU_HANDLER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/bwu_manager.cc b/chromium/third_party/nearby/src/cpp/core/internal/bwu_manager.cc
deleted file mode 100644
index f73980fe2b9..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/bwu_manager.cc
+++ /dev/null
@@ -1,1201 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/bwu_manager.h"
-
-#include <algorithm>
-#include <memory>
-
-#include "absl/functional/bind_front.h"
-#include "absl/time/time.h"
-#include "core/internal/bluetooth_bwu_handler.h"
-#include "core/internal/bwu_handler.h"
-#include "core/internal/offline_frames.h"
-#include "core/internal/webrtc_bwu_handler.h"
-#include "core/internal/wifi_lan_bwu_handler.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/feature_flags.h"
-#include "platform/public/count_down_latch.h"
-#include "proto/connections_enums.pb.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-using ::location::nearby::proto::connections::DisconnectionReason;
-
-// Required for C++ 14 support in Chrome
-constexpr absl::Duration BwuManager::kReadClientIntroductionFrameTimeout;
-
-BwuManager::BwuManager(
- Mediums& mediums, EndpointManager& endpoint_manager,
- EndpointChannelManager& channel_manager,
- absl::flat_hash_map<Medium, std::unique_ptr<BwuHandler>> handlers,
- Config config)
- : config_(config),
- mediums_(&mediums),
- endpoint_manager_(&endpoint_manager),
- channel_manager_(&channel_manager) {
- if (config_.bandwidth_upgrade_retry_delay == absl::ZeroDuration()) {
- if (FeatureFlags::GetInstance().GetFlags().use_exp_backoff_in_bwu_retry) {
- config_.bandwidth_upgrade_retry_delay =
- FeatureFlags::GetInstance()
- .GetFlags()
- .bwu_retry_exp_backoff_initial_delay;
- } else {
- config_.bandwidth_upgrade_retry_delay = absl::Seconds(5);
- }
- }
- if (config_.bandwidth_upgrade_retry_max_delay == absl::ZeroDuration()) {
- if (FeatureFlags::GetInstance().GetFlags().use_exp_backoff_in_bwu_retry) {
- config_.bandwidth_upgrade_retry_max_delay =
- FeatureFlags::GetInstance()
- .GetFlags()
- .bwu_retry_exp_backoff_maximum_delay;
- } else {
- config_.bandwidth_upgrade_retry_max_delay = absl::Seconds(10);
- }
- }
- if (config_.allow_upgrade_to.All(false)) {
- config_.allow_upgrade_to.web_rtc = true;
- }
- if (!handlers.empty()) {
- handlers_ = std::move(handlers);
- } else {
- InitBwuHandlers();
- }
-
- // Register the offline frame processor.
- endpoint_manager_->RegisterFrameProcessor(
- V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION, this);
-}
-
-BwuManager::~BwuManager() {
- NEARBY_LOGS(INFO) << "BwuManager going down";
- Shutdown();
-}
-
-void BwuManager::InitBwuHandlers() {
- // Register the supported concrete BwuMedium implementations.
- BwuHandler::BwuNotifications notifications{
- .incoming_connection_cb =
- absl::bind_front(&BwuManager::OnIncomingConnection, this),
- };
- if (config_.allow_upgrade_to.wifi_lan) {
- handlers_.emplace(Medium::WIFI_LAN,
- std::make_unique<WifiLanBwuHandler>(
- *mediums_, *channel_manager_, notifications));
- }
- if (config_.allow_upgrade_to.web_rtc) {
- handlers_.emplace(Medium::WEB_RTC,
- std::make_unique<WebrtcBwuHandler>(
- *mediums_, *channel_manager_, notifications));
- }
- if (config_.allow_upgrade_to.bluetooth) {
- handlers_.emplace(Medium::BLUETOOTH,
- std::make_unique<BluetoothBwuHandler>(
- *mediums_, *channel_manager_, notifications));
- }
-}
-
-void BwuManager::Shutdown() {
- NEARBY_LOGS(INFO) << "Initiating shutdown of BwuManager.";
-
- endpoint_manager_->UnregisterFrameProcessor(
- V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION, this);
-
- // Stop all the ongoing Runnables (as gracefully as possible).
- alarm_executor_.Shutdown();
- serial_executor_.Shutdown();
-
- // After worker threads are down we became exclusive owners of data and
- // may access it from current thread.
- for (auto& item : previous_endpoint_channels_) {
- EndpointChannel* channel = item.second.get();
- if (!channel) continue;
- channel->Close(DisconnectionReason::SHUTDOWN);
- }
-
- CancelAllRetryUpgradeAlarms();
- medium_ = Medium::UNKNOWN_MEDIUM;
- for (auto& item : handlers_) {
- BwuHandler& handler = *item.second;
- handler.Revert();
- }
- handlers_.clear();
-
- NEARBY_LOGS(INFO) << "BwuHandler has shut down.";
-}
-
-// This is the point on the Initiator side where the
-// medium_ is set.
-void BwuManager::InitiateBwuForEndpoint(ClientProxy* client,
- const std::string& endpoint_id,
- Medium new_medium) {
- NEARBY_LOGS(INFO) << "InitiateBwuForEndpoint for endpoint " << endpoint_id
- << " with medium " << new_medium;
- RunOnBwuManagerThread("bwu-init", [this, client, endpoint_id, new_medium]() {
- Medium proposed_medium = ChooseBestUpgradeMedium(
- client->GetUpgradeMediums(endpoint_id).GetMediums(true));
- if (new_medium != Medium::UNKNOWN_MEDIUM) {
- proposed_medium = new_medium;
- }
- auto* handler = SetCurrentBwuHandler(proposed_medium);
- if (!handler) {
- NEARBY_LOGS(ERROR)
- << "BwuManager cannot initiate bandwidth upgrade for endpoint "
- << endpoint_id
- << " because the current BandwidthUpgradeMedium cannot be deduced.";
- return;
- }
-
- if (in_progress_upgrades_.contains(endpoint_id)) {
- NEARBY_LOGS(INFO)
- << "BwuManager is ignoring bandwidth upgrade for endpoint "
- << endpoint_id
- << " because we're already upgrading bandwidth for that endpoint.";
-
- return;
- }
- CancelRetryUpgradeAlarm(endpoint_id);
-
- auto channel = channel_manager_->GetChannelForEndpoint(endpoint_id);
- Medium channel_medium =
- channel ? channel->GetMedium() : Medium::UNKNOWN_MEDIUM;
- client->GetAnalyticsRecorder().OnBandwidthUpgradeStarted(
- endpoint_id, channel_medium, medium_, proto::connections::INCOMING,
- client->GetConnectionToken(endpoint_id));
- if (channel == nullptr) {
- NEARBY_LOGS(INFO)
- << "BwuManager couldn't complete the upgrade for endpoint "
- << endpoint_id
- << " because it couldn't find an existing EndpointChannel for it.";
- client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
- endpoint_id, proto::connections::CHANNEL_ERROR,
- proto::connections::NETWORK_AVAILABLE);
- return;
- }
-
- // Ignore requests where the medium we're upgrading to is the medium we're
- // already connected over. This can happen now that Bluetooth is both an
- // advertising medium and a potential bandwidth upgrade, and will continue
- // to be possible as we add other new advertising mediums like mDNS (WiFi
- // LAN). Very specifically, this happens now when a device uses P2P_CLUSTER,
- // connects over Bluetooth, and is not connected to LAN. Bluetooth is the
- // best medium, and we attempt to upgrade from Bluetooth to Bluetooth.
- // if (medium_ == channel->GetMedium()) {
- NEARBY_LOGS(INFO) << "BwuManager ignoring the upgrade for endpoint "
- << endpoint_id
- << " because it is already connected over medium "
- << proto::connections::Medium_Name(medium_);
- if (medium_ == channel->GetMedium()) {
- return;
- }
-
- std::string service_id = client->GetServiceId();
- ByteArray bytes = handler->InitializeUpgradedMediumForEndpoint(
- client, service_id, endpoint_id);
-
- // Because we grab the endpointChannel first thing, it is possible the
- // endpointChannel is stale by the time we attempt to write over it.
- if (bytes.Empty()) {
- NEARBY_LOGS(ERROR)
- << "BwuManager couldn't complete the upgrade for endpoint "
- << endpoint_id << " to medium "
- << proto::connections::Medium_Name(medium_)
- << " because it failed to initialize the "
- "BWU_NEGOTIATION.UPGRADE_PATH_AVAILABLE OfflineFrame.";
- UpgradePathInfo info;
- info.set_medium(parser::MediumToUpgradePathInfoMedium(medium_));
-
- ProcessUpgradeFailureEvent(client, endpoint_id, info);
- client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
- endpoint_id, proto::connections::RESULT_IO_ERROR,
- proto::connections::NETWORK_AVAILABLE);
- return;
- }
- if (!channel->Write(bytes).Ok()) {
- NEARBY_LOGS(ERROR)
- << "BwuManager couldn't complete the upgrade for endpoint "
- << endpoint_id << " to medium "
- << proto::connections::Medium_Name(medium_)
- << " because it failed to write the "
- "BWU_NEGOTIATION.UPGRADE_PATH_AVAILABLE OfflineFrame.";
- return;
- }
-
- NEARBY_LOGS(INFO)
- << "BwuManager successfully wrote the "
- "BWU_NEGOTIATION.UPGRADE_PATH_AVAILABLE OfflineFrame while "
- "upgrading endpoint "
- << endpoint_id << " to medium"
- << proto::connections::Medium_Name(medium_);
- in_progress_upgrades_.emplace(endpoint_id, client);
- });
-}
-
-void BwuManager::OnIncomingFrame(OfflineFrame& frame,
- const std::string& endpoint_id,
- ClientProxy* client, Medium medium) {
- NEARBY_LOGS(INFO) << "OnIncomingFrame for endpoint " << endpoint_id
- << " with medium "
- << proto::connections::Medium_Name(medium);
- if (parser::GetFrameType(frame) != V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION)
- return;
- auto bwu_frame = frame.v1().bandwidth_upgrade_negotiation();
- if (FeatureFlags::GetInstance().GetFlags().enable_async_bandwidth_upgrade) {
- RunOnBwuManagerThread(
- "bwu-on-incoming-frame", [this, client, endpoint_id, bwu_frame]() {
- OnBwuNegotiationFrame(client, bwu_frame, endpoint_id);
- });
- } else {
- CountDownLatch latch(1);
- RunOnBwuManagerThread("bwu-on-incoming-frame", [this, client, endpoint_id,
- bwu_frame, &latch]() {
- OnBwuNegotiationFrame(client, bwu_frame, endpoint_id);
- latch.CountDown();
- });
- latch.Await();
- }
-}
-
-void BwuManager::OnEndpointDisconnect(ClientProxy* client,
- const std::string& endpoint_id,
- CountDownLatch barrier) {
- NEARBY_LOGS(INFO)
- << "BwuManager has processed endpoint disconnection for endpoint "
- << endpoint_id;
- RunOnBwuManagerThread(
- "bwu-on-endpoint-disconnect",
- [this, client, endpoint_id, barrier]() mutable {
- if (medium_ == Medium::UNKNOWN_MEDIUM) {
- NEARBY_LOGS(INFO)
- << "BwuManager has processed endpoint disconnection for endpoint "
- << endpoint_id
- << " because there is no current BandwidthUpgradeMedium.";
- barrier.CountDown();
- return;
- }
-
- if (handler_) {
- handler_->OnEndpointDisconnect(client, endpoint_id);
- }
-
- auto item = previous_endpoint_channels_.extract(endpoint_id);
-
- if (!item.empty()) {
- auto old_channel = item.mapped();
- if (old_channel != nullptr) {
- old_channel->Close(DisconnectionReason::SHUTDOWN);
- }
- }
- in_progress_upgrades_.erase(endpoint_id);
- retry_delays_.erase(endpoint_id);
- CancelRetryUpgradeAlarm(endpoint_id);
-
- successfully_upgraded_endpoints_.erase(endpoint_id);
-
- // If this was our very last endpoint:
- //
- // a) revert all the changes for currentBwuMedium.
- // b) reset currentBwuMedium.
- if (channel_manager_->GetConnectedEndpointsCount() <= 1) {
- Revert();
- }
- barrier.CountDown();
- });
-}
-
-BwuHandler* BwuManager::SetCurrentBwuHandler(Medium medium) {
- NEARBY_LOGS(INFO) << "SetCurrentBwuHandler to medium "
- << proto::connections::Medium_Name(medium);
- handler_ = nullptr;
- medium_ = medium;
- if (medium != Medium::UNKNOWN_MEDIUM) {
- auto item = handlers_.find(medium);
- if (item != handlers_.end()) {
- handler_ = item->second.get();
- }
- }
- return handler_;
-}
-
-void BwuManager::Revert() {
- NEARBY_LOGS(INFO) << "Revert reseting medium "
- << proto::connections::Medium_Name(medium_);
- if (handler_) {
- handler_->Revert();
- handler_ = nullptr;
- }
- medium_ = Medium::UNKNOWN_MEDIUM;
-}
-
-void BwuManager::OnBwuNegotiationFrame(ClientProxy* client,
- const BwuNegotiationFrame frame,
- const string& endpoint_id) {
- NEARBY_LOGS(INFO) << "BwuManager process incoming OfflineFrame for endpoint "
- << endpoint_id;
- switch (frame.event_type()) {
- case BwuNegotiationFrame::UPGRADE_PATH_AVAILABLE:
- ProcessBwuPathAvailableEvent(client, endpoint_id,
- frame.upgrade_path_info());
- break;
- case BwuNegotiationFrame::UPGRADE_FAILURE:
- ProcessUpgradeFailureEvent(client, endpoint_id,
- frame.upgrade_path_info());
- break;
- case BwuNegotiationFrame::LAST_WRITE_TO_PRIOR_CHANNEL:
- ProcessLastWriteToPriorChannelEvent(client, endpoint_id);
- break;
- case BwuNegotiationFrame::SAFE_TO_CLOSE_PRIOR_CHANNEL:
- ProcessSafeToClosePriorChannelEvent(client, endpoint_id);
- break;
- default:
- NEARBY_LOGS(WARNING)
- << "BwuManager can't process unknown incoming OfflineFrame of type "
- << frame.event_type() << ", ignoring it.";
- break;
- }
-}
-
-void BwuManager::OnIncomingConnection(
- ClientProxy* client,
- std::unique_ptr<BwuHandler::IncomingSocketConnection> mutable_connection) {
- NEARBY_LOGS(INFO) << "BwuManager process incoming connection service_id="
- << client->GetServiceId();
- std::shared_ptr<BwuHandler::IncomingSocketConnection> connection(
- mutable_connection.release());
- RunOnBwuManagerThread(
- "bwu-on-incoming-connection", [this, client, connection]() {
- absl::Time connection_attempt_start_time =
- SystemClock::ElapsedRealtime();
- EndpointChannel* channel = connection->channel.get();
- if (channel == nullptr) {
- NEARBY_LOGS(ERROR)
- << "BwuManager failed to create new EndpointChannel for incoming "
- "socket.";
- connection->socket->Close();
- AttemptToRecordBandwidthUpgradeErrorForUnknownEndpoint(
- proto::connections::MEDIUM_ERROR,
- proto::connections::SOCKET_CREATION);
- return;
- }
-
- NEARBY_LOGS(VERBOSE)
- << "BwuManager successfully created new EndpointChannel for "
- "incoming socket";
-
- ClientIntroduction introduction;
- if (!ReadClientIntroductionFrame(channel, introduction)) {
- // This was never a fully EstablishedConnection, no need to provide a
- // closure reason.
- channel->Close();
- NEARBY_LOGS(ERROR)
- << "BwuManager failed to read "
- "BWU_NEGOTIATION.CLIENT_INTRODUCTION OfflineFrame from "
- "newly-created EndpointChannel "
- << channel->GetName()
- << ", so the EndpointChannel was discarded.";
- return;
- }
-
- if (!WriteClientIntroductionAckFrame(channel)) {
- // This was never a fully EstablishedConnection, no need to provide a
- // closure reason.
- channel->Close();
- return;
- }
-
- NEARBY_LOGS(VERBOSE) << "BwuManager successfully received "
- "BWU_NEGOTIATION.CLIENT_INTRODUCTION "
- "OfflineFrame on EndpointChannel "
- << channel->GetName();
-
- const std::string& endpoint_id = introduction.endpoint_id();
- ClientProxy* mapped_client;
- const auto item = in_progress_upgrades_.find(endpoint_id);
- if (item == in_progress_upgrades_.end()) return;
- mapped_client = item->second;
- CancelRetryUpgradeAlarm(endpoint_id);
- if (mapped_client == nullptr) {
- // This was never a fully EstablishedConnection, no need to provide a
- // closure reason.
- channel->Close();
- return;
- }
-
- CHECK(client == mapped_client);
-
- // The ConnectionAttempt has now succeeded, so record it as such.
- client->GetAnalyticsRecorder().OnIncomingConnectionAttempt(
- proto::connections::UPGRADE, channel->GetMedium(),
- proto::connections::RESULT_SUCCESS,
- SystemClock::ElapsedRealtime() - connection_attempt_start_time,
- client->GetConnectionToken(endpoint_id));
-
- // Use the introductory client information sent over to run the upgrade
- // protocol.
- RunUpgradeProtocol(mapped_client, endpoint_id,
- std::move(connection->channel));
- });
-}
-
-void BwuManager::RunOnBwuManagerThread(const std::string& name,
- Runnable runnable) {
- serial_executor_.Execute(name, std::move(runnable));
-}
-
-void BwuManager::RunUpgradeProtocol(
- ClientProxy* client, const std::string& endpoint_id,
- std::unique_ptr<EndpointChannel> new_channel) {
- NEARBY_LOGS(INFO) << "RunUpgradeProtocol new channel @" << new_channel.get()
- << " name: " << new_channel->GetName()
- << ", medium: " << new_channel->GetMedium();
- // First, register this new EndpointChannel as *the* EndpointChannel to use
- // for this endpoint here onwards. NOTE: We pause this new EndpointChannel
- // until we've completely drained the old EndpointChannel to avoid out of
- // order reads on the other side. This is a consequence of using the same
- // UKEY2 context for both the previous and new EndpointChannels. UKEY2 uses
- // sequence numbers for writes and reads, and simultaneously sending Payloads
- // on the new channel and control messages on the old channel cause the other
- // side to read messages out of sequence
- new_channel->Pause();
- auto old_channel = channel_manager_->GetChannelForEndpoint(endpoint_id);
- if (!old_channel) {
- NEARBY_LOGS(INFO)
- << "BwuManager didn't find a previous EndpointChannel for "
- << endpoint_id
- << " when registering the new EndpointChannel, short-circuiting the "
- "upgrade protocol.";
- client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
- endpoint_id, proto::connections::CHANNEL_ERROR,
- proto::connections::PRIOR_ENDPOINT_CHANNEL);
- return;
- }
- channel_manager_->ReplaceChannelForEndpoint(client, endpoint_id,
- std::move(new_channel));
-
- // Next, initiate a clean shutdown for the previous EndpointChannel used for
- // this endpoint by telling the remote device that it will not receive any
- // more writes over that EndpointChannel.
- if (!old_channel->Write(parser::ForBwuLastWrite()).Ok()) {
- NEARBY_LOGS(ERROR)
- << "BwuManager failed to write "
- "BWU_NEGOTIATION.LAST_WRITE_TO_PRIOR_CHANNEL OfflineFrame to "
- "endpoint "
- << endpoint_id << ", short-circuiting the upgrade protocol.";
- client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
- endpoint_id, proto::connections::RESULT_IO_ERROR,
- proto::connections::LAST_WRITE_TO_PRIOR_CHANNEL);
- return;
- }
- NEARBY_LOGS(VERBOSE) << "BwuManager successfully wrote "
- "BWU_NEGOTIATION.LAST_WRITE_TO_PRIOR_CHANNEL "
- "OfflineFrame while upgrading endpoint "
- << endpoint_id;
-
- // The remainder of this clean shutdown for the previous EndpointChannel will
- // continue when we receive a corresponding
- // BANDWIDTH_UPGRADE_NEGOTIATION.LAST_WRITE_TO_PRIOR_CHANNEL OfflineFrame from
- // the remote device, so for now, just store that previous EndpointChannel.
- previous_endpoint_channels_.emplace(endpoint_id, old_channel);
-
- // If we already read LAST_WRITE on the old endpoint channel, then we can
- // safely close it now.
- auto item = successfully_upgraded_endpoints_.extract(endpoint_id);
- if (!item.empty()) {
- ProcessLastWriteToPriorChannelEvent(client, endpoint_id);
- }
-}
-
-// Outgoing BWU session.
-void BwuManager::ProcessBwuPathAvailableEvent(
- ClientProxy* client, const string& endpoint_id,
- const UpgradePathInfo& upgrade_path_info) {
- NEARBY_LOGS(INFO) << "ProcessBwuPathAvailableEvent for endpoint "
- << endpoint_id << " medium "
- << parser::UpgradePathInfoMediumToMedium(
- upgrade_path_info.medium());
- if (in_progress_upgrades_.contains(endpoint_id)) {
- NEARBY_LOGS(ERROR)
- << "BwuManager received a duplicate bandwidth upgrade for endpoint "
- << endpoint_id
- << ". We're out of sync with the remote device and cannot recover; "
- "closing all channels.";
-
- auto item = previous_endpoint_channels_.extract(endpoint_id);
- if (!item.empty()) {
- std::shared_ptr<EndpointChannel> previous_endpoint_channel =
- item.mapped();
- if (previous_endpoint_channel) {
- previous_endpoint_channel->Close(DisconnectionReason::UNFINISHED);
- }
- }
- std::shared_ptr<EndpointChannel> new_channel =
- channel_manager_->GetChannelForEndpoint(endpoint_id);
- if (new_channel) {
- // The upgraded channel never finished upgrading, and therefore is still
- // paused.
- new_channel->Resume();
- new_channel->Close(DisconnectionReason::UNFINISHED);
- }
-
- return;
- }
- Medium medium =
- parser::UpgradePathInfoMediumToMedium(upgrade_path_info.medium());
- if (medium_ == Medium::UNKNOWN_MEDIUM) {
- SetCurrentBwuHandler(medium);
- }
- // Check for the correct medium so we don't process an incorrect OfflineFrame.
- if (medium != medium_) {
- NEARBY_LOGS(INFO) << "Medium not matching";
- RunUpgradeFailedProtocol(client, endpoint_id, upgrade_path_info);
- return;
- }
-
- client->GetAnalyticsRecorder().OnBandwidthUpgradeStarted(
- endpoint_id, medium, medium_, proto::connections::OUTGOING,
- client->GetConnectionToken(endpoint_id));
-
- absl::Time connection_attempt_start_time = SystemClock::ElapsedRealtime();
- auto channel = ProcessBwuPathAvailableEventInternal(client, endpoint_id,
- upgrade_path_info);
- proto::connections::ConnectionAttemptResult connection_attempt_result;
- if (channel != nullptr) {
- connection_attempt_result = proto::connections::RESULT_SUCCESS;
- } else if (client->GetCancellationFlag(endpoint_id)->Cancelled()) {
- connection_attempt_result = proto::connections::RESULT_CANCELLED;
- client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
- endpoint_id, proto::connections::RESULT_REMOTE_ERROR,
- proto::connections::UPGRADE_CANCEL);
- } else {
- connection_attempt_result = proto::connections::RESULT_ERROR;
- }
-
- client->GetAnalyticsRecorder().OnOutgoingConnectionAttempt(
- endpoint_id, proto::connections::UPGRADE, medium_,
- connection_attempt_result,
- SystemClock::ElapsedRealtime() - connection_attempt_start_time,
- client->GetConnectionToken(endpoint_id));
-
- if (channel == nullptr) {
- NEARBY_LOGS(INFO) << "Failed to get new channel.";
- RunUpgradeFailedProtocol(client, endpoint_id, upgrade_path_info);
- return;
- }
-
- in_progress_upgrades_.emplace(endpoint_id, client);
- RunUpgradeProtocol(client, endpoint_id, std::move(channel));
-}
-
-std::unique_ptr<EndpointChannel>
-BwuManager::ProcessBwuPathAvailableEventInternal(
- ClientProxy* client, const string& endpoint_id,
- const UpgradePathInfo& upgrade_path_info) {
- NEARBY_LOGS(INFO) << "ProcessBwuPathAvailableEventInternal for endpoint "
- << endpoint_id << " medium "
- << parser::UpgradePathInfoMediumToMedium(
- upgrade_path_info.medium());
- std::unique_ptr<EndpointChannel> channel =
- handler_->CreateUpgradedEndpointChannel(client, client->GetServiceId(),
- endpoint_id, upgrade_path_info);
- if (!channel) {
- NEARBY_LOGS(ERROR)
- << "BwuManager failed to create an endpoint channel to endpoint"
- << endpoint_id << ", aborting upgrade.";
- client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
- endpoint_id, proto::connections::RESULT_IO_ERROR,
- proto::connections::SOCKET_CREATION);
- return nullptr;
- }
-
- // Write the requisite BANDWIDTH_UPGRADE_NEGOTIATION.CLIENT_INTRODUCTION as
- // the first OfflineFrame on this new EndpointChannel.
- if (!channel->Write(parser::ForBwuIntroduction(client->GetLocalEndpointId()))
- .Ok()) {
- // This was never a fully EstablishedConnection, no need to provide a
- // closure reason.
- channel->Close();
-
- NEARBY_LOGS(ERROR)
- << "BwuManager failed to write BWU_NEGOTIATION.CLIENT_INTRODUCTION "
- "OfflineFrame to newly-created EndpointChannel "
- << channel->GetName() << ", aborting upgrade.";
- client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
- endpoint_id, proto::connections::RESULT_IO_ERROR,
- proto::connections::CLIENT_INTRODUCTION);
- return {};
- }
-
- if (upgrade_path_info.supports_client_introduction_ack()) {
- if (!ReadClientIntroductionAckFrame(channel.get())) {
- // This was never a fully EstablishedConnection, no need to provide a
- // closure reason.
- channel->Close();
-
- NEARBY_LOGS(ERROR) << "BwuManager failed to read "
- "BWU_NEGOTIATION.CLIENT_INTRODUCTION_ACK "
- "OfflineFrame to newly-created EndpointChannel "
- << channel->GetName() << ", aborting upgrade.";
-
- return {};
- }
- }
-
- NEARBY_LOGS(INFO) << "BwuManager successfully wrote "
- "BWU_NEGOTIATION.CLIENT_INTRODUCTION OfflineFrame to "
- "newly-created EndpointChannel "
- << channel->GetName() << " while upgrading endpoint "
- << endpoint_id;
-
- // Set the AnalyticsRecorder so that the future closure of this
- // EndpointChannel will be recorded.
- return channel;
-}
-
-void BwuManager::RunUpgradeFailedProtocol(
- ClientProxy* client, const std::string& endpoint_id,
- const UpgradePathInfo& upgrade_path_info) {
- NEARBY_LOGS(INFO) << "RunUpgradeFailedProtocol for endpoint " << endpoint_id
- << " medium "
- << parser::UpgradePathInfoMediumToMedium(
- upgrade_path_info.medium());
- // We attempted to connect to the new medium that the remote device has set up
- // for us but we failed. We need to let the remote device know so that they
- // can pick another medium for us to try.
- std::shared_ptr<EndpointChannel> channel =
- channel_manager_->GetChannelForEndpoint(endpoint_id);
- if (!channel) {
- NEARBY_LOGS(ERROR)
- << "BwuManager didn't find a previous EndpointChannel for "
- << endpoint_id
- << " when sending an upgrade failure frame, short-circuiting the "
- "upgrade protocol.";
- client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
- endpoint_id, proto::connections::CHANNEL_ERROR,
- proto::connections::NETWORK_AVAILABLE);
- return;
- }
-
- // Report UPGRADE_FAILURE to the remote device.
- if (!channel->Write(parser::ForBwuFailure(upgrade_path_info)).Ok()) {
- channel->Close(DisconnectionReason::IO_ERROR);
-
- NEARBY_LOGS(ERROR)
- << "BwuManager failed to write BWU_NEGOTIATION.UPGRADE_FAILURE "
- "OfflineFrame to endpoint "
- << endpoint_id << ", short-circuiting the upgrade protocol.";
- client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
- endpoint_id, proto::connections::RESULT_IO_ERROR,
- proto::connections::NETWORK_AVAILABLE);
- return;
- }
-
- // And lastly, clean up our currentBwuMedium since we failed to
- // utilize it anyways.
- if (medium_ != Medium::UNKNOWN_MEDIUM) {
- Revert();
- }
- in_progress_upgrades_.erase(endpoint_id);
- NEARBY_LOGS(INFO) << "BwuManager has informed endpoint " << endpoint_id
- << " that the bandwidth upgrade failed.";
-}
-
-bool BwuManager::ReadClientIntroductionFrame(EndpointChannel* channel,
- ClientIntroduction& introduction) {
- NEARBY_LOGS(INFO) << "ReadClientIntroductionFrame with channel name: "
- << channel->GetName()
- << ", medium: " << channel->GetMedium();
- CancelableAlarm timeout_alarm(
- "BwuManager::ReadClientIntroductionFrame",
- [channel]() {
- NEARBY_LOGS(ERROR) << "In BwuManager, failed to read the "
- "ClientIntroductionFrame after "
- << absl::FormatDuration(
- kReadClientIntroductionFrameTimeout)
- << ". Timing out and closing EndpointChannel "
- << channel->GetType();
- channel->Close();
- },
- kReadClientIntroductionFrameTimeout, &alarm_executor_);
- auto data = channel->Read();
- timeout_alarm.Cancel();
- if (!data.ok()) return false;
- auto transfer(parser::FromBytes(data.result()));
- if (!transfer.ok()) {
- NEARBY_LOGS(ERROR) << "In ReadClientIntroductionFrame, attempted to read a "
- "ClientIntroductionFrame from EndpointChannel "
- << channel->GetType()
- << " but was unable to obtain any OfflineFrame.";
- return false;
- }
- OfflineFrame frame = transfer.result();
- if (!frame.has_v1() || !frame.v1().has_bandwidth_upgrade_negotiation()) {
- NEARBY_LOGS(ERROR)
- << "In ReadClientIntroductionFrame, expected a "
- "BANDWIDTH_UPGRADE_NEGOTIATION v1 OfflineFrame but got a "
- << parser::GetFrameType(frame) << " frame instead.";
- return false;
- }
- if (frame.v1().bandwidth_upgrade_negotiation().event_type() !=
- BandwidthUpgradeNegotiationFrame::CLIENT_INTRODUCTION) {
- NEARBY_LOGS(ERROR)
- << "In ReadClientIntroductionFrame, expected a CLIENT_INTRODUCTION "
- "v1 OfflineFrame but got a BANDWIDTH_UPGRADE_NEGOTIATION frame "
- "with eventType "
- << frame.v1().bandwidth_upgrade_negotiation().event_type()
- << " instead.";
- return false;
- }
- const auto& frame_intro =
- frame.v1().bandwidth_upgrade_negotiation().client_introduction();
- introduction = frame_intro;
- return true;
-}
-
-bool BwuManager::ReadClientIntroductionAckFrame(EndpointChannel* channel) {
- NEARBY_LOGS(INFO) << "ReadClientIntroductionAckFrame with channel name: "
- << channel->GetName() << ", medium: "
- << proto::connections::Medium_Name(channel->GetMedium());
- CancelableAlarm timeout_alarm(
- "BwuManager::ReadClientIntroductionAckFrame",
- [channel]() {
- NEARBY_LOGS(ERROR)
- << "In BwuManager, failed to read the ClientIntroductionAckFrame "
- "after "
- << absl::FormatDuration(kReadClientIntroductionFrameTimeout)
- << ". Timing out and closing EndpointChannel "
- << channel->GetType();
- channel->Close();
- },
- kReadClientIntroductionFrameTimeout, &alarm_executor_);
- auto data = channel->Read();
- timeout_alarm.Cancel();
- if (!data.ok()) return false;
- auto transfer(parser::FromBytes(data.result()));
- if (!transfer.ok()) return false;
- OfflineFrame frame = transfer.result();
- if (!frame.has_v1() || !frame.v1().has_bandwidth_upgrade_negotiation())
- return false;
- if (frame.v1().bandwidth_upgrade_negotiation().event_type() !=
- BandwidthUpgradeNegotiationFrame::CLIENT_INTRODUCTION_ACK)
- return false;
- return true;
-}
-
-bool BwuManager::WriteClientIntroductionAckFrame(EndpointChannel* channel) {
- NEARBY_LOGS(INFO) << "WriteClientIntroductionAckFrame channel name: "
- << channel->GetName()
- << ", medium: " << channel->GetMedium();
- return channel->Write(parser::ForBwuIntroductionAck()).Ok();
-}
-
-void BwuManager::ProcessLastWriteToPriorChannelEvent(
- ClientProxy* client, const std::string& endpoint_id) {
- NEARBY_LOGS(INFO) << "ProcessLastWriteToPriorChannelEvent for endpoint "
- << endpoint_id;
- // By this point in the upgrade protocol, there is the guarantee that both
- // involved endpoints have registered a new EndpointChannel with the
- // EndpointChannelManager as the official channel for communication; given
- // the way communication is structured in the EndpointManager, this means
- // that all new writes are happening over that new EndpointChannel, but
- // reads are still happening over this prior EndpointChannel (to avoid data
- // loss). But now that we've received this definitive final write over that
- // prior EndpointChannel, we can let the remote device that they can safely
- // close their end of this now-dormant EndpointChannel.
- EndpointChannel* previous_endpoint_channel =
- previous_endpoint_channels_[endpoint_id].get();
- if (!previous_endpoint_channel) {
- NEARBY_LOGS(ERROR)
- << "BwuManager received a BWU_NEGOTIATION.LAST_WRITE_TO_PRIOR_CHANNEL "
- "OfflineFrame for unknown endpoint "
- << endpoint_id << ", can't complete the upgrade protocol.";
- successfully_upgraded_endpoints_.emplace(endpoint_id);
- return;
- }
-
- if (!previous_endpoint_channel->Write(parser::ForBwuSafeToClose()).Ok()) {
- previous_endpoint_channel->Close(DisconnectionReason::IO_ERROR);
- // Remove this prior EndpointChannel from previous_endpoint_channels to
- // avoid leaks.
- previous_endpoint_channels_.erase(endpoint_id);
-
- NEARBY_LOGS(ERROR) << "BwuManager failed to write "
- "BWU_NEGOTIATION.SAFE_TO_CLOSE_PRIOR_CHANNEL "
- "OfflineFrame to endpoint "
- << endpoint_id
- << ", short-circuiting the upgrade protocol.";
- client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
- endpoint_id, proto::connections::RESULT_IO_ERROR,
- proto::connections::SAFE_TO_CLOSE_PRIOR_CHANNEL);
- return;
- }
- NEARBY_LOGS(VERBOSE) << "BwuManager successfully wrote "
- "BWU_NEGOTIATION.SAFE_TO_CLOSE_PRIOR_CHANNEL "
- "OfflineFrame while trying to upgrade endpoint "
- << endpoint_id;
-
- // The upgrade protocol's clean shutdown of the prior EndpointChannel will
- // conclude when we receive a corresponding
- // BANDWIDTH_UPGRADE_NEGOTIATION.SAFE_TO_CLOSE_PRIOR_CHANNEL OfflineFrame
- // from the remote device.
-}
-
-void BwuManager::ProcessSafeToClosePriorChannelEvent(
- ClientProxy* client, const std::string& endpoint_id) {
- NEARBY_LOGS(INFO) << "ProcessSafeToClosePriorChannelEvent for endpoint "
- << endpoint_id;
- // By this point in the upgrade protocol, there's no more writes happening
- // over the prior EndpointChannel, and the remote device has given us the
- // go-ahead to close this EndpointChannel [1], so we can safely close it
- // (and depend on the EndpointManager querying the EndpointChannelManager to
- // start reading from the new EndpointChannel).
- //
- // [1] Which also implies that they've received our
- // BANDWIDTH_UPGRADE_NEGOTIATION.LAST_WRITE_TO_PRIOR_CHANNEL OfflineFrame),
- // so there can be no data loss, regardless of whether the EndpointChannel
- // allows reads of queued, unread data after the EndpointChannel has been
- // closed from the other end (as is the case with conventional TCP sockets)
- // or not (as is the case with Android's Bluetooth sockets, where closing
- // instantly throws an IOException on the remote device).
- auto item = previous_endpoint_channels_.extract(endpoint_id);
- auto& previous_endpoint_channel = item.mapped();
- if (previous_endpoint_channel == nullptr) {
- NEARBY_LOGS(ERROR)
- << "BwuManager received a BWU_NEGOTIATION.SAFE_TO_CLOSE_PRIOR_CHANNEL "
- "OfflineFrame for unknown endpoint "
- << endpoint_id << ", can't complete the upgrade protocol.";
- return;
- }
- NEARBY_LOGS(INFO)
- << "BwuManager successfully received a "
- << "BWU_NEGOTIATION.SAFE_TO_CLOSE_PRIOR_CHANNEL OfflineFrame while "
- << "trying to upgrade endpoint " << endpoint_id;
-
- // Each encrypted message includes the key to decrypt the next message. The
- // disconnect message is optional and may not be received under normal
- // circumstances so it is necessary to send it unencrypted. This way the
- // serial crypto context does not increment here.
- previous_endpoint_channel->DisableEncryption();
- previous_endpoint_channel->Write(parser::ForDisconnection());
-
- // Attempt to read the disconnect message from the previous channel. We don't
- // care whether we successfully read it or whether we get an exception here.
- // The idea is just to make sure the other side has had a chance to receive
- // the full SAFE_TO_CLOSE_PRIOR_CHANNEL message before we actually close the
- // channel. See b/172380349 for more context.
- previous_endpoint_channel->Read();
- previous_endpoint_channel->Close(DisconnectionReason::UPGRADED);
-
- NEARBY_LOGS(VERBOSE)
- << "BwuManager cleanly shut down prior "
- << previous_endpoint_channel->GetType()
- << " EndpointChannel to conclude upgrade protocol for endpoint "
- << endpoint_id;
-
- // Now the upgrade protocol has completed, record analytics for this new
- // upgraded bandwidth connection...
- client->GetAnalyticsRecorder().OnConnectionEstablished(
- endpoint_id, medium_, client->GetConnectionToken(endpoint_id));
- // ...and the success of the upgrade itself.
- client->GetAnalyticsRecorder().OnBandwidthUpgradeSuccess(endpoint_id);
-
- // Now that the old channel has been drained, we can unpause the new channel
- std::shared_ptr<EndpointChannel> channel =
- channel_manager_->GetChannelForEndpoint(endpoint_id);
-
- if (!channel) {
- NEARBY_LOGS(ERROR) << "BwuManager attempted to resume the current "
- "EndpointChannel with endpoint "
- << endpoint_id << ", but none was found.";
- return;
- }
-
- channel->Resume();
-
- // Report the success to the client
- client->OnBandwidthChanged(endpoint_id, channel->GetMedium());
- in_progress_upgrades_.erase(endpoint_id);
-}
-
-void BwuManager::ProcessUpgradeFailureEvent(
- ClientProxy* client, const std::string& endpoint_id,
- const UpgradePathInfo& upgrade_info) {
- NEARBY_LOGS(INFO) << "ProcessUpgradeFailureEvent for endpoint " << endpoint_id
- << " from medium: "
- << parser::UpgradePathInfoMediumToMedium(
- upgrade_info.medium());
- // The remote device failed to upgrade to the new medium we set up for them.
- // That's alright! We'll just try the next available medium (if there is
- // one).
- in_progress_upgrades_.erase(endpoint_id);
-
- // The first thing we have to do is to replace our
- // currentBwuMedium with the next best upgrade medium we share
- // with the remote device. The catch is that we can only do this if we only
- // have one connected endpoint. Otherwise, we'll end up disrupting our other
- // connected peers.
- if (channel_manager_->GetConnectedEndpointsCount() > 1) {
- // We can't change the currentBwuMedium, so there are no more
- // upgrade attempts for this endpoint. Sorry.
- NEARBY_LOGS(ERROR)
- << "BwuManager failed to attempt a new bandwidth upgrade for endpoint "
- << endpoint_id
- << " because we have other connected endpoints and can't try a new "
- "upgrade medium.";
- client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
- endpoint_id, proto::connections::CHANNEL_ERROR,
- proto::connections::NETWORK_AVAILABLE);
- return;
- }
-
- // Revert the existing upgrade medium for now.
- if (medium_ != Medium::UNKNOWN_MEDIUM) {
- Revert();
- }
-
- // Loop through the ordered list of upgrade mediums. One by one, remove the
- // top element until we get to the medium we last attempted to upgrade to.
- // The remainder of the list will contain the mediums we haven't attempted
- // yet.
- Medium last = parser::UpgradePathInfoMediumToMedium(upgrade_info.medium());
- std::vector<Medium> all_possible_mediums =
- client->GetUpgradeMediums(endpoint_id).GetMediums(true);
- std::vector<Medium> untried_mediums(all_possible_mediums);
- for (Medium medium : all_possible_mediums) {
- untried_mediums.erase(untried_mediums.begin());
- if (medium == last) {
- break;
- }
- }
-
- RetryUpgradeMediums(client, endpoint_id, untried_mediums);
-}
-
-void BwuManager::RetryUpgradeMediums(ClientProxy* client,
- const std::string& endpoint_id,
- std::vector<Medium> upgrade_mediums) {
- Medium next_medium = ChooseBestUpgradeMedium(upgrade_mediums);
- NEARBY_LOGS(INFO) << "RetryUpgradeMediums for endpoint " << endpoint_id
- << " after ChooseBestUpgradeMedium: " << next_medium;
-
- // If current medium is not WiFi and we have not succeeded with upgrading
- // yet, retry upgrade.
- Medium current_medium = GetEndpointMedium(endpoint_id);
- if (current_medium != Medium::WIFI_LAN &&
- (next_medium == current_medium || next_medium == Medium::UNKNOWN_MEDIUM ||
- upgrade_mediums.empty())) {
- RetryUpgradesAfterDelay(client, endpoint_id);
- return;
- }
-
- // Attempt to set the new upgrade medium.
- if (!SetCurrentBwuHandler(next_medium)) {
- NEARBY_LOGS(INFO)
- << "BwuManager failed to attempt a new bandwidth upgrade for endpoint "
- << endpoint_id
- << " because we couldn't set a new bandwidth upgrade medium.";
- return;
- }
-
- // Now that we've successfully picked a new upgrade medium to try,
- // re-initiate the bandwidth upgrade.
- NEARBY_LOGS(INFO) << "BwuManager is attempting to upgrade endpoint "
- << endpoint_id
- << " again with a new bandwidth upgrade medium.";
- InitiateBwuForEndpoint(client, endpoint_id, next_medium);
-}
-
-std::vector<Medium> BwuManager::StripOutUnavailableMediums(
- const std::vector<Medium>& mediums) {
- std::vector<Medium> available_mediums;
- for (Medium m : mediums) {
- bool available = false;
- switch (m) {
- case Medium::WIFI_LAN:
- available = mediums_->GetWifiLan().IsAvailable();
- break;
- case Medium::WEB_RTC:
- available = mediums_->GetWebRtc().IsAvailable();
- break;
- case Medium::BLUETOOTH:
- available = mediums_->GetBluetoothClassic().IsAvailable();
- break;
- default:
- break;
- }
- if (available) {
- available_mediums.push_back(m);
- }
- }
- return available_mediums;
-}
-
-// Returns the optimal medium supported by both devices.
-// Each medium in the passed in list is checked for its availability with the
-// medium_manager_ to ensure that the chosen upgrade medium is supported and
-// available locally before continuing the upgrade. Once we pick a medium, all
-// future connections will use it too. eg. If we chose Wifi LAN, we'll attempt
-// to upgrade the 2nd, 3rd, etc remote endpoints with Wifi LAN even if they're
-// on a different network (or had a better medium). This is a quick and easy
-// way to prevent mediums, like Wifi Hotspot, from interfering with active
-// connections (although it's suboptimal for bandwidth throughput). When all
-// endpoints disconnect, we reset the bandwidth upgrade medium.
-Medium BwuManager::ChooseBestUpgradeMedium(const std::vector<Medium>& mediums) {
- auto available_mediums = StripOutUnavailableMediums(mediums);
- if (medium_ == Medium::UNKNOWN_MEDIUM) {
- if (!available_mediums.empty()) {
- // Case 1: This is our first time upgrading, and we have at least one
- // supported medium to choose from. Return the first medium in the list,
- // since they are ordered by preference.
- return available_mediums[0];
- }
- // Case 2: This is our first time upgrading, but there are no available
- // upgrade mediums. Fall through to returning UNKNOWN_MEDIUM at the
- // bottom.
- NEARBY_LOGS(INFO)
- << "Current upgrade medium is unset, but there are no common supported "
- "upgrade mediums.";
- } else {
- // Case 3: We have already upgraded, and there is a list of supported
- // mediums to check against. Return the current upgrade medium if it's in
- // the supported list.
- if (std::find(available_mediums.begin(), available_mediums.end(),
- medium_) != available_mediums.end()) {
- return medium_;
- }
- // Case 4: We have already upgraded, but the current medium is not
- // supported by the remote endpoint (it's not in the list, or the list is
- // empty). Fall through and return Medium.UNKNOWN_MEDIUM because we cannot
- // continue with the current upgrade medium, and we are not allowed to
- // switch.
- std::string mediums_string;
- for (const auto& medium : available_mediums) {
- absl::StrAppend(&mediums_string, proto::connections::Medium_Name(medium),
- "; ");
- }
- NEARBY_LOGS(INFO)
- << "Current upgrade medium " << proto::connections::Medium_Name(medium_)
- << " is not supported by the remote endpoint (supported mediums: "
- << mediums_string << ")";
- }
-
- return Medium::UNKNOWN_MEDIUM;
-}
-
-void BwuManager::RetryUpgradesAfterDelay(ClientProxy* client,
- const std::string& endpoint_id) {
- absl::Duration delay = CalculateNextRetryDelay(endpoint_id);
- CancelRetryUpgradeAlarm(endpoint_id);
- CancelableAlarm alarm(
- "BWU alarm",
- [this, client, endpoint_id]() {
- RunOnBwuManagerThread(
- "bwu-retry-upgrade", [this, client, endpoint_id]() {
- if (!client->IsConnectedToEndpoint(endpoint_id)) {
- return;
- }
- RetryUpgradeMediums(
- client, endpoint_id,
- client->GetUpgradeMediums(endpoint_id).GetMediums(true));
- });
- },
- delay, &alarm_executor_);
-
- retry_upgrade_alarms_.emplace(endpoint_id,
- std::make_pair(std::move(alarm), delay));
- retry_delays_[endpoint_id] = delay;
- NEARBY_LOGS(INFO) << "Retry bandwidth upgrade after "
- << absl::FormatDuration(delay);
-}
-
-void BwuManager::AttemptToRecordBandwidthUpgradeErrorForUnknownEndpoint(
- proto::connections::BandwidthUpgradeResult result,
- proto::connections::BandwidthUpgradeErrorStage error_stage) {
- if (in_progress_upgrades_.size() == 1) {
- auto it = in_progress_upgrades_.begin();
- std::string endpoint_id = it->first;
- ClientProxy* client = it->second;
- // Note: Even though we know this is an error, we cannot clear state yet.
- // We've sent the remote device the credentials they need and it's up to
- // them if they want to repeatedly attempt to connect or if they want to
- // give up and have us try a different medium. This isn't a decision we can
- // make for them.
- client->GetAnalyticsRecorder().OnBandwidthUpgradeError(endpoint_id, result,
- error_stage);
- NEARBY_LOGS(INFO) << "BwuManager got error "
- << proto::connections::BandwidthUpgradeResult_Name(result)
- << " at stage "
- << proto::connections::BandwidthUpgradeErrorStage_Name(
- error_stage)
- << " when upgrading endpoint " << endpoint_id;
- }
- // Otherwise, we have no way of knowing which endpoint was trying to connect
- // to us :(
- NEARBY_LOGS(INFO) << "BwuManager got error "
- << proto::connections::BandwidthUpgradeResult_Name(result)
- << " at stage "
- << proto::connections::BandwidthUpgradeErrorStage_Name(
- error_stage)
- << ", but we don't know which endpoint was trying to "
- "connect to us, so skipping analytics for his error.";
-}
-
-absl::Duration BwuManager::CalculateNextRetryDelay(
- const std::string& endpoint_id) {
- auto item = retry_delays_.find(endpoint_id);
- auto initial_delay = config_.bandwidth_upgrade_retry_delay;
- if (item == retry_delays_.end()) return initial_delay;
- /*
- * Without use_exp_backoff_in_bwu_retry, bwu retry intervals for the same
- * endpoint_id in seconds will be like: 5, 10, 10, 10...
- * With use_exp_backoff_in_bwu_retry enabled, bwu retry intervals in seconds
- * would be like: 3, 6, 12, 24, ... 300, 300, ...
- */
- auto delay =
- FeatureFlags::GetInstance().GetFlags().use_exp_backoff_in_bwu_retry
- ? item->second * 2
- : item->second + initial_delay;
- return std::min(delay, config_.bandwidth_upgrade_retry_max_delay);
-}
-
-void BwuManager::CancelRetryUpgradeAlarm(const std::string& endpoint_id) {
- NEARBY_LOGS(INFO) << "CancelRetryUpgradeAlarm for endpoint " << endpoint_id;
- auto item = retry_upgrade_alarms_.extract(endpoint_id);
- if (item.empty()) return;
- auto& pair = item.mapped();
- pair.first.Cancel();
-}
-
-void BwuManager::CancelAllRetryUpgradeAlarms() {
- NEARBY_LOGS(INFO) << "CancelAllRetryUpgradeAlarms invoked";
- for (auto& item : retry_upgrade_alarms_) {
- const std::string& endpoint_id = item.first;
- CancelableAlarm& cancellable_alarm = item.second.first;
- NEARBY_LOGS(INFO) << "CancelRetryUpgradeAlarm for endpoint " << endpoint_id;
- cancellable_alarm.Cancel();
- }
- retry_upgrade_alarms_.clear();
- retry_delays_.clear();
-}
-
-Medium BwuManager::GetEndpointMedium(const std::string& endpoint_id) {
- auto channel = channel_manager_->GetChannelForEndpoint(endpoint_id);
- return channel == nullptr ? Medium::UNKNOWN_MEDIUM : channel->GetMedium();
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/bwu_manager.h b/chromium/third_party/nearby/src/cpp/core/internal/bwu_manager.h
deleted file mode 100644
index b304a49a587..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/bwu_manager.h
+++ /dev/null
@@ -1,203 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_BWU_MANAGER_H_
-#define CORE_INTERNAL_BWU_MANAGER_H_
-
-#include <memory>
-#include <string>
-#include <vector>
-
-#include "absl/container/flat_hash_map.h"
-#include "absl/container/flat_hash_set.h"
-#include "absl/time/time.h"
-#include "core/internal/bwu_handler.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/endpoint_manager.h"
-#include "core/internal/mediums/mediums.h"
-#include "core/options.h"
-#include "platform/base/byte_array.h"
-#include "platform/public/scheduled_executor.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Base class for managing the upgrade of endpoints to a different medium for
-// communication (from whatever they were previously using).
-//
-// The sequencing of the upgrade protocol is as follows:
-// - Initiator sets up an upgrade path, sends
-// BANDWIDTH_UPGRADE_NEGOTIATION.UPGRADE_PATH_AVAILABLE to Responder over
-// the prior EndpointChannel.
-// - Responder joins the upgrade path, sends (possibly without encryption)
-// BANDWIDTH_UPGRADE_NEGOTIATION.CLIENT_INTRODUCTION over the new
-// EndpointChannel, and sends
-// BANDWIDTH_UPGRADE_NEGOTIATION.LAST_WRITE_TO_PRIOR_CHANNEL over the
-// prior EndpointChannel.
-// - Initiator receives BANDWIDTH_UPGRADE_NEGOTIATION.CLIENT_INTRODUCTION
-// over the newly-established EndpointChannel, and sends
-// BANDWIDTH_UPGRADE_NEGOTIATION.LAST_WRITE_TO_PRIOR_CHANNEL over the
-// prior EndpointChannel.
-// - Both wait to receive
-// BANDWIDTH_UPGRADE_NEGOTIATION.LAST_WRITE_TO_PRIOR_CHANNEL from the
-// other, and upon doing so, send
-// BANDWIDTH_UPGRADE_NEGOTIATION.SAFE_TO_CLOSE_PRIOR_CHANNEL to each other
-// - Both then wait to receive
-// BANDWIDTH_UPGRADE_NEGOTIATION.SAFE_TO_CLOSE_PRIOR_CHANNEL from the
-// other, and upon doing so, close the prior EndpointChannel.
-class BwuManager : public EndpointManager::FrameProcessor {
- public:
- using UpgradePathInfo = BwuHandler::UpgradePathInfo;
-
- struct Config {
- BooleanMediumSelector allow_upgrade_to;
- absl::Duration bandwidth_upgrade_retry_delay;
- absl::Duration bandwidth_upgrade_retry_max_delay;
- };
-
- BwuManager(Mediums& mediums, EndpointManager& endpoint_manager,
- EndpointChannelManager& channel_manager,
- absl::flat_hash_map<Medium, std::unique_ptr<BwuHandler>> handlers,
- Config config);
-
- ~BwuManager() override;
-
- // This is the point on the outbound BWU protocol where the handler_ is set.
- // Function initiates the bandwidth upgrade and sends an
- // UPGRADE_PATH_AVAILABLE OfflineFrame.
- void InitiateBwuForEndpoint(ClientProxy* client_proxy,
- const std::string& endpoint_id,
- Medium new_medium = Medium::UNKNOWN_MEDIUM);
-
- // == EndpointManager::FrameProcessor interface ==.
- // This is the point on the inbound BWU protocol where the handler_ is set.
- // This is also an entry point for handling messages for both outbound and
- // inbound BWU protocol.
- // @EndpointManagerReaderThread
- void OnIncomingFrame(OfflineFrame& frame, const std::string& endpoint_id,
- ClientProxy* client, Medium medium) override;
-
- // Cleans up in-progress upgrades after endpoint disconnection.
- // @EndpointManagerReaderThread
- void OnEndpointDisconnect(ClientProxy* client_proxy,
- const std::string& endpoint_id,
- CountDownLatch barrier) override;
- void Shutdown();
-
- private:
- static constexpr absl::Duration kReadClientIntroductionFrameTimeout =
- absl::Seconds(5);
- BwuHandler* SetCurrentBwuHandler(Medium medium);
- void InitBwuHandlers();
- void RunOnBwuManagerThread(const std::string& name,
- std::function<void()> runnable);
- std::vector<Medium> StripOutUnavailableMediums(
- const std::vector<Medium>& mediums);
- Medium ChooseBestUpgradeMedium(const std::vector<Medium>& mediums);
-
- // BaseBwuHandler
- using ClientIntroduction = BwuNegotiationFrame::ClientIntroduction;
-
- // Processes the BwuNegotiationFrames that come over the
- // EndpointChannel on both initiator and responder side of the upgrade.
- void OnBwuNegotiationFrame(ClientProxy* client,
- const BwuNegotiationFrame frame,
- const string& endpoint_id);
-
- // Called to revert any state changed by the Initiator or Responder in the
- // course of setting up the upgraded medium for an endpoint.
- void Revert();
-
- // Common functionality to take an incoming connection and go through the
- // upgrade process. This is a callback, invoked by concrete handlers, once
- // connection is available.
- void OnIncomingConnection(
- ClientProxy* client,
- std::unique_ptr<BwuHandler::IncomingSocketConnection> mutable_connection);
-
- void RunUpgradeProtocol(ClientProxy* client, const std::string& endpoint_id,
- std::unique_ptr<EndpointChannel> new_channel);
- void RunUpgradeFailedProtocol(ClientProxy* client,
- const std::string& endpoint_id,
- const UpgradePathInfo& upgrade_path_info);
- void ProcessBwuPathAvailableEvent(ClientProxy* client,
- const std::string& endpoint_id,
- const UpgradePathInfo& upgrade_path_info);
- std::unique_ptr<EndpointChannel> ProcessBwuPathAvailableEventInternal(
- ClientProxy* client, const std::string& endpoint_id,
- const UpgradePathInfo& upgrade_path_info);
- void ProcessLastWriteToPriorChannelEvent(ClientProxy* client,
- const std::string& endpoint_id);
- void ProcessSafeToClosePriorChannelEvent(ClientProxy* client,
- const std::string& endpoint_id);
- bool ReadClientIntroductionFrame(EndpointChannel* endpoint_channel,
- ClientIntroduction& introduction);
- bool ReadClientIntroductionAckFrame(EndpointChannel* endpoint_channel);
- bool WriteClientIntroductionAckFrame(EndpointChannel* endpoint_channel);
- void ProcessEndpointDisconnection(ClientProxy* client,
- const std::string& endpoint_id,
- CountDownLatch* barrier);
- void ProcessUpgradeFailureEvent(ClientProxy* client,
- const std::string& endpoint_id,
- const UpgradePathInfo& upgrade_info);
- void CancelRetryUpgradeAlarm(const std::string& endpoint_id);
- void CancelAllRetryUpgradeAlarms();
- void RetryUpgradeMediums(ClientProxy* client, const std::string& endpoint_id,
- std::vector<Medium> upgrade_mediums);
- Medium GetEndpointMedium(const std::string& endpoint_id);
- absl::Duration CalculateNextRetryDelay(const std::string& endpoint_id);
- void RetryUpgradesAfterDelay(ClientProxy* client,
- const std::string& endpoint_id);
- void AttemptToRecordBandwidthUpgradeErrorForUnknownEndpoint(
- proto::connections::BandwidthUpgradeResult result,
- proto::connections::BandwidthUpgradeErrorStage error_stage);
-
- Config config_;
-
- Medium medium_ = Medium::UNKNOWN_MEDIUM;
- BwuHandler* handler_ = nullptr;
- Mediums* mediums_;
- absl::flat_hash_map<Medium, std::unique_ptr<BwuHandler>> handlers_;
-
- EndpointManager* endpoint_manager_;
- EndpointChannelManager* channel_manager_;
- ScheduledExecutor alarm_executor_;
- SingleThreadExecutor serial_executor_;
- // Stores each upgraded endpoint's previous EndpointChannel (that was
- // displaced in favor of a new EndpointChannel) temporarily, until it can
- // safely be shut down for good in processLastWriteToPriorChannelEvent().
- absl::flat_hash_map<std::string, std::shared_ptr<EndpointChannel>>
- previous_endpoint_channels_;
- absl::flat_hash_set<std::string> successfully_upgraded_endpoints_;
- // Maps endpointId -> ClientProxy for which
- // initiateBwuForEndpoint() has been called but which have not
- // yet completed the upgrade via onIncomingConnection().
- absl::flat_hash_map<std::string, ClientProxy*> in_progress_upgrades_;
- // Maps endpointId -> timestamp of when the SAFE_TO_CLOSE message was written.
- absl::flat_hash_map<std::string, absl::Time> safe_to_close_write_timestamps_;
- absl::flat_hash_map<std::string, std::pair<CancelableAlarm, absl::Duration>>
- retry_upgrade_alarms_;
- // Maps endpointId -> duration of delay before bwu retry.
- // When bwu failed, retry_upgrade_alarms_ will clear the entry before the
- // retry happen, then we can not find the last delay used in the alarm. Thus
- // using a different map to keep track of the delays per endpoint.
- absl::flat_hash_map<std::string, absl::Duration> retry_delays_;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_BWU_MANAGER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/bwu_manager_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/bwu_manager_test.cc
deleted file mode 100644
index 050a4563cd1..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/bwu_manager_test.cc
+++ /dev/null
@@ -1,110 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/bwu_manager.h"
-
-#include <string>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/time/time.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/endpoint_channel_manager.h"
-#include "core/internal/endpoint_manager.h"
-#include "core/internal/mediums/mediums.h"
-#include "core/internal/mediums/utils.h"
-#include "core/internal/offline_frames.h"
-#include "platform/public/system_clock.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-
-TEST(BwuManagerTest, CanCreateInstance) {
- Mediums mediums;
- EndpointChannelManager ecm;
- EndpointManager em{&ecm};
- BwuManager bwu_manager{mediums, em, ecm, {}, {}};
-
- SystemClock::Sleep(absl::Seconds(3));
-
- bwu_manager.Shutdown();
-}
-
-TEST(BwuManagerTest, CanInitiateBwu) {
- ClientProxy client;
- std::string endpoint_id("EP_A");
- Mediums mediums;
- EndpointChannelManager ecm;
- EndpointManager em{&ecm};
- BwuManager bwu_manager{mediums, em, ecm, {}, {}};
-
- // Method returns void, so we just verify we did not SEGFAULT while calling.
- bwu_manager.InitiateBwuForEndpoint(&client, endpoint_id);
- SystemClock::Sleep(absl::Seconds(3));
-
- bwu_manager.Shutdown();
-}
-
-TEST(BwuManagerTest, CanProcessBandwidthUpgradeFrames) {
- ClientProxy client;
- std::string endpoint_id("EP_A");
- LocationHint location_hint = Utils::BuildLocationHint("US");
- Mediums mediums;
- EndpointChannelManager ecm;
- EndpointManager em{&ecm};
- BwuManager bwu_manager{mediums, em, ecm, {}, {}};
-
- ExceptionOr<OfflineFrame> path_available_frame = parser::FromBytes(
- parser::ForBwuWebrtcPathAvailable("my_id", location_hint));
- bwu_manager.OnIncomingFrame(path_available_frame.result(), endpoint_id,
- &client, Medium::WEB_RTC);
-
- ExceptionOr<OfflineFrame> last_write_frame =
- parser::FromBytes(parser::ForBwuLastWrite());
- bwu_manager.OnIncomingFrame(last_write_frame.result(), endpoint_id, &client,
- Medium::WEB_RTC);
-
- ExceptionOr<OfflineFrame> safe_to_close_frame =
- parser::FromBytes(parser::ForBwuSafeToClose());
- bwu_manager.OnIncomingFrame(safe_to_close_frame.result(), endpoint_id,
- &client, Medium::WEB_RTC);
-
- bwu_manager.Shutdown();
-}
-
-TEST(BwuManagerTest, InitiateBwu_UpgradeFails_NoCrash) {
- ClientProxy client;
- std::string endpoint_id("EP_A");
- Mediums mediums;
- EndpointChannelManager ecm;
- EndpointManager em{&ecm};
- BwuManager bwu_manager{mediums, em, ecm, {}, {}};
- parser::UpgradePathInfo upgrade_path_info;
- upgrade_path_info.set_medium(parser::UpgradePathInfo::WEB_RTC);
-
- bwu_manager.InitiateBwuForEndpoint(&client, endpoint_id);
- ExceptionOr<OfflineFrame> bwu_failed_frame =
- parser::FromBytes(parser::ForBwuFailure(upgrade_path_info));
- bwu_manager.OnIncomingFrame(bwu_failed_frame.result(), endpoint_id, &client,
- Medium::WEB_RTC);
-
- bwu_manager.Shutdown();
-}
-
-} // namespace
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/client_proxy.cc b/chromium/third_party/nearby/src/cpp/core/internal/client_proxy.cc
deleted file mode 100644
index 031832cbad7..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/client_proxy.cc
+++ /dev/null
@@ -1,774 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/client_proxy.h"
-
-#include <cstdlib>
-#include <functional>
-#include <limits>
-#include <string>
-#include <utility>
-
-#include "absl/container/flat_hash_map.h"
-#include "absl/container/flat_hash_set.h"
-#include "absl/strings/escaping.h"
-#include "absl/strings/str_cat.h"
-#include "platform/base/error_code_recorder.h"
-#include "platform/base/feature_flags.h"
-#include "platform/base/prng.h"
-#include "platform/public/logging.h"
-#include "platform/public/mutex_lock.h"
-#include "proto/connections_enums.pb.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// The definition is necessary before C++17.
-constexpr absl::Duration
- ClientProxy::kHighPowerAdvertisementEndpointIdCacheTimeout;
-
-constexpr char kEndpointIdChars[] = {
- 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
- 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
- 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
-
-ClientProxy::ClientProxy(analytics::EventLogger* event_logger)
- : client_id_(Prng().NextInt64()) {
- NEARBY_LOGS(INFO) << "ClientProxy ctor event_logger=" << event_logger;
- analytics_recorder_ =
- std::make_unique<analytics::AnalyticsRecorder>(event_logger);
- error_code_recorder_ = std::make_unique<ErrorCodeRecorder>(
- [this](const ErrorCodeParams& params) {
- analytics_recorder_->OnErrorCode(params);
- });
-}
-
-ClientProxy::~ClientProxy() { Reset(); }
-
-std::int64_t ClientProxy::GetClientId() const { return client_id_; }
-
-std::string ClientProxy::GetLocalEndpointId() {
- MutexLock lock(&mutex_);
- if (local_endpoint_id_.empty()) {
- local_endpoint_id_ = GenerateLocalEndpointId();
- NEARBY_LOGS(INFO) << "ClientProxy [Local Endpoint Generated]: client="
- << GetClientId()
- << "; endpoint_id=" << local_endpoint_id_;
- }
- return local_endpoint_id_;
-}
-
-std::string ClientProxy::GetConnectionToken(const std::string& endpoint_id) {
- Connection* item = LookupConnection(endpoint_id);
- if (item != nullptr) {
- return item->connection_token;
- }
- return {};
-}
-
-std::string ClientProxy::GenerateLocalEndpointId() {
- if (high_vis_mode_) {
- if (!local_high_vis_mode_cache_endpoint_id_.empty()) {
- NEARBY_LOGS(INFO)
- << "ClientProxy [Local Endpoint Re-using cached endpoint id]: client="
- << GetClientId() << "; local_high_vis_mode_cache_endpoint_id_="
- << local_high_vis_mode_cache_endpoint_id_;
- return local_high_vis_mode_cache_endpoint_id_;
- }
- }
- std::string id;
- for (int i = 0; i < kEndpointIdLength; i++) {
- id += kEndpointIdChars[prng_.NextUint32() % sizeof(kEndpointIdChars)];
- }
- return id;
-}
-
-void ClientProxy::Reset() {
- MutexLock lock(&mutex_);
-
- StoppedAdvertising();
- StoppedDiscovery();
- RemoveAllEndpoints();
- ExitHighVisibilityMode();
- analytics_recorder_->LogSession();
-}
-
-void ClientProxy::StartedAdvertising(
- const std::string& service_id, Strategy strategy,
- const ConnectionListener& listener,
- absl::Span<proto::connections::Medium> mediums,
- const ConnectionOptions& advertising_options) {
- MutexLock lock(&mutex_);
- NEARBY_LOGS(INFO) << "ClientProxy [StartedAdvertising]: client="
- << GetClientId();
-
- if (high_vis_mode_) {
- local_high_vis_mode_cache_endpoint_id_ = local_endpoint_id_;
- NEARBY_LOGS(INFO)
- << "ClientProxy [High Visibility Mode Adv, Cache EndpointId]: client="
- << GetClientId() << "; local_high_vis_mode_cache_endpoint_id_="
- << local_high_vis_mode_cache_endpoint_id_;
- CancelClearLocalHighVisModeCacheEndpointIdAlarm();
- }
-
- advertising_info_ = {service_id, listener};
- advertising_options_ = advertising_options;
-
- const std::vector<proto::connections::Medium> medium_vector(mediums.begin(),
- mediums.end());
- analytics_recorder_->OnStartAdvertising(strategy, medium_vector);
-}
-
-void ClientProxy::StoppedAdvertising() {
- MutexLock lock(&mutex_);
- NEARBY_LOGS(INFO) << "ClientProxy [StoppedAdvertising]: client="
- << GetClientId();
-
- if (IsAdvertising()) {
- advertising_info_.Clear();
- analytics_recorder_->OnStopAdvertising();
- }
- // advertising_options_ is purposefully not cleared here.
- ResetLocalEndpointIdIfNeeded();
-
- ExitHighVisibilityMode();
-}
-
-bool ClientProxy::IsAdvertising() const {
- MutexLock lock(&mutex_);
-
- return !advertising_info_.IsEmpty();
-}
-
-std::string ClientProxy::GetAdvertisingServiceId() const {
- MutexLock lock(&mutex_);
- return advertising_info_.service_id;
-}
-
-std::string ClientProxy::GetServiceId() const {
- MutexLock lock(&mutex_);
- if (IsAdvertising()) return advertising_info_.service_id;
- if (IsDiscovering()) return discovery_info_.service_id;
- return "idle_service_id";
-}
-
-void ClientProxy::StartedDiscovery(
- const std::string& service_id, Strategy strategy,
- const DiscoveryListener& listener,
- absl::Span<proto::connections::Medium> mediums,
- const ConnectionOptions& discovery_options) {
- MutexLock lock(&mutex_);
- discovery_info_ = DiscoveryInfo{service_id, listener};
- discovery_options_ = discovery_options;
-
- const std::vector<proto::connections::Medium> medium_vector(mediums.begin(),
- mediums.end());
- analytics_recorder_->OnStartDiscovery(strategy, medium_vector);
-}
-
-void ClientProxy::StoppedDiscovery() {
- MutexLock lock(&mutex_);
-
- if (IsDiscovering()) {
- discovered_endpoint_ids_.clear();
- discovery_info_.Clear();
- analytics_recorder_->OnStopDiscovery();
- }
- // discovery_options_ is purposefully not cleared here.
- ResetLocalEndpointIdIfNeeded();
-}
-
-bool ClientProxy::IsDiscoveringServiceId(const std::string& service_id) const {
- MutexLock lock(&mutex_);
-
- return IsDiscovering() && service_id == discovery_info_.service_id;
-}
-
-bool ClientProxy::IsDiscovering() const {
- MutexLock lock(&mutex_);
-
- return !discovery_info_.IsEmpty();
-}
-
-std::string ClientProxy::GetDiscoveryServiceId() const {
- MutexLock lock(&mutex_);
-
- return discovery_info_.service_id;
-}
-
-void ClientProxy::OnEndpointFound(const std::string& service_id,
- const std::string& endpoint_id,
- const ByteArray& endpoint_info,
- proto::connections::Medium medium) {
- MutexLock lock(&mutex_);
-
- NEARBY_LOGS(INFO) << "ClientProxy [Endpoint Found]: [enter] id="
- << endpoint_id << "; service=" << service_id << "; info="
- << absl::BytesToHexString(endpoint_info.data());
- if (!IsDiscoveringServiceId(service_id)) {
- NEARBY_LOGS(INFO) << "ClientProxy [Endpoint Found]: Ignoring event for id="
- << endpoint_id
- << " because this client is not discovering.";
- return;
- }
-
- if (discovered_endpoint_ids_.count(endpoint_id)) {
- NEARBY_LOGS(WARNING)
- << "ClientProxy [Endpoint Found]: Ignoring event for id=" << endpoint_id
- << " because this client has already reported this endpoint as found.";
- return;
- }
-
- discovered_endpoint_ids_.insert(endpoint_id);
- discovery_info_.listener.endpoint_found_cb(endpoint_id, endpoint_info,
- service_id);
- analytics_recorder_->OnEndpointFound(medium);
-}
-
-void ClientProxy::OnEndpointLost(const std::string& service_id,
- const std::string& endpoint_id) {
- MutexLock lock(&mutex_);
-
- NEARBY_LOGS(INFO) << "ClientProxy [Endpoint Lost]: [enter] id=" << endpoint_id
- << "; service=" << service_id;
- if (!IsDiscoveringServiceId(service_id)) {
- NEARBY_LOG(INFO,
- "ClientProxy [Endpoint Lost]: Ignoring event for id=%s because "
- "this client is not discovering",
- endpoint_id.c_str());
- return;
- }
-
- const auto it = discovered_endpoint_ids_.find(endpoint_id);
- if (it == discovered_endpoint_ids_.end()) {
- NEARBY_LOGS(WARNING)
- << "ClientProxy [Endpoint Lost]: Ignoring event for id=" << endpoint_id
- << " because this client has not yet reported this endpoint as found";
- return;
- }
-
- discovered_endpoint_ids_.erase(it);
- discovery_info_.listener.endpoint_lost_cb(endpoint_id);
-}
-
-void ClientProxy::OnConnectionInitiated(const std::string& endpoint_id,
- const ConnectionResponseInfo& info,
- const ConnectionOptions& options,
- const ConnectionListener& listener,
- const std::string& connection_token) {
- MutexLock lock(&mutex_);
-
- // Whether this is incoming or outgoing, the local and remote endpoints both
- // still need to accept this connection, so set its establishment status to
- // PENDING.
- auto result = connections_.emplace(
- endpoint_id, Connection{
- .is_incoming = info.is_incoming_connection,
- .connection_listener = listener,
- .connection_options = options,
- .connection_token = connection_token,
- });
- // Instead of using structured binding which is nice, but banned
- // (can not use c++17 features, until chromium does) we unpack manually.
- auto& pair_iter = result.first;
- bool inserted = result.second;
- NEARBY_LOGS(INFO)
- << "ClientProxy [Connection Initiated]: add Connection: client="
- << GetClientId() << "; endpoint_id=" << endpoint_id
- << "; inserted=" << inserted;
- DCHECK(inserted);
- const Connection& item = pair_iter->second;
- // Notify the client.
- //
- // Note: we allow devices to connect to an advertiser even after it stops
- // advertising, so no need to check IsAdvertising() here.
- item.connection_listener.initiated_cb(endpoint_id, info);
-
- if (info.is_incoming_connection) {
- // Add CancellationFlag for advertisers once encryption succeeds.
- AddCancellationFlag(endpoint_id);
- analytics_recorder_->OnConnectionRequestReceived(endpoint_id);
- } else {
- analytics_recorder_->OnConnectionRequestSent(endpoint_id);
- }
-}
-
-void ClientProxy::OnConnectionAccepted(const std::string& endpoint_id) {
- MutexLock lock(&mutex_);
-
- if (!HasPendingConnectionToEndpoint(endpoint_id)) {
- NEARBY_LOGS(INFO) << "ClientProxy [Connection Accepted]: no pending "
- "connection; endpoint_id="
- << endpoint_id;
- return;
- }
-
- // Notify the client.
- Connection* item = LookupConnection(endpoint_id);
- if (item != nullptr) {
- item->connection_listener.accepted_cb(endpoint_id);
- item->status = Connection::kConnected;
- }
-}
-
-void ClientProxy::OnConnectionRejected(const std::string& endpoint_id,
- const Status& status) {
- MutexLock lock(&mutex_);
-
- if (!HasPendingConnectionToEndpoint(endpoint_id)) {
- NEARBY_LOGS(INFO) << "ClientProxy [Connection Rejected]: no pending "
- "connection; endpoint_id="
- << endpoint_id;
- return;
- }
-
- // Notify the client.
- const Connection* item = LookupConnection(endpoint_id);
- if (item != nullptr) {
- item->connection_listener.rejected_cb(endpoint_id, status);
- OnDisconnected(endpoint_id, false /* notify */);
- }
-}
-
-void ClientProxy::OnBandwidthChanged(const std::string& endpoint_id,
- Medium new_medium) {
- MutexLock lock(&mutex_);
-
- const Connection* item = LookupConnection(endpoint_id);
- if (item != nullptr) {
- item->connection_listener.bandwidth_changed_cb(endpoint_id, new_medium);
- NEARBY_LOGS(INFO) << "ClientProxy [reporting onBandwidthChanged]: client="
- << GetClientId() << "; endpoint_id=" << endpoint_id;
- }
-}
-
-void ClientProxy::OnDisconnected(const std::string& endpoint_id, bool notify) {
- MutexLock lock(&mutex_);
-
- const Connection* item = LookupConnection(endpoint_id);
- if (item != nullptr) {
- if (notify) {
- item->connection_listener.disconnected_cb({endpoint_id});
- }
- connections_.erase(endpoint_id);
- ResetLocalEndpointIdIfNeeded();
- }
-
- CancelEndpoint(endpoint_id);
-}
-
-bool ClientProxy::ConnectionStatusMatches(const std::string& endpoint_id,
- Connection::Status status) const {
- MutexLock lock(&mutex_);
-
- const Connection* item = LookupConnection(endpoint_id);
- if (item != nullptr) {
- return item->status == status;
- }
- return false;
-}
-
-BooleanMediumSelector ClientProxy::GetUpgradeMediums(
- const std::string& endpoint_id) const {
- MutexLock lock(&mutex_);
-
- const Connection* item = LookupConnection(endpoint_id);
- if (item != nullptr) {
- return item->connection_options.allowed;
- }
- return {};
-}
-
-bool ClientProxy::IsConnectedToEndpoint(const std::string& endpoint_id) const {
- return ConnectionStatusMatches(endpoint_id, Connection::kConnected);
-}
-
-std::vector<std::string> ClientProxy::GetMatchingEndpoints(
- std::function<bool(const Connection&)> pred) const {
- MutexLock lock(&mutex_);
-
- std::vector<std::string> connected_endpoints;
-
- for (const auto& pair : connections_) {
- const auto& endpoint_id = pair.first;
- const auto& connection = pair.second;
- if (pred(connection)) {
- connected_endpoints.push_back(endpoint_id);
- }
- }
- return connected_endpoints;
-}
-
-std::vector<std::string> ClientProxy::GetPendingConnectedEndpoints() const {
- return GetMatchingEndpoints([](const Connection& connection) {
- return connection.status != Connection::kConnected;
- });
-}
-
-std::vector<std::string> ClientProxy::GetConnectedEndpoints() const {
- return GetMatchingEndpoints([](const Connection& connection) {
- return connection.status == Connection::kConnected;
- });
-}
-
-std::int32_t ClientProxy::GetNumOutgoingConnections() const {
- return GetMatchingEndpoints([](const Connection& connection) {
- return connection.status == Connection::kConnected &&
- !connection.is_incoming;
- })
- .size();
-}
-
-std::int32_t ClientProxy::GetNumIncomingConnections() const {
- return GetMatchingEndpoints([](const Connection& connection) {
- return connection.status == Connection::kConnected &&
- connection.is_incoming;
- })
- .size();
-}
-
-bool ClientProxy::HasPendingConnectionToEndpoint(
- const std::string& endpoint_id) const {
- MutexLock lock(&mutex_);
-
- const Connection* item = LookupConnection(endpoint_id);
- if (item != nullptr) {
- return item->status != Connection::kConnected;
- }
- return false;
-}
-
-bool ClientProxy::HasLocalEndpointResponded(
- const std::string& endpoint_id) const {
- MutexLock lock(&mutex_);
-
- return ConnectionStatusesContains(
- endpoint_id,
- static_cast<Connection::Status>(Connection::kLocalEndpointAccepted |
- Connection::kLocalEndpointRejected));
-}
-
-bool ClientProxy::HasRemoteEndpointResponded(
- const std::string& endpoint_id) const {
- MutexLock lock(&mutex_);
-
- return ConnectionStatusesContains(
- endpoint_id,
- static_cast<Connection::Status>(Connection::kRemoteEndpointAccepted |
- Connection::kRemoteEndpointRejected));
-}
-
-void ClientProxy::LocalEndpointAcceptedConnection(
- const std::string& endpoint_id, const PayloadListener& listener) {
- MutexLock lock(&mutex_);
-
- if (HasLocalEndpointResponded(endpoint_id)) {
- NEARBY_LOGS(INFO)
- << "ClientProxy [Local Accepted]: local endpoint has responded; id="
- << endpoint_id;
- return;
- }
-
- AppendConnectionStatus(endpoint_id, Connection::kLocalEndpointAccepted);
- Connection* item = LookupConnection(endpoint_id);
- if (item != nullptr) {
- item->payload_listener = listener;
- }
- analytics_recorder_->OnLocalEndpointAccepted(endpoint_id);
-}
-
-void ClientProxy::LocalEndpointRejectedConnection(
- const std::string& endpoint_id) {
- MutexLock lock(&mutex_);
-
- if (HasLocalEndpointResponded(endpoint_id)) {
- NEARBY_LOGS(INFO)
- << "ClientProxy [Local Rejected]: local endpoint has responded; id="
- << endpoint_id;
- return;
- }
-
- AppendConnectionStatus(endpoint_id, Connection::kLocalEndpointRejected);
- analytics_recorder_->OnLocalEndpointRejected(endpoint_id);
-}
-
-void ClientProxy::RemoteEndpointAcceptedConnection(
- const std::string& endpoint_id) {
- MutexLock lock(&mutex_);
-
- if (HasRemoteEndpointResponded(endpoint_id)) {
- NEARBY_LOGS(INFO)
- << "ClientProxy [Remote Accepted]: remote endpoint has responded; id="
- << endpoint_id;
- return;
- }
-
- AppendConnectionStatus(endpoint_id, Connection::kRemoteEndpointAccepted);
- analytics_recorder_->OnRemoteEndpointAccepted(endpoint_id);
-}
-
-void ClientProxy::RemoteEndpointRejectedConnection(
- const std::string& endpoint_id) {
- MutexLock lock(&mutex_);
-
- if (HasRemoteEndpointResponded(endpoint_id)) {
- NEARBY_LOGS(INFO)
- << "ClientProxy [Remote Rejected]: remote endpoint has responded; id="
- << endpoint_id;
- return;
- }
-
- AppendConnectionStatus(endpoint_id, Connection::kRemoteEndpointRejected);
- analytics_recorder_->OnRemoteEndpointRejected(endpoint_id);
-}
-
-bool ClientProxy::IsConnectionAccepted(const std::string& endpoint_id) const {
- MutexLock lock(&mutex_);
-
- return ConnectionStatusesContains(endpoint_id,
- Connection::kLocalEndpointAccepted) &&
- ConnectionStatusesContains(endpoint_id,
- Connection::kRemoteEndpointAccepted);
-}
-
-bool ClientProxy::IsConnectionRejected(const std::string& endpoint_id) const {
- MutexLock lock(&mutex_);
-
- return ConnectionStatusesContains(
- endpoint_id,
- static_cast<Connection::Status>(Connection::kLocalEndpointRejected |
- Connection::kRemoteEndpointRejected));
-}
-
-bool ClientProxy::LocalConnectionIsAccepted(std::string endpoint_id) const {
- return ConnectionStatusesContains(
- endpoint_id, ClientProxy::Connection::kLocalEndpointAccepted);
-}
-
-bool ClientProxy::RemoteConnectionIsAccepted(std::string endpoint_id) const {
- return ConnectionStatusesContains(
- endpoint_id, ClientProxy::Connection::kRemoteEndpointAccepted);
-}
-
-void ClientProxy::AddCancellationFlag(const std::string& endpoint_id) {
- // Don't insert the CancellationFlag to the map if feature flag is disabled.
- if (!FeatureFlags::GetInstance().GetFlags().enable_cancellation_flag) {
- return;
- }
-
- auto item = cancellation_flags_.find(endpoint_id);
- if (item != cancellation_flags_.end()) {
- return;
- }
- cancellation_flags_.emplace(endpoint_id,
- std::make_unique<CancellationFlag>());
-}
-
-CancellationFlag* ClientProxy::GetCancellationFlag(
- const std::string& endpoint_id) {
- const auto item = cancellation_flags_.find(endpoint_id);
- if (item == cancellation_flags_.end()) {
- return default_cancellation_flag_.get();
- }
- return item->second.get();
-}
-
-void ClientProxy::CancelEndpoint(const std::string& endpoint_id) {
- const auto item = cancellation_flags_.find(endpoint_id);
- if (item == cancellation_flags_.end()) return;
- item->second->Cancel();
- cancellation_flags_.erase(item);
-}
-
-void ClientProxy::CancelAllEndpoints() {
- for (const auto& item : cancellation_flags_) {
- CancellationFlag* cancellation_flag = item.second.get();
- if (cancellation_flag->Cancelled()) {
- continue;
- }
- cancellation_flag->Cancel();
- }
- cancellation_flags_.clear();
-}
-
-void ClientProxy::OnPayload(const std::string& endpoint_id, Payload payload) {
- MutexLock lock(&mutex_);
-
- if (IsConnectedToEndpoint(endpoint_id)) {
- const Connection* item = LookupConnection(endpoint_id);
- if (item != nullptr) {
- NEARBY_LOGS(INFO) << "ClientProxy [reporting onPayloadReceived]: client="
- << GetClientId() << "; endpoint_id=" << endpoint_id
- << " ; payload_id=" << payload.GetId();
- item->payload_listener.payload_cb(endpoint_id, std::move(payload));
- }
- }
-}
-
-const ClientProxy::Connection* ClientProxy::LookupConnection(
- const std::string& endpoint_id) const {
- auto item = connections_.find(endpoint_id);
- return item != connections_.end() ? &item->second : nullptr;
-}
-
-ClientProxy::Connection* ClientProxy::LookupConnection(
- const std::string& endpoint_id) {
- auto item = connections_.find(endpoint_id);
- return item != connections_.end() ? &item->second : nullptr;
-}
-
-void ClientProxy::OnPayloadProgress(const std::string& endpoint_id,
- const PayloadProgressInfo& info) {
- MutexLock lock(&mutex_);
-
- if (IsConnectedToEndpoint(endpoint_id)) {
- Connection* item = LookupConnection(endpoint_id);
- if (item != nullptr) {
- item->payload_listener.payload_progress_cb(endpoint_id, info);
-
- if (info.status == PayloadProgressInfo::Status::kInProgress) {
- NEARBY_LOGS(VERBOSE)
- << "ClientProxy [reporting onPayloadProgress]: client="
- << GetClientId() << "; endpoint_id=" << endpoint_id
- << "; payload_id=" << info.payload_id
- << ", payload_status=" << ToString(info.status);
- } else {
- NEARBY_LOGS(INFO)
- << "ClientProxy [reporting onPayloadProgress]: client="
- << GetClientId() << "; endpoint_id=" << endpoint_id
- << "; payload_id=" << info.payload_id
- << ", payload_status=" << ToString(info.status);
- }
- }
- }
-}
-
-void ClientProxy::RemoveAllEndpoints() {
- MutexLock lock(&mutex_);
-
- // Note: we may want to notify the client of onDisconnected() for each
- // endpoint, in the case when this is called from stopAllEndpoints(). For now,
- // just remove without notifying.
- connections_.clear();
- cancellation_flags_.clear();
- local_endpoint_id_.clear();
-}
-
-void ClientProxy::ResetLocalEndpointIdIfNeeded() {
- MutexLock lock(&mutex_);
- if (connections_.empty() && !IsAdvertising() && !IsDiscovering()) {
- local_endpoint_id_.clear();
- }
-}
-
-bool ClientProxy::ConnectionStatusesContains(
- const std::string& endpoint_id, Connection::Status status_to_match) const {
- const Connection* item = LookupConnection(endpoint_id);
- if (item != nullptr) {
- return (item->status & status_to_match) != 0;
- }
- return false;
-}
-
-void ClientProxy::AppendConnectionStatus(const std::string& endpoint_id,
- Connection::Status status_to_append) {
- Connection* item = LookupConnection(endpoint_id);
- if (item != nullptr) {
- item->status =
- static_cast<Connection::Status>(item->status | status_to_append);
- }
-}
-
-ConnectionOptions ClientProxy::GetAdvertisingOptions() const {
- return advertising_options_;
-}
-
-ConnectionOptions ClientProxy::GetDiscoveryOptions() const {
- return discovery_options_;
-}
-
-void ClientProxy::EnterHighVisibilityMode() {
- MutexLock lock(&mutex_);
- NEARBY_LOGS(INFO) << "ClientProxy [EnterHighVisibilityMode]: client="
- << GetClientId();
-
- high_vis_mode_ = true;
-}
-
-void ClientProxy::ExitHighVisibilityMode() {
- MutexLock lock(&mutex_);
- NEARBY_LOGS(INFO) << "ClientProxy [ExitHighVisibilityMode]: client="
- << GetClientId();
-
- high_vis_mode_ = false;
- ScheduleClearLocalHighVisModeCacheEndpointIdAlarm();
-}
-
-void ClientProxy::ScheduleClearLocalHighVisModeCacheEndpointIdAlarm() {
- CancelClearLocalHighVisModeCacheEndpointIdAlarm();
-
- if (local_high_vis_mode_cache_endpoint_id_.empty()) {
- NEARBY_LOGS(VERBOSE) << "ClientProxy [There is no cached local high power "
- "advertising endpoint Id]: client="
- << GetClientId();
- return;
- }
-
- // Schedule to clear cache high visibility mode advertisement endpoint id in
- // 30s.
- NEARBY_LOGS(INFO) << "ClientProxy [High Visibility Mode Adv, Schedule to "
- "Clear Cache EndpointId]: client="
- << GetClientId()
- << "; local_high_vis_mode_cache_endpoint_id_="
- << local_high_vis_mode_cache_endpoint_id_;
- clear_local_high_vis_mode_cache_endpoint_id_alarm_ =
- CancelableAlarm(
- "clear_high_power_endpoint_id_cache",
- [this]() {
- MutexLock lock(&mutex_);
- NEARBY_LOGS(INFO)
- << "ClientProxy [Cleared cached local high power advertising "
- "endpoint Id.]: client="
- << GetClientId() << "; local_high_vis_mode_cache_endpoint_id_="
- << local_high_vis_mode_cache_endpoint_id_;
- local_high_vis_mode_cache_endpoint_id_.clear();
- },
- kHighPowerAdvertisementEndpointIdCacheTimeout,
- &single_thread_executor_);
-}
-
-void ClientProxy::CancelClearLocalHighVisModeCacheEndpointIdAlarm() {
- if (clear_local_high_vis_mode_cache_endpoint_id_alarm_.IsValid()) {
- clear_local_high_vis_mode_cache_endpoint_id_alarm_.Cancel();
- clear_local_high_vis_mode_cache_endpoint_id_alarm_ = CancelableAlarm();
- }
-}
-
-std::string ClientProxy::ToString(PayloadProgressInfo::Status status) const {
- switch (status) {
- case PayloadProgressInfo::Status::kSuccess:
- return std::string("Success");
- case PayloadProgressInfo::Status::kFailure:
- return std::string("Failure");
- case PayloadProgressInfo::Status::kInProgress:
- return std::string("In Progress");
- case PayloadProgressInfo::Status::kCanceled:
- return std::string("Cancelled");
- }
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/client_proxy.h b/chromium/third_party/nearby/src/cpp/core/internal/client_proxy.h
deleted file mode 100644
index 8bf210f16a6..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/client_proxy.h
+++ /dev/null
@@ -1,323 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_CLIENT_PROXY_H_
-#define CORE_INTERNAL_CLIENT_PROXY_H_
-
-#include <cstdint>
-#include <functional>
-#include <string>
-#include <vector>
-
-#include "analytics/analytics_recorder.h"
-#include "core/listeners.h"
-#include "core/options.h"
-#include "core/status.h"
-#include "core/strategy.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/cancellation_flag.h"
-#include "platform/base/error_code_recorder.h"
-#include "platform/base/prng.h"
-#include "platform/public/cancelable_alarm.h"
-#include "platform/public/mutex.h"
-// Prefer using absl:: versions of a set and a map; they tend to be more
-// efficient: implementation is using open-addressing hash tables.
-#include "absl/container/flat_hash_map.h"
-#include "absl/container/flat_hash_set.h"
-#include "absl/types/span.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// CLientProxy is tracking state of client's connection, and serves as
-// a proxy for notifications sent to this client.
-class ClientProxy final {
- public:
- static constexpr int kEndpointIdLength = 4;
- static constexpr absl::Duration
- kHighPowerAdvertisementEndpointIdCacheTimeout = absl::Seconds(30);
-
- explicit ClientProxy(analytics::EventLogger* event_logger = nullptr);
- ~ClientProxy();
- ClientProxy(ClientProxy&&) = default;
- ClientProxy& operator=(ClientProxy&&) = default;
-
- std::int64_t GetClientId() const;
-
- std::string GetLocalEndpointId();
-
- analytics::AnalyticsRecorder& GetAnalyticsRecorder() const {
- return *analytics_recorder_;
- }
-
- std::string GetConnectionToken(const std::string& endpoint_id);
-
- // Clears all the runtime state of this client.
- void Reset();
-
- // Marks this client as advertising with the given callbacks.
- void StartedAdvertising(
- const std::string& service_id, Strategy strategy,
- const ConnectionListener& connection_lifecycle_listener,
- absl::Span<proto::connections::Medium> mediums,
- const ConnectionOptions& advertising_options = ConnectionOptions{});
- // Marks this client as not advertising.
- void StoppedAdvertising();
- bool IsAdvertising() const;
- std::string GetAdvertisingServiceId() const;
-
- // Get service ID of a surrently active link (either advertising, or
- // discovering).
- std::string GetServiceId() const;
-
- // Marks this client as discovering with the given callback.
- void StartedDiscovery(
- const std::string& service_id, Strategy strategy,
- const DiscoveryListener& discovery_listener,
- absl::Span<proto::connections::Medium> mediums,
- const ConnectionOptions& discovery_options = ConnectionOptions{});
- // Marks this client as not discovering at all.
- void StoppedDiscovery();
- bool IsDiscoveringServiceId(const std::string& service_id) const;
- bool IsDiscovering() const;
- std::string GetDiscoveryServiceId() const;
-
- // Proxies to the client's DiscoveryListener::OnEndpointFound() callback.
- void OnEndpointFound(const std::string& service_id,
- const std::string& endpoint_id,
- const ByteArray& endpoint_info,
- proto::connections::Medium medium);
- // Proxies to the client's DiscoveryListener::OnEndpointLost() callback.
- void OnEndpointLost(const std::string& service_id,
- const std::string& endpoint_id);
-
- // Proxies to the client's ConnectionListener::OnInitiated() callback.
- void OnConnectionInitiated(const std::string& endpoint_id,
- const ConnectionResponseInfo& info,
- const ConnectionOptions& options,
- const ConnectionListener& listener,
- const std::string& connection_token);
-
- // Proxies to the client's ConnectionListener::OnAccepted() callback.
- void OnConnectionAccepted(const std::string& endpoint_id);
- // Proxies to the client's ConnectionListener::OnRejected() callback.
- void OnConnectionRejected(const std::string& endpoint_id,
- const Status& status);
-
- void OnBandwidthChanged(const std::string& endpoint_id, Medium new_medium);
-
- // Removes the endpoint from this client's list of connected endpoints. If
- // notify is true, also calls the client's
- // ConnectionListener.disconnected_cb() callback.
- void OnDisconnected(const std::string& endpoint_id, bool notify);
-
- // Returns all mediums eligible for upgrade.
- BooleanMediumSelector GetUpgradeMediums(const std::string& endpoint_id) const;
- // Returns true if it's safe to send payloads to this endpoint.
- bool IsConnectedToEndpoint(const std::string& endpoint_id) const;
- // Returns all endpoints that can safely be sent payloads.
- std::vector<std::string> GetConnectedEndpoints() const;
- // Returns all endpoints that are still awaiting acceptance.
- std::vector<std::string> GetPendingConnectedEndpoints() const;
- // Returns the number of endpoints that are connected and outgoing.
- std::int32_t GetNumOutgoingConnections() const;
- // Returns the number of endpoints that are connected and incoming.
- std::int32_t GetNumIncomingConnections() const;
- // If true, then we're in the process of approving (or rejecting) a
- // connection. No payloads should be sent until isConnectedToEndpoint()
- // returns true.
- bool HasPendingConnectionToEndpoint(const std::string& endpoint_id) const;
- // Returns true if the local endpoint has already marked itself as
- // accepted/rejected.
- bool HasLocalEndpointResponded(const std::string& endpoint_id) const;
- // Returns true if the remote endpoint has already marked themselves as
- // accepted/rejected.
- bool HasRemoteEndpointResponded(const std::string& endpoint_id) const;
- // Marks the local endpoint as having accepted the connection.
- void LocalEndpointAcceptedConnection(const std::string& endpoint_id,
- const PayloadListener& listener);
- // Marks the local endpoint as having rejected the connection.
- void LocalEndpointRejectedConnection(const std::string& endpoint_id);
- // Marks the remote endpoint as having accepted the connection.
- void RemoteEndpointAcceptedConnection(const std::string& endpoint_id);
- // Marks the remote endpoint as having rejected the connection.
- void RemoteEndpointRejectedConnection(const std::string& endpoint_id);
- // Returns true if both the local endpoint and the remote endpoint have
- // accepted the connection.
- bool IsConnectionAccepted(const std::string& endpoint_id) const;
- // Returns true if either the local endpoint or the remote endpoint has
- // rejected the connection.
- bool IsConnectionRejected(const std::string& endpoint_id) const;
-
- // Proxies to the client's PayloadListener::OnPayload() callback.
- void OnPayload(const std::string& endpoint_id, Payload payload);
- // Proxies to the client's PayloadListener::OnPayloadProgress() callback.
- void OnPayloadProgress(const std::string& endpoint_id,
- const PayloadProgressInfo& info);
- bool LocalConnectionIsAccepted(std::string endpoint_id) const;
- bool RemoteConnectionIsAccepted(std::string endpoint_id) const;
-
- // Adds a CancellationFlag for endpoint id.
- void AddCancellationFlag(const std::string& endpoint_id);
- // Returns the CancellationFlag for endpoint id,
- CancellationFlag* GetCancellationFlag(const std::string& endpoint_id);
- // Sets the CancellationFlag to true for endpoint id.
- void CancelEndpoint(const std::string& endpoint_id);
- // Cancels all CancellationFlags.
- void CancelAllEndpoints();
- ConnectionOptions GetAdvertisingOptions() const;
- ConnectionOptions GetDiscoveryOptions() const;
-
- // The endpoint id will be stable for 30 seconds after high visibility mode
- // (high power and Bluetooth Classic) advertisement stops.
- // If client re-enters high visibility mode within 30 seconds, he is going to
- // have the same endpoint id.
- void EnterHighVisibilityMode();
- // Cleans up any modifications in high visibility mode. The endpoint id always
- // rotates.
- void ExitHighVisibilityMode();
-
- private:
- struct Connection {
- // Status: may be either:
- // Connection::PENDING, or combination of
- // Connection::LOCAL_ENDPOINT_ACCEPTED:
- // Connection::LOCAL_ENDPOINT_REJECTED and
- // Connection::REMOTE_ENDPOINT_ACCEPTED:
- // Connection::REMOTE_ENDPOINT_REJECTED, or
- // Connection::CONNECTED.
- // Only when this is set to CONNECTED should you allow payload transfers.
- //
- // We want this enum to be implicitly convertible to int, because
- // we perform bit operations on it.
- enum Status : uint8_t {
- kPending = 0,
- kLocalEndpointAccepted = 1 << 0,
- kLocalEndpointRejected = 1 << 1,
- kRemoteEndpointAccepted = 1 << 2,
- kRemoteEndpointRejected = 1 << 3,
- kConnected = 1 << 4,
- };
- bool is_incoming{false};
- Status status{kPending};
- ConnectionListener connection_listener;
- PayloadListener payload_listener;
- ConnectionOptions connection_options;
- std::string connection_token;
- };
-
- struct AdvertisingInfo {
- std::string service_id;
- ConnectionListener listener;
- void Clear() { service_id.clear(); }
- bool IsEmpty() const { return service_id.empty(); }
- };
-
- struct DiscoveryInfo {
- std::string service_id;
- DiscoveryListener listener;
- void Clear() { service_id.clear(); }
- bool IsEmpty() const { return service_id.empty(); }
- };
-
- void RemoveAllEndpoints();
- void ResetLocalEndpointIdIfNeeded();
- bool ConnectionStatusesContains(const std::string& endpoint_id,
- Connection::Status status_to_match) const;
- void AppendConnectionStatus(const std::string& endpoint_id,
- Connection::Status status_to_append);
-
- const Connection* LookupConnection(const std::string& endpoint_id) const;
- Connection* LookupConnection(const std::string& endpoint_id);
- bool ConnectionStatusMatches(const std::string& endpoint_id,
- Connection::Status status) const;
- std::vector<std::string> GetMatchingEndpoints(
- std::function<bool(const Connection&)> pred) const;
- std::string GenerateLocalEndpointId();
-
- void ScheduleClearLocalHighVisModeCacheEndpointIdAlarm();
- void CancelClearLocalHighVisModeCacheEndpointIdAlarm();
-
- std::string ToString(PayloadProgressInfo::Status status) const;
-
- mutable RecursiveMutex mutex_;
- Prng prng_;
- std::int64_t client_id_;
- std::string local_endpoint_id_;
- // If currently is advertising in high visibility mode is true: high power and
- // Bluetooth Classic enabled. When high_visibility_mode_ is true, the endpoint
- // id is stable for 30s. When high_visibility_mode_ is false, the endpoint id
- // always rotates.
- bool high_vis_mode_{false};
- // Caches the endpoint id when it is in high visibility mode advertisement for
- // 30s. Currently, Nearby Connections keeps rotating endpoint id. The client
- // (Nearby Share) treats different endpoints as different receivers, duplicate
- // share targets for same devices occur on share sheet in this case.
- // Therefore, we remember the high visibility mode advertisement endpoint id
- // here. empty if 1) There is no high power advertisement before 2) The
- // endpoint id cached here in previous high visibility mode advertisement
- // expires.
- std::string local_high_vis_mode_cache_endpoint_id_;
- ScheduledExecutor single_thread_executor_;
- CancelableAlarm clear_local_high_vis_mode_cache_endpoint_id_alarm_;
-
- // If not empty, we are currently advertising and accepting connection
- // requests for the given service_id.
- AdvertisingInfo advertising_info_;
-
- // If not empty, we are currently discovering for the given service_id.
- DiscoveryInfo discovery_info_;
-
- // The active ClientProxy's advertising constraints. Empty()
- // returns true if the client hasn't started advertising false otherwise.
- // Note: this is not cleared when the client stops advertising because it
- // might still be useful downstream of advertising (eg: establishing
- // connections, performing bandwidth upgrades, etc.)
- ConnectionOptions advertising_options_;
-
- // The active ClientProxy's discovery constraints. Null if the client
- // hasn't started discovering. Note: this is not cleared when the client
- // stops discovering because it might still be useful downstream of
- // discovery (eg: connection speed, etc.)
- ConnectionOptions discovery_options_;
-
- // Maps endpoint_id to endpoint connection state.
- absl::flat_hash_map<std::string, Connection> connections_;
-
- // A cache of endpoint ids that we've already notified the discoverer of. We
- // check this cache before calling onEndpointFound() so that we don't notify
- // the client multiple times for the same endpoint. This would otherwise
- // happen because some mediums (like Bluetooth) repeatedly give us the same
- // endpoints after each scan.
- absl::flat_hash_set<std::string> discovered_endpoint_ids_;
-
- // Maps endpoint_id to CancellationFlag.
- absl::flat_hash_map<std::string, std::unique_ptr<CancellationFlag>>
- cancellation_flags_;
- // A default cancellation flag with isCancelled set be true.
- std::unique_ptr<CancellationFlag> default_cancellation_flag_ =
- std::make_unique<CancellationFlag>(true);
-
- // An analytics logger with |EventLogger| provided by client, which is default
- // nullptr as no-op.
- std::unique_ptr<analytics::AnalyticsRecorder> analytics_recorder_;
- std::unique_ptr<ErrorCodeRecorder> error_code_recorder_;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_CLIENT_PROXY_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/client_proxy_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/client_proxy_test.cc
deleted file mode 100644
index 61038279636..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/client_proxy_test.cc
+++ /dev/null
@@ -1,622 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/client_proxy.h"
-
-#include <string>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/container/flat_hash_set.h"
-#include "absl/time/clock.h"
-#include "absl/time/time.h"
-#include "absl/types/span.h"
-#include "core/listeners.h"
-#include "core/options.h"
-#include "core/strategy.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/feature_flags.h"
-#include "platform/base/medium_environment.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-
-using FeatureFlags = FeatureFlags::Flags;
-using ::testing::MockFunction;
-using ::testing::StrictMock;
-
-constexpr FeatureFlags kTestCases[] = {
- FeatureFlags{
- .enable_cancellation_flag = true,
- },
- FeatureFlags{
- .enable_cancellation_flag = false,
- },
-};
-
-class ClientProxyTest : public ::testing::TestWithParam<FeatureFlags> {
- protected:
- struct MockDiscoveryListener {
- StrictMock<MockFunction<void(const std::string& endpoint_id,
- const ByteArray& endpoint_info,
- const std::string& service_id)>>
- endpoint_found_cb;
- StrictMock<MockFunction<void(const std::string& endpoint_id)>>
- endpoint_lost_cb;
- };
- struct MockConnectionListener {
- StrictMock<MockFunction<void(const std::string& endpoint_id,
- const ConnectionResponseInfo& info)>>
- initiated_cb;
- StrictMock<MockFunction<void(const std::string& endpoint_id)>> accepted_cb;
- StrictMock<MockFunction<void(const std::string& endpoint_id,
- const Status& status)>>
- rejected_cb;
- StrictMock<MockFunction<void(const std::string& endpoint_id)>>
- disconnected_cb;
- StrictMock<MockFunction<void(const std::string& endpoint_id,
- std::int32_t quality)>>
- bandwidth_changed_cb;
- };
- struct MockPayloadListener {
- StrictMock<
- MockFunction<void(const std::string& endpoint_id, Payload payload)>>
- payload_cb;
- StrictMock<MockFunction<void(const std::string& endpoint_id,
- const PayloadProgressInfo& info)>>
- payload_progress_cb;
- };
-
- struct Endpoint {
- ByteArray info;
- std::string id;
- };
-
- bool ShouldEnterHighVisibilityMode(const ConnectionOptions& options) {
- return !options.low_power && options.allowed.bluetooth;
- }
-
- Endpoint StartAdvertising(
- ClientProxy* client, ConnectionListener listener,
- ConnectionOptions advertising_options = ConnectionOptions{}) {
- if (ShouldEnterHighVisibilityMode(advertising_options)) {
- client->EnterHighVisibilityMode();
- }
- Endpoint endpoint{
- .info = ByteArray{"advertising endpoint name"},
- .id = client->GetLocalEndpointId(),
- };
- client->StartedAdvertising(service_id_, strategy_, listener,
- absl::MakeSpan(mediums_), advertising_options);
- return endpoint;
- }
-
- void StopAdvertising(ClientProxy* client) { client->StoppedAdvertising(); }
-
- Endpoint StartDiscovery(ClientProxy* client, DiscoveryListener listener) {
- Endpoint endpoint{
- .info = ByteArray{"discovery endpoint name"},
- .id = client->GetLocalEndpointId(),
- };
- client->StartedDiscovery(service_id_, strategy_, listener,
- absl::MakeSpan(mediums_));
- return endpoint;
- }
-
- void OnDiscoveryEndpointFound(ClientProxy* client, const Endpoint& endpoint) {
- EXPECT_CALL(mock_discovery_.endpoint_found_cb, Call).Times(1);
- client->OnEndpointFound(service_id_, endpoint.id, endpoint.info, medium_);
- }
-
- void OnDiscoveryEndpointLost(ClientProxy* client, const Endpoint& endpoint) {
- EXPECT_CALL(mock_discovery_.endpoint_lost_cb, Call).Times(1);
- client->OnEndpointLost(service_id_, endpoint.id);
- }
-
- void OnDiscoveryConnectionInitiated(ClientProxy* client,
- const Endpoint& endpoint) {
- EXPECT_CALL(mock_discovery_connection_.initiated_cb, Call).Times(1);
- const std::string auth_token{"auth_token"};
- const ByteArray raw_auth_token{auth_token};
- const std::string connection_token{"conntokn"};
- advertising_connection_info_.remote_endpoint_info = endpoint.info;
- client->OnConnectionInitiated(
- endpoint.id, advertising_connection_info_, connection_options_,
- discovery_connection_listener_, connection_token);
- EXPECT_TRUE(client->HasPendingConnectionToEndpoint(endpoint.id));
- }
-
- void OnDiscoveryConnectionLocalAccepted(ClientProxy* client,
- const Endpoint& endpoint) {
- EXPECT_TRUE(client->HasPendingConnectionToEndpoint(endpoint.id));
- EXPECT_FALSE(client->HasLocalEndpointResponded(endpoint.id));
- client->LocalEndpointAcceptedConnection(endpoint.id, payload_listener_);
- EXPECT_TRUE(client->HasLocalEndpointResponded(endpoint.id));
- EXPECT_TRUE(client->LocalConnectionIsAccepted(endpoint.id));
- }
-
- void OnDiscoveryConnectionRemoteAccepted(ClientProxy* client,
- const Endpoint& endpoint) {
- EXPECT_TRUE(client->HasPendingConnectionToEndpoint(endpoint.id));
- EXPECT_FALSE(client->HasRemoteEndpointResponded(endpoint.id));
- client->RemoteEndpointAcceptedConnection(endpoint.id);
- EXPECT_TRUE(client->HasRemoteEndpointResponded(endpoint.id));
- EXPECT_TRUE(client->RemoteConnectionIsAccepted(endpoint.id));
- }
-
- void OnDiscoveryConnectionLocalRejected(ClientProxy* client,
- const Endpoint& endpoint) {
- EXPECT_TRUE(client->HasPendingConnectionToEndpoint(endpoint.id));
- EXPECT_FALSE(client->HasLocalEndpointResponded(endpoint.id));
- client->LocalEndpointRejectedConnection(endpoint.id);
- EXPECT_TRUE(client->HasLocalEndpointResponded(endpoint.id));
- EXPECT_FALSE(client->LocalConnectionIsAccepted(endpoint.id));
- }
-
- void OnDiscoveryConnectionRemoteRejected(ClientProxy* client,
- const Endpoint& endpoint) {
- EXPECT_TRUE(client->HasPendingConnectionToEndpoint(endpoint.id));
- EXPECT_FALSE(client->HasRemoteEndpointResponded(endpoint.id));
- client->RemoteEndpointRejectedConnection(endpoint.id);
- EXPECT_TRUE(client->HasRemoteEndpointResponded(endpoint.id));
- EXPECT_FALSE(client->RemoteConnectionIsAccepted(endpoint.id));
- }
-
- void OnDiscoveryConnectionAccepted(ClientProxy* client,
- const Endpoint& endpoint) {
- EXPECT_CALL(mock_discovery_connection_.accepted_cb, Call).Times(1);
- EXPECT_TRUE(client->IsConnectionAccepted(endpoint.id));
- client->OnConnectionAccepted(endpoint.id);
- }
-
- void OnDiscoveryConnectionRejected(ClientProxy* client,
- const Endpoint& endpoint) {
- EXPECT_CALL(mock_discovery_connection_.rejected_cb, Call).Times(1);
- EXPECT_TRUE(client->IsConnectionRejected(endpoint.id));
- client->OnConnectionRejected(endpoint.id, {Status::kConnectionRejected});
- }
-
- void OnDiscoveryBandwidthChanged(ClientProxy* client,
- const Endpoint& endpoint) {
- EXPECT_CALL(mock_discovery_connection_.bandwidth_changed_cb, Call).Times(1);
- client->OnBandwidthChanged(endpoint.id, Medium::WIFI_LAN);
- }
-
- void OnDiscoveryConnectionDisconnected(ClientProxy* client,
- const Endpoint& endpoint) {
- EXPECT_CALL(mock_discovery_connection_.disconnected_cb, Call).Times(1);
- client->OnDisconnected(endpoint.id, true);
- }
-
- void OnPayload(ClientProxy* client, const Endpoint& endpoint) {
- EXPECT_CALL(mock_discovery_payload_.payload_cb, Call).Times(1);
- client->OnPayload(endpoint.id, Payload(payload_bytes_));
- }
-
- void OnPayloadProgress(ClientProxy* client, const Endpoint& endpoint) {
- EXPECT_CALL(mock_discovery_payload_.payload_progress_cb, Call).Times(1);
- client->OnPayloadProgress(endpoint.id, {});
- }
-
- MockDiscoveryListener mock_discovery_;
- MockConnectionListener mock_discovery_connection_;
- MockPayloadListener mock_discovery_payload_;
-
- proto::connections::Medium medium_{proto::connections::Medium::BLUETOOTH};
- std::vector<proto::connections::Medium> mediums_{
- proto::connections::Medium::BLUETOOTH,
- };
- Strategy strategy_{Strategy::kP2pPointToPoint};
- const std::string service_id_{"service"};
- ClientProxy client1_;
- ClientProxy client2_;
- std::string auth_token_ = "auth_token";
- ByteArray raw_auth_token_ = ByteArray(auth_token_);
- ByteArray payload_bytes_{"bytes"};
- ConnectionResponseInfo advertising_connection_info_{
- .authentication_token = auth_token_,
- .raw_authentication_token = raw_auth_token_,
- .is_incoming_connection = true,
- };
- ConnectionListener advertising_connection_listener_;
- ConnectionListener discovery_connection_listener_{
- .initiated_cb = mock_discovery_connection_.initiated_cb.AsStdFunction(),
- .accepted_cb = mock_discovery_connection_.accepted_cb.AsStdFunction(),
- .rejected_cb = mock_discovery_connection_.rejected_cb.AsStdFunction(),
- .disconnected_cb =
- mock_discovery_connection_.disconnected_cb.AsStdFunction(),
- .bandwidth_changed_cb =
- mock_discovery_connection_.bandwidth_changed_cb.AsStdFunction(),
- };
- DiscoveryListener discovery_listener_{
- .endpoint_found_cb = mock_discovery_.endpoint_found_cb.AsStdFunction(),
- .endpoint_lost_cb = mock_discovery_.endpoint_lost_cb.AsStdFunction(),
- };
- PayloadListener payload_listener_{
- .payload_cb = mock_discovery_payload_.payload_cb.AsStdFunction(),
- .payload_progress_cb =
- mock_discovery_payload_.payload_progress_cb.AsStdFunction(),
- };
- ConnectionOptions connection_options_;
-};
-
-TEST_P(ClientProxyTest, CanCancelEndpoint) {
- FeatureFlags feature_flags = GetParam();
- MediumEnvironment::Instance().SetFeatureFlags(feature_flags);
-
- Endpoint advertising_endpoint =
- StartAdvertising(&client1_, advertising_connection_listener_);
- StartDiscovery(&client2_, discovery_listener_);
- OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
- OnDiscoveryConnectionInitiated(&client2_, advertising_endpoint);
-
- EXPECT_FALSE(
- client2_.GetCancellationFlag(advertising_endpoint.id)->Cancelled());
-
- client2_.CancelEndpoint(advertising_endpoint.id);
-
- // If FeatureFlag is disabled, Cancelled is false as no-op.
- if (!feature_flags.enable_cancellation_flag) {
- EXPECT_FALSE(
- client2_.GetCancellationFlag(advertising_endpoint.id)->Cancelled());
- } else {
- // The Cancelled is always true as the default flag being returned.
- EXPECT_TRUE(
- client2_.GetCancellationFlag(advertising_endpoint.id)->Cancelled());
- }
-}
-
-TEST_P(ClientProxyTest, CanCancelAllEndpoints) {
- FeatureFlags feature_flags = GetParam();
- MediumEnvironment::Instance().SetFeatureFlags(feature_flags);
-
- Endpoint advertising_endpoint =
- StartAdvertising(&client1_, advertising_connection_listener_);
- StartDiscovery(&client2_, discovery_listener_);
- OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
- OnDiscoveryConnectionInitiated(&client2_, advertising_endpoint);
-
- EXPECT_FALSE(
- client2_.GetCancellationFlag(advertising_endpoint.id)->Cancelled());
-
- client2_.CancelAllEndpoints();
-
- // If FeatureFlag is disabled, Cancelled is false as no-op.
- if (!feature_flags.enable_cancellation_flag) {
- EXPECT_FALSE(
- client2_.GetCancellationFlag(advertising_endpoint.id)->Cancelled());
- } else {
- // The Cancelled is always true as the default flag being returned.
- EXPECT_TRUE(
- client2_.GetCancellationFlag(advertising_endpoint.id)->Cancelled());
- }
-}
-
-TEST_P(ClientProxyTest, CanCancelAllEndpointsWithDifferentEndpoint) {
- FeatureFlags feature_flags = GetParam();
- MediumEnvironment::Instance().SetFeatureFlags(feature_flags);
-
- ConnectionListener advertising_connection_listener_2;
- ConnectionListener advertising_connection_listener_3;
- ClientProxy client3;
-
- StartDiscovery(&client1_, discovery_listener_);
- Endpoint advertising_endpoint_2 =
- StartAdvertising(&client2_, advertising_connection_listener_2);
- Endpoint advertising_endpoint_3 =
- StartAdvertising(&client3, advertising_connection_listener_3);
- OnDiscoveryEndpointFound(&client1_, advertising_endpoint_2);
- OnDiscoveryConnectionInitiated(&client1_, advertising_endpoint_2);
- OnDiscoveryEndpointFound(&client1_, advertising_endpoint_3);
- OnDiscoveryConnectionInitiated(&client1_, advertising_endpoint_3);
-
- // The CancellationFlag of endpoint_2 and endpoint_3 have been added. Default
- // Cancelled is false.
- EXPECT_FALSE(
- client1_.GetCancellationFlag(advertising_endpoint_2.id)->Cancelled());
- EXPECT_FALSE(
- client1_.GetCancellationFlag(advertising_endpoint_3.id)->Cancelled());
-
- client1_.CancelAllEndpoints();
-
- if (!feature_flags.enable_cancellation_flag) {
- // The CancellationFlag of endpoint_2 and endpoint_3 will not be removed
- // since it is not added. The default flag returned as Cancelled being true,
- // but Cancelled requested is false since the FeatureFlag is off.
- EXPECT_FALSE(
- client1_.GetCancellationFlag(advertising_endpoint_2.id)->Cancelled());
- EXPECT_FALSE(
- client1_.GetCancellationFlag(advertising_endpoint_3.id)->Cancelled());
- } else {
- // Expect the CancellationFlag of endpoint_2 and endpoint_3 has been
- // removed. The Cancelled is always true as the default flag being returned.
- EXPECT_TRUE(
- client1_.GetCancellationFlag(advertising_endpoint_2.id)->Cancelled());
- EXPECT_TRUE(
- client1_.GetCancellationFlag(advertising_endpoint_3.id)->Cancelled());
- }
-}
-
-INSTANTIATE_TEST_SUITE_P(ParametrisedClientProxyTest, ClientProxyTest,
- ::testing::ValuesIn(kTestCases));
-
-TEST_F(ClientProxyTest, ConstructorDestructorWorks) { SUCCEED(); }
-
-TEST_F(ClientProxyTest, ClientIdIsUnique) {
- EXPECT_NE(client1_.GetClientId(), client2_.GetClientId());
-}
-
-TEST_F(ClientProxyTest, GeneratedEndpointIdIsUnique) {
- EXPECT_NE(client1_.GetLocalEndpointId(), client2_.GetLocalEndpointId());
-}
-
-TEST_F(ClientProxyTest, ResetClearsState) {
- client1_.Reset();
- EXPECT_FALSE(client1_.IsAdvertising());
- EXPECT_FALSE(client1_.IsDiscovering());
- EXPECT_TRUE(client1_.GetAdvertisingServiceId().empty());
- EXPECT_TRUE(client1_.GetDiscoveryServiceId().empty());
-}
-
-TEST_F(ClientProxyTest, StartedAdvertisingChangesStateFromIdle) {
- client1_.StartedAdvertising(service_id_, strategy_, {}, {});
-
- EXPECT_TRUE(client1_.IsAdvertising());
- EXPECT_FALSE(client1_.IsDiscovering());
- EXPECT_EQ(client1_.GetAdvertisingServiceId(), service_id_);
- EXPECT_TRUE(client1_.GetDiscoveryServiceId().empty());
-}
-
-TEST_F(ClientProxyTest, StartedDiscoveryChangesStateFromIdle) {
- client1_.StartedDiscovery(service_id_, strategy_, {}, {});
-
- EXPECT_FALSE(client1_.IsAdvertising());
- EXPECT_TRUE(client1_.IsDiscovering());
- EXPECT_TRUE(client1_.GetAdvertisingServiceId().empty());
- EXPECT_EQ(client1_.GetDiscoveryServiceId(), service_id_);
-}
-
-TEST_F(ClientProxyTest, OnEndpointFoundFiresNotificationInDiscovery) {
- Endpoint advertising_endpoint =
- StartAdvertising(&client1_, advertising_connection_listener_);
- StartDiscovery(&client2_, discovery_listener_);
- OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
-}
-
-TEST_F(ClientProxyTest, OnEndpointLostFiresNotificationInDiscovery) {
- Endpoint advertising_endpoint =
- StartAdvertising(&client1_, advertising_connection_listener_);
- StartDiscovery(&client2_, discovery_listener_);
- OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
- OnDiscoveryEndpointLost(&client2_, advertising_endpoint);
-}
-
-TEST_F(ClientProxyTest, OnConnectionInitiatedFiresNotificationInDiscovery) {
- Endpoint advertising_endpoint =
- StartAdvertising(&client1_, advertising_connection_listener_);
- StartDiscovery(&client2_, discovery_listener_);
- OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
- OnDiscoveryConnectionInitiated(&client2_, advertising_endpoint);
-}
-
-TEST_F(ClientProxyTest, OnBandwidthChangedFiresNotificationInDiscovery) {
- Endpoint advertising_endpoint =
- StartAdvertising(&client1_, advertising_connection_listener_);
- StartDiscovery(&client2_, discovery_listener_);
- OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
- OnDiscoveryConnectionInitiated(&client2_, advertising_endpoint);
- OnDiscoveryConnectionLocalAccepted(&client2_, advertising_endpoint);
- OnDiscoveryConnectionRemoteAccepted(&client2_, advertising_endpoint);
- OnDiscoveryConnectionAccepted(&client2_, advertising_endpoint);
- OnDiscoveryBandwidthChanged(&client2_, advertising_endpoint);
-}
-
-TEST_F(ClientProxyTest, OnDisconnectedFiresNotificationInDiscovery) {
- Endpoint advertising_endpoint =
- StartAdvertising(&client1_, advertising_connection_listener_);
- StartDiscovery(&client2_, discovery_listener_);
- OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
- OnDiscoveryConnectionInitiated(&client2_, advertising_endpoint);
- OnDiscoveryConnectionDisconnected(&client2_, advertising_endpoint);
-}
-
-TEST_F(ClientProxyTest, LocalEndpointAcceptedConnectionChangesState) {
- Endpoint advertising_endpoint =
- StartAdvertising(&client1_, advertising_connection_listener_);
- StartDiscovery(&client2_, discovery_listener_);
- OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
- OnDiscoveryConnectionInitiated(&client2_, advertising_endpoint);
- OnDiscoveryConnectionLocalAccepted(&client2_, advertising_endpoint);
-}
-
-TEST_F(ClientProxyTest, LocalEndpointRejectedConnectionChangesState) {
- Endpoint advertising_endpoint =
- StartAdvertising(&client1_, advertising_connection_listener_);
- StartDiscovery(&client2_, discovery_listener_);
- OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
- OnDiscoveryConnectionInitiated(&client2_, advertising_endpoint);
- OnDiscoveryConnectionLocalRejected(&client2_, advertising_endpoint);
-}
-
-TEST_F(ClientProxyTest, RemoteEndpointAcceptedConnectionChangesState) {
- Endpoint advertising_endpoint =
- StartAdvertising(&client1_, advertising_connection_listener_);
- StartDiscovery(&client2_, discovery_listener_);
- OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
- OnDiscoveryConnectionInitiated(&client2_, advertising_endpoint);
- OnDiscoveryConnectionRemoteAccepted(&client2_, advertising_endpoint);
-}
-
-TEST_F(ClientProxyTest, RemoteEndpointRejectedConnectionChangesState) {
- Endpoint advertising_endpoint =
- StartAdvertising(&client1_, advertising_connection_listener_);
- StartDiscovery(&client2_, discovery_listener_);
- OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
- OnDiscoveryConnectionInitiated(&client2_, advertising_endpoint);
- OnDiscoveryConnectionRemoteRejected(&client2_, advertising_endpoint);
-}
-
-TEST_F(ClientProxyTest, OnPayloadChangesState) {
- Endpoint advertising_endpoint =
- StartAdvertising(&client1_, advertising_connection_listener_);
- StartDiscovery(&client2_, discovery_listener_);
- OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
- OnDiscoveryConnectionInitiated(&client2_, advertising_endpoint);
- OnDiscoveryConnectionLocalAccepted(&client2_, advertising_endpoint);
- OnDiscoveryConnectionRemoteAccepted(&client2_, advertising_endpoint);
- OnDiscoveryConnectionAccepted(&client2_, advertising_endpoint);
- OnPayload(&client2_, advertising_endpoint);
-}
-
-TEST_F(ClientProxyTest, OnPayloadProgressChangesState) {
- Endpoint advertising_endpoint =
- StartAdvertising(&client1_, advertising_connection_listener_);
- StartDiscovery(&client2_, discovery_listener_);
- OnDiscoveryEndpointFound(&client2_, advertising_endpoint);
- OnDiscoveryConnectionInitiated(&client2_, advertising_endpoint);
- OnDiscoveryConnectionLocalAccepted(&client2_, advertising_endpoint);
- OnDiscoveryConnectionRemoteAccepted(&client2_, advertising_endpoint);
- OnDiscoveryConnectionAccepted(&client2_, advertising_endpoint);
- OnPayloadProgress(&client2_, advertising_endpoint);
-}
-
-TEST_F(ClientProxyTest,
- EndpointIdCacheWhenHighVizAdvertisementAgainImmediately) {
- ConnectionOptions advertising_options{.strategy = strategy_,
- .allowed =
- {
- .bluetooth = true,
- },
- .low_power = false};
-
- Endpoint advertising_endpoint_1 = StartAdvertising(
- &client1_, advertising_connection_listener_, advertising_options);
-
- StopAdvertising(&client1_);
-
- // Advertise immediately.
- Endpoint advertising_endpoint_2 = StartAdvertising(
- &client1_, advertising_connection_listener_, advertising_options);
-
- EXPECT_EQ(advertising_endpoint_1.id, advertising_endpoint_2.id);
-}
-
-TEST_F(ClientProxyTest,
- EndpointIdRotateWhenHighVizAdvertisementAgainForAWhile) {
- ConnectionOptions advertising_options{.strategy = strategy_,
- .allowed =
- {
- .bluetooth = true,
- },
- .low_power = false};
-
- Endpoint advertising_endpoint_1 = StartAdvertising(
- &client1_, advertising_connection_listener_, advertising_options);
-
- StopAdvertising(&client1_);
-
- // Wait to expire and then advertise.
- absl::SleepFor(ClientProxy::kHighPowerAdvertisementEndpointIdCacheTimeout +
- absl::Milliseconds(100));
- Endpoint advertising_endpoint_2 = StartAdvertising(
- &client1_, advertising_connection_listener_, advertising_options);
-
- EXPECT_NE(advertising_endpoint_1.id, advertising_endpoint_2.id);
-}
-
-TEST_F(ClientProxyTest,
- EndpointIdRotateWhenLowVizAdvertisementAfterHighVizAdvertisement) {
- ConnectionOptions high_viz_advertising_options{.strategy = strategy_,
- .allowed =
- {
- .bluetooth = true,
- },
- .low_power = false};
- Endpoint advertising_endpoint_1 =
- StartAdvertising(&client1_, advertising_connection_listener_,
- high_viz_advertising_options);
-
- StopAdvertising(&client1_);
-
- ConnectionOptions low_viz_advertising_options{.strategy = strategy_,
- .low_power = true};
-
- Endpoint advertising_endpoint_2 = StartAdvertising(
- &client1_, advertising_connection_listener_, low_viz_advertising_options);
-
- EXPECT_NE(advertising_endpoint_1.id, advertising_endpoint_2.id);
-}
-
-// Tests endpoint_id rotates when discover.
-TEST_F(ClientProxyTest, EndpointIdRotateWhenStartDiscovery) {
- ConnectionOptions advertising_options{.strategy = strategy_,
- .allowed =
- {
- .bluetooth = true,
- },
- .low_power = false};
-
- Endpoint advertising_endpoint_1 = StartAdvertising(
- &client1_, advertising_connection_listener_, advertising_options);
-
- StopAdvertising(&client1_);
- StartDiscovery(&client1_, discovery_listener_);
-
- Endpoint advertising_endpoint_2 = StartAdvertising(
- &client1_, advertising_connection_listener_, advertising_options);
-
- EXPECT_NE(advertising_endpoint_1.id, advertising_endpoint_2.id);
-}
-
-// Tests the low visibility mode with bluetooth disabled advertisment.
-TEST_F(ClientProxyTest,
- EndpointIdRotateWhenLowVizAdvertisementWithBluetoothDisabled) {
- ConnectionOptions advertising_options{.strategy = strategy_,
- .allowed = {
- .bluetooth = false,
- }};
-
- Endpoint advertising_endpoint_1 = StartAdvertising(
- &client1_, advertising_connection_listener_, advertising_options);
-
- StopAdvertising(&client1_);
-
- Endpoint advertising_endpoint_2 = StartAdvertising(
- &client1_, advertising_connection_listener_, advertising_options);
-
- EXPECT_NE(advertising_endpoint_1.id, advertising_endpoint_2.id);
-}
-
-// Tests the low visibility mode with low power advertisment.
-TEST_F(ClientProxyTest, EndpointIdRotateWhenLowVizAdvertisementWithLowPower) {
- ConnectionOptions advertising_options{.strategy = strategy_,
- .low_power = true};
-
- Endpoint advertising_endpoint_1 = StartAdvertising(
- &client1_, advertising_connection_listener_, advertising_options);
-
- StopAdvertising(&client1_);
-
- Endpoint advertising_endpoint_2 = StartAdvertising(
- &client1_, advertising_connection_listener_, advertising_options);
-
- EXPECT_NE(advertising_endpoint_1.id, advertising_endpoint_2.id);
-}
-
-} // namespace
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/encryption_runner.cc b/chromium/third_party/nearby/src/cpp/core/internal/encryption_runner.cc
deleted file mode 100644
index e81f6065791..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/encryption_runner.cc
+++ /dev/null
@@ -1,389 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/encryption_runner.h"
-
-#include <cinttypes>
-#include <cstdint>
-#include <memory>
-
-#include "securegcm/ukey2_handshake.h"
-#include "absl/strings/ascii.h"
-#include "absl/time/clock.h"
-#include "absl/time/time.h"
-#include "platform/base/base64_utils.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/exception.h"
-#include "platform/public/cancelable_alarm.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-
-constexpr absl::Duration kTimeout = absl::Seconds(15);
-constexpr std::int32_t kMaxUkey2VerificationStringLength = 32;
-constexpr std::int32_t kTokenLength = 5;
-constexpr securegcm::UKey2Handshake::HandshakeCipher kCipher =
- securegcm::UKey2Handshake::HandshakeCipher::P256_SHA512;
-
-// Transforms a raw UKEY2 token (which is a random ByteArray that's
-// kMaxUkey2VerificationStringLength long) into a kTokenLength string that only
-// uses [A-Z], [0-9], '_', '-' for each character.
-std::string ToHumanReadableString(const ByteArray& token) {
- std::string result = Base64Utils::Encode(token).substr(0, kTokenLength);
- absl::AsciiStrToUpper(&result);
- return result;
-}
-
-bool HandleEncryptionSuccess(const std::string& endpoint_id,
- std::unique_ptr<securegcm::UKey2Handshake> ukey2,
- const EncryptionRunner::ResultListener& listener) {
- std::unique_ptr<std::string> verification_string =
- ukey2->GetVerificationString(kMaxUkey2VerificationStringLength);
- if (verification_string == nullptr) {
- return false;
- }
-
- ByteArray raw_authentication_token(*verification_string);
-
- listener.on_success_cb(endpoint_id, std::move(ukey2),
- ToHumanReadableString(raw_authentication_token),
- raw_authentication_token);
-
- return true;
-}
-
-void CancelableAlarmRunnable(ClientProxy* client,
- const std::string& endpoint_id,
- EndpointChannel* endpoint_channel) {
- NEARBY_LOGS(INFO) << "Timing out encryption for client "
- << client->GetClientId()
- << " to endpoint_id=" << endpoint_id << " after "
- << absl::FormatDuration(kTimeout);
- endpoint_channel->Close();
-}
-
-class ServerRunnable final {
- public:
- ServerRunnable(ClientProxy* client, ScheduledExecutor* alarm_executor,
- const std::string& endpoint_id, EndpointChannel* channel,
- EncryptionRunner::ResultListener&& listener)
- : client_(client),
- alarm_executor_(alarm_executor),
- endpoint_id_(endpoint_id),
- channel_(channel),
- listener_(std::move(listener)) {}
-
- void operator()() const {
- CancelableAlarm timeout_alarm(
- "EncryptionRunner.StartServer() timeout",
- [this]() { CancelableAlarmRunnable(client_, endpoint_id_, channel_); },
- kTimeout, alarm_executor_);
-
- std::unique_ptr<securegcm::UKey2Handshake> server =
- securegcm::UKey2Handshake::ForResponder(kCipher);
- if (server == nullptr) {
- LogException();
- HandleHandshakeOrIoException(&timeout_alarm);
- return;
- }
-
- // Message 1 (Client Init)
- ExceptionOr<ByteArray> client_init = channel_->Read();
- if (!client_init.ok()) {
- LogException();
- HandleHandshakeOrIoException(&timeout_alarm);
- return;
- }
-
- securegcm::UKey2Handshake::ParseResult parse_result =
- server->ParseHandshakeMessage(std::string(client_init.result()));
-
- // Java code throws a HandshakeException / AlertException.
- if (!parse_result.success) {
- LogException();
- if (parse_result.alert_to_send != nullptr) {
- HandleAlertException(parse_result);
- }
- HandleHandshakeOrIoException(&timeout_alarm);
- return;
- }
-
- NEARBY_LOGS(INFO)
- << "In StartServer(), read UKEY2 Message 1 from endpoint(id="
- << endpoint_id_ << ").";
-
- // Message 2 (Server Init)
- std::unique_ptr<std::string> server_init =
- server->GetNextHandshakeMessage();
-
- // Java code throws a HandshakeException.
- if (server_init == nullptr) {
- LogException();
- HandleHandshakeOrIoException(&timeout_alarm);
- return;
- }
-
- Exception write_exception =
- channel_->Write(ByteArray(std::move(*server_init)));
- if (!write_exception.Ok()) {
- LogException();
- HandleHandshakeOrIoException(&timeout_alarm);
- return;
- }
-
- NEARBY_LOGS(INFO)
- << "In StartServer(), wrote UKEY2 Message 2 to endpoint(id="
- << endpoint_id_ << ").";
-
- // Message 3 (Client Finish)
- ExceptionOr<ByteArray> client_finish = channel_->Read();
-
- if (!client_finish.ok()) {
- LogException();
- HandleHandshakeOrIoException(&timeout_alarm);
- return;
- }
-
- parse_result =
- server->ParseHandshakeMessage(std::string(client_finish.result()));
-
- // Java code throws an AlertException or a HandshakeException.
- if (!parse_result.success) {
- LogException();
- if (parse_result.alert_to_send != nullptr) {
- HandleAlertException(parse_result);
- }
- HandleHandshakeOrIoException(&timeout_alarm);
- return;
- }
-
- NEARBY_LOGS(INFO)
- << "In StartServer(), read UKEY2 Message 3 from endpoint(id="
- << endpoint_id_ << ").";
-
- timeout_alarm.Cancel();
-
- if (!HandleEncryptionSuccess(endpoint_id_, std::move(server), listener_)) {
- LogException();
- HandleHandshakeOrIoException(&timeout_alarm);
- return;
- }
- }
-
- private:
- void LogException() const {
- NEARBY_LOGS(ERROR) << "In StartServer(), UKEY2 failed with endpoint(id="
- << endpoint_id_ << ").";
- }
-
- void HandleHandshakeOrIoException(CancelableAlarm* timeout_alarm) const {
- timeout_alarm->Cancel();
- listener_.on_failure_cb(endpoint_id_, channel_);
- }
-
- void HandleAlertException(
- const securegcm::UKey2Handshake::ParseResult& parse_result) const {
- Exception write_exception =
- channel_->Write(ByteArray(*parse_result.alert_to_send));
- if (!write_exception.Ok()) {
- NEARBY_LOGS(WARNING)
- << "In StartServer(), client " << client_->GetClientId()
- << " failed to pass the alert error message to endpoint(id="
- << endpoint_id_ << ").";
- }
- }
-
- ClientProxy* client_;
- ScheduledExecutor* alarm_executor_;
- const std::string endpoint_id_;
- EndpointChannel* channel_;
- EncryptionRunner::ResultListener listener_;
-};
-
-class ClientRunnable final {
- public:
- ClientRunnable(ClientProxy* client, ScheduledExecutor* alarm_executor,
- const std::string& endpoint_id, EndpointChannel* channel,
- EncryptionRunner::ResultListener&& listener)
- : client_(client),
- alarm_executor_(alarm_executor),
- endpoint_id_(endpoint_id),
- channel_(channel),
- listener_(std::move(listener)) {}
-
- void operator()() const {
- CancelableAlarm timeout_alarm(
- "EncryptionRunner.StartClient() timeout",
- [this]() { CancelableAlarmRunnable(client_, endpoint_id_, channel_); },
- kTimeout, alarm_executor_);
-
- std::unique_ptr<securegcm::UKey2Handshake> crypto =
- securegcm::UKey2Handshake::ForInitiator(kCipher);
-
- // Java code throws a HandshakeException.
- if (crypto == nullptr) {
- LogException();
- HandleHandshakeOrIoException(&timeout_alarm);
- return;
- }
-
- // Message 1 (Client Init)
- std::unique_ptr<std::string> client_init =
- crypto->GetNextHandshakeMessage();
-
- // Java code throws a HandshakeException.
- if (client_init == nullptr) {
- LogException();
- HandleHandshakeOrIoException(&timeout_alarm);
- return;
- }
-
- Exception write_init_exception = channel_->Write(ByteArray(*client_init));
- if (!write_init_exception.Ok()) {
- LogException();
- HandleHandshakeOrIoException(&timeout_alarm);
- return;
- }
-
- NEARBY_LOGS(INFO)
- << "In StartClient(), wrote UKEY2 Message 1 to endpoint(id="
- << endpoint_id_ << ").";
-
- // Message 2 (Server Init)
- ExceptionOr<ByteArray> server_init = channel_->Read();
-
- if (!server_init.ok()) {
- LogException();
- HandleHandshakeOrIoException(&timeout_alarm);
- return;
- }
-
- securegcm::UKey2Handshake::ParseResult parse_result =
- crypto->ParseHandshakeMessage(std::string(server_init.result()));
-
- // Java code throws an AlertException or a HandshakeException.
- if (!parse_result.success) {
- LogException();
- if (parse_result.alert_to_send != nullptr) {
- HandleAlertException(parse_result);
- }
- HandleHandshakeOrIoException(&timeout_alarm);
- return;
- }
-
- NEARBY_LOGS(INFO)
- << "In StartClient(), read UKEY2 Message 2 from endpoint(id="
- << endpoint_id_ << ").";
-
- // Message 3 (Client Finish)
- std::unique_ptr<std::string> client_finish =
- crypto->GetNextHandshakeMessage();
-
- // Java code throws a HandshakeException.
- if (client_finish == nullptr) {
- LogException();
- HandleHandshakeOrIoException(&timeout_alarm);
- return;
- }
-
- Exception write_finish_exception =
- channel_->Write(ByteArray(*client_finish));
- if (!write_finish_exception.Ok()) {
- LogException();
- HandleHandshakeOrIoException(&timeout_alarm);
- return;
- }
-
- NEARBY_LOGS(INFO)
- << "In StartClient(), wrote UKEY2 Message 3 to endpoint(id="
- << endpoint_id_ << ").";
-
- timeout_alarm.Cancel();
-
- if (!HandleEncryptionSuccess(endpoint_id_, std::move(crypto), listener_)) {
- LogException();
- HandleHandshakeOrIoException(&timeout_alarm);
- return;
- }
- }
-
- private:
- void LogException() const {
- NEARBY_LOGS(ERROR) << "In StartClient(), UKEY2 failed with endpoint(id="
- << endpoint_id_ << ").";
- }
-
- void HandleHandshakeOrIoException(CancelableAlarm* timeout_alarm) const {
- timeout_alarm->Cancel();
- listener_.on_failure_cb(endpoint_id_, channel_);
- }
-
- void HandleAlertException(
- const securegcm::UKey2Handshake::ParseResult& parse_result) const {
- Exception write_exception =
- channel_->Write(ByteArray(*parse_result.alert_to_send));
- if (!write_exception.Ok()) {
- NEARBY_LOGS(WARNING)
- << "In StartClient(), client " << client_->GetClientId()
- << " failed to pass the alert error message to endpoint(id="
- << endpoint_id_ << ").";
- }
- }
-
- ClientProxy* client_;
- ScheduledExecutor* alarm_executor_;
- const std::string endpoint_id_;
- EndpointChannel* channel_;
- EncryptionRunner::ResultListener listener_;
-};
-
-} // namespace
-
-EncryptionRunner::~EncryptionRunner() {
- // Stop all the ongoing Runnables (as gracefully as possible).
- client_executor_.Shutdown();
- server_executor_.Shutdown();
- alarm_executor_.Shutdown();
-}
-
-void EncryptionRunner::StartServer(
- ClientProxy* client, const std::string& endpoint_id,
- EndpointChannel* endpoint_channel,
- EncryptionRunner::ResultListener&& listener) {
- server_executor_.Execute(
- "encryption-server",
- [runnable{ServerRunnable(client, &alarm_executor_, endpoint_id,
- endpoint_channel, std::move(listener))}]() {
- runnable();
- });
-}
-
-void EncryptionRunner::StartClient(
- ClientProxy* client, const std::string& endpoint_id,
- EndpointChannel* endpoint_channel,
- EncryptionRunner::ResultListener&& listener) {
- client_executor_.Execute(
- "encryption-client",
- [runnable{ClientRunnable(client, &alarm_executor_, endpoint_id,
- endpoint_channel, std::move(listener))}]() {
- runnable();
- });
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/encryption_runner.h b/chromium/third_party/nearby/src/cpp/core/internal/encryption_runner.h
deleted file mode 100644
index 452fa627fec..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/encryption_runner.h
+++ /dev/null
@@ -1,86 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_ENCRYPTION_RUNNER_H_
-#define CORE_INTERNAL_ENCRYPTION_RUNNER_H_
-
-#include <string>
-
-#include "securegcm/ukey2_handshake.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/endpoint_channel.h"
-#include "core/listeners.h"
-#include "platform/base/byte_array.h"
-#include "platform/public/scheduled_executor.h"
-#include "platform/public/single_thread_executor.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Encrypts a connection over UKEY2.
-//
-// NOTE: Stalled EndpointChannels will be disconnected after kTimeout.
-// This is to prevent unverified endpoints from maintaining an
-// indefinite connection to us.
-class EncryptionRunner {
- public:
- EncryptionRunner() = default;
- ~EncryptionRunner();
-
- struct ResultListener {
- // @EncryptionRunnerThread
- std::function<void(const std::string& endpoint_id,
- std::unique_ptr<securegcm::UKey2Handshake> ukey2,
- const std::string& auth_token,
- const ByteArray& raw_auth_token)>
- on_success_cb =
- DefaultCallback<const std::string&,
- std::unique_ptr<securegcm::UKey2Handshake>,
- const std::string&, const ByteArray&>();
-
- // Encryption has failed. The remote_endpoint_id and channel are given so
- // that any pending state can be cleaned up.
- //
- // We return the EndpointChannel because, at this stage, simultaneous
- // connections are a possibility. Use this channel to verify that the state
- // you're cleaning up is for this EndpointChannel, and not state for another
- // channel to the same endpoint.
- //
- // @EncryptionRunnerThread
- std::function<void(const std::string& endpoint_id,
- EndpointChannel* channel)>
- on_failure_cb = DefaultCallback<const std::string&, EndpointChannel*>();
- };
-
- // @AnyThread
- void StartServer(ClientProxy* client, const std::string& endpoint_id,
- EndpointChannel* endpoint_channel,
- ResultListener&& result_listener);
- // @AnyThread
- void StartClient(ClientProxy* client, const std::string& endpoint_id,
- EndpointChannel* endpoint_channel,
- ResultListener&& result_listener);
-
- private:
- ScheduledExecutor alarm_executor_;
- SingleThreadExecutor server_executor_;
- SingleThreadExecutor client_executor_;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_ENCRYPTION_RUNNER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/encryption_runner_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/encryption_runner_test.cc
deleted file mode 100644
index 06720e3385e..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/encryption_runner_test.cc
+++ /dev/null
@@ -1,150 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/encryption_runner.h"
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/time/clock.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/endpoint_channel.h"
-#include "platform/base/byte_array.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/pipe.h"
-#include "platform/public/system_clock.h"
-#include "proto/connections_enums.pb.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-
-using ::location::nearby::proto::connections::Medium;
-
-class FakeEndpointChannel : public EndpointChannel {
- public:
- FakeEndpointChannel(InputStream* in, OutputStream* out)
- : in_(in), out_(out) {}
- ExceptionOr<ByteArray> Read() override {
- read_timestamp_ = SystemClock::ElapsedRealtime();
- return in_ ? in_->Read(Pipe::kChunkSize)
- : ExceptionOr<ByteArray>{Exception::kIo};
- }
- Exception Write(const ByteArray& data) override {
- write_timestamp_ = SystemClock::ElapsedRealtime();
- return out_ ? out_->Write(data) : Exception{Exception::kIo};
- }
- void Close() override {
- if (in_) in_->Close();
- if (out_) out_->Close();
- }
- void Close(proto::connections::DisconnectionReason reason) override {
- Close();
- }
- std::string GetType() const override { return "fake-channel-type"; }
- std::string GetName() const override { return "fake-channel"; }
- Medium GetMedium() const override { return Medium::BLE; }
- int GetMaxTransmitPacketSize() const override { return 512; }
- void EnableEncryption(std::shared_ptr<EncryptionContext> context) override {}
- void DisableEncryption() override {}
- bool IsPaused() const override { return false; }
- void Pause() override {}
- void Resume() override {}
- absl::Time GetLastReadTimestamp() const override { return read_timestamp_; }
- absl::Time GetLastWriteTimestamp() const override { return write_timestamp_; }
- void SetAnalyticsRecorder(analytics::AnalyticsRecorder* analytics_recorder,
- const std::string& endpoint_id) override {}
-
- private:
- InputStream* in_ = nullptr;
- OutputStream* out_ = nullptr;
- absl::Time read_timestamp_ = absl::InfinitePast();
- absl::Time write_timestamp_ = absl::InfinitePast();
-};
-
-struct User {
- User(Pipe* reader, Pipe* writer)
- : channel(&reader->GetInputStream(), &writer->GetOutputStream()) {}
-
- FakeEndpointChannel channel;
- EncryptionRunner crypto;
- ClientProxy client;
-};
-
-struct Response {
- enum class Status {
- kUnknown = 0,
- kDone = 1,
- kFailed = 2,
- };
-
- CountDownLatch latch{2};
- Status server_status = Status::kUnknown;
- Status client_status = Status::kUnknown;
-};
-
-TEST(EncryptionRunnerTest, ConstructorDestructorWorks) { EncryptionRunner enc; }
-
-TEST(EncryptionRunnerTest, ReadWrite) {
- Pipe from_a_to_b;
- Pipe from_b_to_a;
- User user_a(/*reader=*/&from_b_to_a, /*writer=*/&from_a_to_b);
- User user_b(/*reader=*/&from_a_to_b, /*writer=*/&from_b_to_a);
- Response response;
-
- user_a.crypto.StartServer(
- &user_a.client, "endpoint_id", &user_a.channel,
- {
- .on_success_cb =
- [&response](const std::string& endpoint_id,
- std::unique_ptr<securegcm::UKey2Handshake> ukey2,
- const std::string& auth_token,
- const ByteArray& raw_auth_token) {
- response.server_status = Response::Status::kDone;
- response.latch.CountDown();
- },
- .on_failure_cb =
- [&response](const std::string& endpoint_id,
- EndpointChannel* channel) {
- response.server_status = Response::Status::kFailed;
- response.latch.CountDown();
- },
- });
- user_b.crypto.StartClient(
- &user_b.client, "endpoint_id", &user_b.channel,
- {
- .on_success_cb =
- [&response](const std::string& endpoint_id,
- std::unique_ptr<securegcm::UKey2Handshake> ukey2,
- const std::string& auth_token,
- const ByteArray& raw_auth_token) {
- response.client_status = Response::Status::kDone;
- response.latch.CountDown();
- },
- .on_failure_cb =
- [&response](const std::string& endpoint_id,
- EndpointChannel* channel) {
- response.client_status = Response::Status::kFailed;
- response.latch.CountDown();
- },
- });
- EXPECT_TRUE(response.latch.Await(absl::Milliseconds(5000)).result());
- EXPECT_EQ(response.server_status, Response::Status::kDone);
- EXPECT_EQ(response.client_status, Response::Status::kDone);
-}
-
-} // namespace
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/endpoint_channel.h b/chromium/third_party/nearby/src/cpp/core/internal/endpoint_channel.h
deleted file mode 100644
index 4d9bef3948a..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/endpoint_channel.h
+++ /dev/null
@@ -1,107 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_ENDPOINT_CHANNEL_H_
-#define CORE_INTERNAL_ENDPOINT_CHANNEL_H_
-
-#include <cstdint>
-#include <string>
-
-#include "securegcm/d2d_connection_context_v1.h"
-#include "absl/time/clock.h"
-#include "analytics/analytics_recorder.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/exception.h"
-#include "platform/public/mutex.h"
-#include "proto/connections_enums.pb.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-class EndpointChannel {
- public:
- virtual ~EndpointChannel() = default;
-
- using EncryptionContext = ::securegcm::D2DConnectionContextV1;
-
- virtual ExceptionOr<ByteArray>
- Read() = 0; // throws Exception::IO, Exception::INTERRUPTED
-
- virtual Exception Write(const ByteArray& data) = 0; // throws Exception::IO
-
- // Closes this EndpointChannel, without tracking the closure in analytics.
- virtual void Close() = 0;
-
- // Closes this EndpointChannel and records the closure with the given reason.
- virtual void Close(proto::connections::DisconnectionReason reason) = 0;
-
- // Returns a one-word type descriptor for the concrete EndpointChannel
- // implementation that can be used in log messages; eg: BLUETOOTH, BLE, WIFI.
- virtual std::string GetType() const = 0;
-
- // Returns the name of the EndpointChannel.
- virtual std::string GetName() const = 0;
-
- // Returns the analytics enum representing the medium of this EndpointChannel.
- virtual proto::connections::Medium GetMedium() const = 0;
-
- // Returns the maximum supported transmit packet size(MTU) for the underlying
- // transport.
- virtual int GetMaxTransmitPacketSize() const = 0;
-
- // Enables encryption on the EndpointChannel.
- virtual void EnableEncryption(std::shared_ptr<EncryptionContext> context) = 0;
-
- // Disables encryption on the EndpointChannel.
- virtual void DisableEncryption() = 0;
-
- // True if the EndpointChannel is currently pausing all writes.
- virtual bool IsPaused() const = 0;
-
- // Pauses all writes on this EndpointChannel until resume() is called.
- virtual void Pause() = 0;
-
- // Resumes any writes on this EndpointChannel that were suspended when pause()
- // was called.
- virtual void Resume() = 0;
-
- // Returns the timestamp of the last read from this endpoint, or -1 if no
- // reads have occurred.
- virtual absl::Time GetLastReadTimestamp() const = 0;
-
- // Returns the timestamp of the last write to this endpoint, or -1 if no
- // writes have occurred.
- virtual absl::Time GetLastWriteTimestamp() const = 0;
-
- // Sets the AnalyticsRecorder instance for analytics.
- virtual void SetAnalyticsRecorder(
- analytics::AnalyticsRecorder* analytics_recorder,
- const std::string& endpoint_id) = 0;
-};
-
-inline bool operator==(const EndpointChannel& lhs, const EndpointChannel& rhs) {
- return (lhs.GetType() == rhs.GetType()) && (lhs.GetName() == rhs.GetName()) &&
- (lhs.GetMedium() == rhs.GetMedium());
-}
-
-inline bool operator!=(const EndpointChannel& lhs, const EndpointChannel& rhs) {
- return !(lhs == rhs);
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_ENDPOINT_CHANNEL_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/endpoint_channel_manager.cc b/chromium/third_party/nearby/src/cpp/core/internal/endpoint_channel_manager.cc
deleted file mode 100644
index 55cead7e84f..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/endpoint_channel_manager.cc
+++ /dev/null
@@ -1,187 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/endpoint_channel_manager.h"
-
-#include <memory>
-#include <string>
-#include <utility>
-
-#include "absl/time/time.h"
-#include "core/internal/offline_frames.h"
-#include "platform/base/feature_flags.h"
-#include "platform/public/logging.h"
-#include "platform/public/mutex.h"
-#include "platform/public/mutex_lock.h"
-#include "platform/public/system_clock.h"
-#include "proto/connections/offline_wire_formats.pb.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-namespace {
-const absl::Duration kDataTransferDelay = absl::Milliseconds(500);
-}
-
-EndpointChannelManager::~EndpointChannelManager() {
- NEARBY_LOG(INFO, "Initiating shutdown of EndpointChannelManager.");
- MutexLock lock(&mutex_);
- channel_state_.DestroyAll();
- NEARBY_LOG(INFO, "EndpointChannelManager has shut down.");
-}
-
-void EndpointChannelManager::RegisterChannelForEndpoint(
- ClientProxy* client, const std::string& endpoint_id,
- std::unique_ptr<EndpointChannel> channel) {
- MutexLock lock(&mutex_);
-
- NEARBY_LOGS(INFO) << "EndpointChannelManager registered channel of type "
- << channel->GetType() << " to endpoint " << endpoint_id;
- SetActiveEndpointChannel(client, endpoint_id, std::move(channel));
-
- NEARBY_LOG(INFO, "Registered channel: id=%s", endpoint_id.c_str());
-}
-
-void EndpointChannelManager::ReplaceChannelForEndpoint(
- ClientProxy* client, const std::string& endpoint_id,
- std::unique_ptr<EndpointChannel> channel) {
- MutexLock lock(&mutex_);
-
- auto* endpoint = channel_state_.LookupEndpointData(endpoint_id);
- if (endpoint != nullptr && endpoint->channel == nullptr) {
- NEARBY_LOGS(INFO) << "EndpointChannelManager is missing channel while "
- "trying to update: endpoint "
- << endpoint_id;
- }
-
- SetActiveEndpointChannel(client, endpoint_id, std::move(channel));
-}
-
-bool EndpointChannelManager::EncryptChannelForEndpoint(
- const std::string& endpoint_id,
- std::unique_ptr<EncryptionContext> context) {
- MutexLock lock(&mutex_);
-
- channel_state_.UpdateEncryptionContextForEndpoint(endpoint_id,
- std::move(context));
- auto* endpoint = channel_state_.LookupEndpointData(endpoint_id);
- return channel_state_.EncryptChannel(endpoint);
-}
-
-std::shared_ptr<EndpointChannel> EndpointChannelManager::GetChannelForEndpoint(
- const std::string& endpoint_id) {
- MutexLock lock(&mutex_);
-
- auto* endpoint = channel_state_.LookupEndpointData(endpoint_id);
- if (endpoint == nullptr) {
- NEARBY_LOGS(INFO) << "No channel info for endpoint " << endpoint_id;
- return {};
- }
-
- return endpoint->channel;
-}
-
-void EndpointChannelManager::SetActiveEndpointChannel(
- ClientProxy* client, const std::string& endpoint_id,
- std::unique_ptr<EndpointChannel> channel) {
- // Update the channel first, then encrypt this new channel, if
- // crypto context is present.
- channel->SetAnalyticsRecorder(&client->GetAnalyticsRecorder(), endpoint_id);
- channel_state_.UpdateChannelForEndpoint(endpoint_id, std::move(channel));
-
- auto* endpoint = channel_state_.LookupEndpointData(endpoint_id);
- if (endpoint->IsEncrypted()) channel_state_.EncryptChannel(endpoint);
-}
-
-int EndpointChannelManager::GetConnectedEndpointsCount() const {
- MutexLock lock(&mutex_);
- return channel_state_.GetConnectedEndpointsCount();
-}
-
-///////////////////////////////// ChannelState /////////////////////////////////
-
-// endpoint - channel endpoint to encrypt
-bool EndpointChannelManager::ChannelState::EncryptChannel(
- EndpointChannelManager::ChannelState::EndpointData* endpoint) {
- if (endpoint != nullptr && endpoint->channel != nullptr &&
- endpoint->context != nullptr) {
- endpoint->channel->EnableEncryption(endpoint->context);
- return true;
- }
- return false;
-}
-
-EndpointChannelManager::ChannelState::EndpointData*
-EndpointChannelManager::ChannelState::LookupEndpointData(
- const std::string& endpoint_id) {
- auto item = endpoints_.find(endpoint_id);
- return item != endpoints_.end() ? &item->second : nullptr;
-}
-
-void EndpointChannelManager::ChannelState::UpdateChannelForEndpoint(
- const std::string& endpoint_id, std::unique_ptr<EndpointChannel> channel) {
- // Create EndpointData instance, if necessary, and populate channel.
- endpoints_[endpoint_id].channel = std::move(channel);
-}
-
-void EndpointChannelManager::ChannelState::UpdateEncryptionContextForEndpoint(
- const std::string& endpoint_id,
- std::unique_ptr<EncryptionContext> context) {
- // Create EndpointData instance, if necessary, and populate crypto context.
- endpoints_[endpoint_id].context = std::move(context);
-}
-
-bool EndpointChannelManager::ChannelState::RemoveEndpoint(
- const std::string& endpoint_id,
- proto::connections::DisconnectionReason reason) {
- auto item = endpoints_.find(endpoint_id);
- if (item == endpoints_.end()) return false;
- item->second.disconnect_reason = reason;
- auto channel = item->second.channel;
- if (channel) {
- // If the channel was paused (i.e. during a bandwidth upgrade negotiation)
- // we resume to ensure the thread won't hang when trying to write to it.
- channel->Resume();
-
- channel->Write(parser::ForDisconnection());
- NEARBY_LOGS(INFO)
- << "EndpointChannelManager reported the disconnection to endpoint "
- << endpoint_id;
- SystemClock::Sleep(kDataTransferDelay);
- }
- endpoints_.erase(item);
- return true;
-}
-
-bool EndpointChannelManager::UnregisterChannelForEndpoint(
- const std::string& endpoint_id) {
- MutexLock lock(&mutex_);
-
- if (!channel_state_.RemoveEndpoint(
- endpoint_id,
- proto::connections::DisconnectionReason::LOCAL_DISCONNECTION)) {
- return false;
- }
-
- NEARBY_LOGS(INFO)
- << "EndpointChannelManager unregistered channel for endpoint "
- << endpoint_id;
-
- return true;
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/endpoint_channel_manager.h b/chromium/third_party/nearby/src/cpp/core/internal/endpoint_channel_manager.h
deleted file mode 100644
index 7ec1e1a1954..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/endpoint_channel_manager.h
+++ /dev/null
@@ -1,172 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_ENDPOINT_CHANNEL_MANAGER_H_
-#define CORE_INTERNAL_ENDPOINT_CHANNEL_MANAGER_H_
-
-#include <memory>
-#include <string>
-
-#include "securegcm/d2d_connection_context_v1.h"
-#include "absl/container/flat_hash_map.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/endpoint_channel.h"
-#include "platform/public/logging.h"
-#include "platform/public/mutex.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// NOTE(std::string):
-// All the strings in internal class public interfaces should be exchanged as
-// const std::string& if they are immutable, and as std::string if they are
-// mutable.
-// This is to keep all the internal classes compatible with each other,
-// and minimize resources spent on the type conversion.
-// Project-wide, strings are either passed around as reference (which has
-// zero maintenance costs, and sizeof(void*) memory usage => passed around in a
-// CPU register), and whenever lifetime etension is required, it must be copied
-// to std::string instance (which will again propagate as a const reference
-// within it's lifetime domain).
-
-// Manages the communication channels to all the remote endpoints with which we
-// are interacting.
-class EndpointChannelManager final {
- public:
- using EncryptionContext = EndpointChannel::EncryptionContext;
-
- ~EndpointChannelManager();
-
- // Registers the initial EndpointChannel to be associated with an endpoint;
- // if there already exists a previously-associated EndpointChannel, that will
- // be closed before continuing the registration.
- void RegisterChannelForEndpoint(ClientProxy* client,
- const std::string& endpoint_id,
- std::unique_ptr<EndpointChannel> channel)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Replaces the EndpointChannel to be associated with an endpoint from here on
- // in, transferring the encryption context from the previous EndpointChannel
- // to the newly-provided EndpointChannel.
- void ReplaceChannelForEndpoint(ClientProxy* client,
- const std::string& endpoint_id,
- std::unique_ptr<EndpointChannel> channel)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- bool EncryptChannelForEndpoint(const std::string& endpoint_id,
- std::unique_ptr<EncryptionContext> context)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // NOTE(shared_ptr<> usage):
- //
- // EndpointChannelManager is holding an EndpointChannel instance;
- // GetChannelForEndpoint() is passing ownership over to a worker thread.
- // It is not a pointer passing but an ownership passing, to guarantee that
- // channel instance will not disappear underneath the feet of a worker thread
- // inside EndpointManager [ EndpointManager::EndpointChannelLoopRunnable() ].
- // If it is just a pointer, Channel will get destroyed while in use by a
- // worker thread. shared_ptr is a simple and reliable tool to avoid that.
- //
- // The reason why it can not be std::unique_ptr<> is: there are other code
- // paths that expect to be able to read the pointer value multiple times, from
- // multiple places (each of them needs "ownership" for the duration of their
- // use). EndpointManager::SendTransferFrameBytes() is another such place.
- // If EndpointChannelManager replaces the current channel, and any (or both)
- // EndpointManager methods that use a channel are running, it is better to
- // have a shared ownership.
- std::shared_ptr<EndpointChannel> GetChannelForEndpoint(
- const std::string& endpoint_id) ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns true if 'endpoint_id' actually had a registered EndpointChannel.
- // IOW, a return of false signifies a no-op.
- bool UnregisterChannelForEndpoint(const std::string& endpoint_id)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- int GetConnectedEndpointsCount() const ABSL_LOCKS_EXCLUDED(mutex_);
-
- private:
- // Tracks channel state for all endpoints. This includes what EndpointChannel
- // the endpoint is currently using and whether or not the EndpointChannel has
- // been encrypted yet.
- class ChannelState {
- public:
- struct EndpointData {
- EndpointData() = default;
- EndpointData(EndpointData&&) = default;
- EndpointData& operator=(EndpointData&&) = default;
- ~EndpointData() {
- if (channel != nullptr) {
- channel->Close(disconnect_reason);
- }
- }
-
- // True if we have a 'context' for the endpoint.
- bool IsEncrypted() const { return context != nullptr; }
-
- std::shared_ptr<EndpointChannel> channel;
- std::shared_ptr<EncryptionContext> context;
- proto::connections::DisconnectionReason disconnect_reason =
- proto::connections::DisconnectionReason::UNKNOWN_DISCONNECTION_REASON;
- };
-
- ChannelState() = default;
- ~ChannelState() { DestroyAll(); }
- ChannelState(ChannelState&&) = default;
- ChannelState& operator=(ChannelState&&) = default;
-
- // Provides a way to destroy contents of a container, while holding a lock.
- void DestroyAll() { endpoints_.clear(); }
- // Return pointer to endpoint data, or nullptr, it not found.
- EndpointData* LookupEndpointData(const std::string& endpoint_id);
-
- // Stores a new EndpointChannel for the endpoint.
- // Prevoius one is destroyed, if it existed.
- void UpdateChannelForEndpoint(const std::string& endpoint_id,
- std::unique_ptr<EndpointChannel> channel);
-
- // Stores a new EncryptionContext for the endpoint.
- // Prevoius one is destroyed, if it existed.
- void UpdateEncryptionContextForEndpoint(
- const std::string& endpoint_id,
- std::unique_ptr<EncryptionContext> context);
-
- // Removes all knowledge of this endpoint, cleaning up as necessary.
- // Returns false if the endpoint was not found.
- bool RemoveEndpoint(const std::string& endpoint_id,
- proto::connections::DisconnectionReason reason);
-
- bool EncryptChannel(EndpointData* endpoint);
- int GetConnectedEndpointsCount() const { return endpoints_.size(); }
-
- private:
- // Endpoint ID -> EndpointData. Contains everything we know about the
- // endpoint.
- absl::flat_hash_map<std::string, EndpointData> endpoints_;
- };
-
- void SetActiveEndpointChannel(ClientProxy* client,
- const std::string& endpoint_id,
- std::unique_ptr<EndpointChannel> channel)
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- mutable Mutex mutex_;
- ChannelState channel_state_ ABSL_GUARDED_BY(mutex_);
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_ENDPOINT_CHANNEL_MANAGER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/endpoint_channel_manager_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/endpoint_channel_manager_test.cc
deleted file mode 100644
index f278a1d26b9..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/endpoint_channel_manager_test.cc
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/endpoint_channel_manager.h"
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-TEST(EndpointChannelManagerTest, ConstructorDestructorWorks) {
- EndpointChannelManager mgr;
- SUCCEED();
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/endpoint_manager.cc b/chromium/third_party/nearby/src/cpp/core/internal/endpoint_manager.cc
deleted file mode 100644
index e050b9f45b1..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/endpoint_manager.cc
+++ /dev/null
@@ -1,675 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/endpoint_manager.h"
-
-#include <memory>
-#include <utility>
-
-#include "core/internal/endpoint_channel.h"
-#include "core/internal/offline_frames.h"
-#include "platform/base/exception.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/logging.h"
-#include "platform/public/mutex_lock.h"
-#include "proto/connections/offline_wire_formats.pb.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-using ::location::nearby::proto::connections::Medium;
-
-constexpr absl::Duration EndpointManager::kProcessEndpointDisconnectionTimeout;
-constexpr absl::Time EndpointManager::kInvalidTimestamp;
-
-class EndpointManager::LockedFrameProcessor {
- public:
- explicit LockedFrameProcessor(FrameProcessorWithMutex* fp)
- : lock_{std::make_unique<MutexLock>(&fp->mutex_)},
- frame_processor_with_mutex_{fp} {}
-
- // Constructor of a no-op object.
- LockedFrameProcessor() {}
-
- explicit operator bool() const { return get() != nullptr; }
-
- FrameProcessor* operator->() const { return get(); }
-
- void set(FrameProcessor* frame_processor) {
- if (frame_processor_with_mutex_)
- frame_processor_with_mutex_->frame_processor_ = frame_processor;
- }
-
- FrameProcessor* get() const {
- return frame_processor_with_mutex_
- ? frame_processor_with_mutex_->frame_processor_
- : nullptr;
- }
-
- void reset() {
- if (frame_processor_with_mutex_)
- frame_processor_with_mutex_->frame_processor_ = nullptr;
- }
-
- private:
- std::unique_ptr<MutexLock> lock_;
- FrameProcessorWithMutex* frame_processor_with_mutex_ = nullptr;
-};
-
-// A Runnable that continuously grabs the most recent EndpointChannel available
-// for an endpoint.
-//
-// handler - Called whenever an EndpointChannel is available for endpointId.
-// Implementations are expected to read/write freely to the
-// EndpointChannel until an Exception::IO is thrown. Once an
-// Exception::IO occurs, a check will be performed to see if another
-// EndpointChannel is available for the given endpoint and, if so,
-// handler(EndpointChannel) will be called again.
-void EndpointManager::EndpointChannelLoopRunnable(
- const std::string& runnable_name, ClientProxy* client,
- const std::string& endpoint_id,
- std::function<ExceptionOr<bool>(EndpointChannel*)> handler) {
- // EndpointChannelManager will not let multiple channels exist simultaneously
- // for the same endpoint_id; it will be closing "old" channels as new ones
- // come.
- // Closed channel will return Exception::kIo for any Read, and loop (below)
- // will retry and attempt to pick another channel.
- // If channel is deleted (no mapping), or it is still the same channel
- // (same Medium) on which we got the Exception::kIo, we terminate the loop.
- NEARBY_LOG(INFO, "Started worker loop name=%s, endpoint=%s",
- runnable_name.c_str(), endpoint_id.c_str());
- Medium last_failed_medium = Medium::UNKNOWN_MEDIUM;
- while (true) {
- // It's important to keep re-fetching the EndpointChannel for an endpoint
- // because it can be changed out from under us (for example, when we
- // upgrade from Bluetooth to Wifi).
- std::shared_ptr<EndpointChannel> channel =
- channel_manager_->GetChannelForEndpoint(endpoint_id);
- if (channel == nullptr) {
- NEARBY_LOG(INFO, "Endpoint channel is nullptr, bail out.");
- break;
- }
-
- // If we're looping back around after a failure, and there's not a new
- // EndpointChannel for this endpoint, there's nothing more to do here.
- if ((last_failed_medium != Medium::UNKNOWN_MEDIUM) &&
- (channel->GetMedium() == last_failed_medium)) {
- NEARBY_LOG(
- INFO, "No new endpoint channel is found after a failure, exit loop.");
- break;
- }
-
- ExceptionOr<bool> keep_using_channel = handler(channel.get());
-
- if (!keep_using_channel.ok()) {
- Exception exception = keep_using_channel.GetException();
- // An "invalid proto" may be a final payload on a channel we're about to
- // close, so we'll loop back around once. We set |last_failed_medium| to
- // ensure we don't loop indefinitely. See crbug.com/1182031 for more
- // detail.
- if (exception.Raised(Exception::kInvalidProtocolBuffer)) {
- last_failed_medium = channel->GetMedium();
- NEARBY_LOGS(INFO)
- << "Received invalid protobuf message, re-fetching endpoint "
- "channel; last_failed_medium="
- << proto::connections::Medium_Name(last_failed_medium);
- continue;
- }
- if (exception.Raised(Exception::kIo)) {
- last_failed_medium = channel->GetMedium();
- NEARBY_LOGS(INFO)
- << "Endpoint channel IO exception; last_failed_medium="
- << proto::connections::Medium_Name(last_failed_medium);
- continue;
- }
- if (exception.Raised(Exception::kInterrupted)) {
- break;
- }
- }
-
- if (!keep_using_channel.result()) {
- NEARBY_LOGS(INFO) << "Dropping current channel: last medium="
- << proto::connections::Medium_Name(last_failed_medium);
- break;
- }
- }
- // Indicate we're out of the loop and it is ok to schedule another instance
- // if needed.
- NEARBY_LOGS(INFO) << "Worker going down; worker name=" << runnable_name
- << "; endpoint_id=" << endpoint_id;
- // Always clear out all state related to this endpoint before terminating
- // this thread.
- DiscardEndpoint(client, endpoint_id);
- NEARBY_LOGS(INFO) << "Worker done; worker name=" << runnable_name
- << "; endpoint_id=" << endpoint_id;
-}
-
-ExceptionOr<bool> EndpointManager::HandleData(
- const std::string& endpoint_id, ClientProxy* client,
- EndpointChannel* endpoint_channel) {
- // Read as much as we can from the healthy EndpointChannel - when it is no
- // longer in good shape (i.e. our read from it throws an Exception), our
- // super class will loop back around and try our luck in case there's been
- // a replacement for this endpoint since we last checked with the
- // EndpointChannelManager.
- while (true) {
- ExceptionOr<ByteArray> bytes = endpoint_channel->Read();
- if (!bytes.ok()) {
- NEARBY_LOG(INFO, "Stop reading on read-time exception: %d",
- bytes.exception());
- return ExceptionOr<bool>(bytes.exception());
- }
- ExceptionOr<OfflineFrame> wrapped_frame = parser::FromBytes(bytes.result());
- if (!wrapped_frame.ok()) {
- if (wrapped_frame.GetException().Raised(
- Exception::kInvalidProtocolBuffer)) {
- NEARBY_LOG(INFO, "Failed to decode; endpoint=%s; channel=%s; skip",
- endpoint_id.c_str(), endpoint_channel->GetType().c_str());
- continue;
- } else {
- NEARBY_LOG(INFO, "Stop reading on parse-time exception: %d",
- wrapped_frame.exception());
- return ExceptionOr<bool>(wrapped_frame.exception());
- }
- }
- OfflineFrame& frame = wrapped_frame.result();
-
- // Route the incoming offlineFrame to its registered processor.
- V1Frame::FrameType frame_type = parser::GetFrameType(frame);
- LockedFrameProcessor frame_processor = GetFrameProcessor(frame_type);
- if (!frame_processor) {
- // report messages without handlers, except KEEP_ALIVE, which has
- // no explicit handler.
- if (frame_type == V1Frame::KEEP_ALIVE) {
- NEARBY_LOG(INFO, "KeepAlive message for endpoint %s",
- endpoint_id.c_str());
- } else if (frame_type == V1Frame::DISCONNECTION) {
- NEARBY_LOG(INFO, "Disconnect message for endpoint %s",
- endpoint_id.c_str());
- endpoint_channel->Close();
- } else {
- NEARBY_LOGS(ERROR) << "Unhandled message: endpoint_id=" << endpoint_id
- << ", frame type="
- << V1Frame::FrameType_Name(frame_type);
- }
- continue;
- }
-
- frame_processor->OnIncomingFrame(frame, endpoint_id, client,
- endpoint_channel->GetMedium());
- }
-}
-
-ExceptionOr<bool> EndpointManager::HandleKeepAlive(
- EndpointChannel* endpoint_channel, absl::Duration keep_alive_interval,
- absl::Duration keep_alive_timeout, Mutex* keep_alive_waiter_mutex,
- ConditionVariable* keep_alive_waiter) {
- // Check if it has been too long since we received a frame from our endpoint.
- absl::Time last_read_time = endpoint_channel->GetLastReadTimestamp();
- absl::Duration duration_until_timeout =
- last_read_time == kInvalidTimestamp
- ? keep_alive_timeout
- : last_read_time + keep_alive_timeout -
- SystemClock::ElapsedRealtime();
- if (duration_until_timeout <= absl::ZeroDuration()) {
- return ExceptionOr<bool>(false);
- }
-
- // If we haven't written anything to the endpoint for a while, attempt to send
- // the KeepAlive frame over the endpoint channel. If the write fails, our
- // super class will loop back around and try our luck again in case there's
- // been a replacement for this endpoint.
- absl::Time last_write_time = endpoint_channel->GetLastWriteTimestamp();
- absl::Duration duration_until_write_keep_alive =
- last_write_time == kInvalidTimestamp
- ? keep_alive_interval
- : last_write_time + keep_alive_interval -
- SystemClock::ElapsedRealtime();
- if (duration_until_write_keep_alive <= absl::ZeroDuration()) {
- Exception write_exception = endpoint_channel->Write(parser::ForKeepAlive());
- if (!write_exception.Ok()) {
- return ExceptionOr<bool>(write_exception);
- }
- duration_until_write_keep_alive = keep_alive_interval;
- }
-
- absl::Duration wait_for =
- std::min(duration_until_timeout, duration_until_write_keep_alive);
- {
- MutexLock lock(keep_alive_waiter_mutex);
- Exception wait_exception = keep_alive_waiter->Wait(wait_for);
- if (!wait_exception.Ok()) {
- return ExceptionOr<bool>(wait_exception);
- }
- }
-
- return ExceptionOr<bool>(true);
-}
-
-bool operator==(const EndpointManager::FrameProcessor& lhs,
- const EndpointManager::FrameProcessor& rhs) {
- // We're comparing addresses because these objects are callbacks which need to
- // be matched by exact instances.
- return &lhs == &rhs;
-}
-
-bool operator<(const EndpointManager::FrameProcessor& lhs,
- const EndpointManager::FrameProcessor& rhs) {
- // We're comparing addresses because these objects are callbacks which need to
- // be matched by exact instances.
- return &lhs < &rhs;
-}
-
-EndpointManager::EndpointManager(EndpointChannelManager* manager)
- : channel_manager_(manager) {}
-
-EndpointManager::~EndpointManager() {
- NEARBY_LOG(INFO, "Initiating shutdown of EndpointManager.");
- CountDownLatch latch(1);
- RunOnEndpointManagerThread("bring-down-endpoints", [this, &latch]() {
- NEARBY_LOG(INFO, "Bringing down endpoints");
- endpoints_.clear();
- latch.CountDown();
- });
- latch.Await();
-
- NEARBY_LOG(INFO, "Bringing down control thread");
- serial_executor_.Shutdown();
- NEARBY_LOG(INFO, "EndpointManager is down");
-}
-
-void EndpointManager::RegisterFrameProcessor(
- V1Frame::FrameType frame_type, EndpointManager::FrameProcessor* processor) {
- if (auto frame_processor = GetFrameProcessor(frame_type)) {
- NEARBY_LOGS(INFO) << "EndpointManager received request to update "
- "registration of frame processor "
- << processor << " for frame type "
- << V1Frame::FrameType_Name(frame_type) << ", self"
- << this;
- frame_processor.set(processor);
- } else {
- MutexLock lock(&frame_processors_lock_);
- NEARBY_LOGS(INFO) << "EndpointManager received request to add registration "
- "of frame processor "
- << processor << " for frame type "
- << V1Frame::FrameType_Name(frame_type)
- << ", self=" << this;
- frame_processors_.emplace(frame_type, processor);
- }
-}
-
-void EndpointManager::UnregisterFrameProcessor(
- V1Frame::FrameType frame_type,
- const EndpointManager::FrameProcessor* processor) {
- NEARBY_LOGS(INFO) << "UnregisterFrameProcessor [enter]: processor ="
- << processor;
- if (processor == nullptr) return;
- if (auto frame_processor = GetFrameProcessor(frame_type)) {
- if (frame_processor.get() == processor) {
- frame_processor.reset();
- NEARBY_LOGS(INFO) << "EndpointManager unregister frame processor "
- << processor << " for frame type "
- << V1Frame::FrameType_Name(frame_type)
- << ", self=" << this;
- } else {
- NEARBY_LOGS(INFO) << "EndpointManager cannot unregister frame processor "
- << processor
- << " because it is not registered for frame type "
- << V1Frame::FrameType_Name(frame_type)
- << ", expected=" << frame_processor.get();
- }
- } else {
- NEARBY_LOGS(INFO) << "UnregisterFrameProcessor [not found]: processor="
- << processor;
- }
-}
-
-EndpointManager::LockedFrameProcessor EndpointManager::GetFrameProcessor(
- V1Frame::FrameType frame_type) {
- MutexLock lock(&frame_processors_lock_);
- auto it = frame_processors_.find(frame_type);
- if (it != frame_processors_.end()) {
- return LockedFrameProcessor(&it->second);
- }
- return LockedFrameProcessor();
-}
-
-void EndpointManager::RemoveEndpointState(const std::string& endpoint_id) {
- NEARBY_LOGS(VERBOSE) << "EnsureWorkersTerminated for endpoint "
- << endpoint_id;
- auto item = endpoints_.find(endpoint_id);
- if (item != endpoints_.end()) {
- NEARBY_LOGS(INFO) << "EndpointState found for endpoint " << endpoint_id;
- // If another instance of data and keep-alive handlers is running, it will
- // terminate soon. Removing EndpointState waits for workers to complete.
- endpoints_.erase(item);
- NEARBY_LOGS(VERBOSE) << "Workers terminated for endpoint " << endpoint_id;
- } else {
- NEARBY_LOGS(INFO) << "EndpointState not found for endpoint " << endpoint_id;
- }
-}
-
-void EndpointManager::RegisterEndpoint(ClientProxy* client,
- const std::string& endpoint_id,
- const ConnectionResponseInfo& info,
- const ConnectionOptions& options,
- std::unique_ptr<EndpointChannel> channel,
- const ConnectionListener& listener,
- const std::string& connection_token) {
- CountDownLatch latch(1);
-
- // NOTE (unique_ptr<> capture):
- // std::unique_ptr<> is not copyable, so we can not pass it to
- // lambda capture, because lambda eventually is converted to std::function<>.
- // Instead, we release() a pointer, and pass a raw pointer, which is copyalbe.
- // We ignore the risk of job not scheduled (and an associated risk of memory
- // leak), because this may only happen during service shutdown.
- RunOnEndpointManagerThread("register-endpoint", [this, client,
- channel = channel.release(),
- &endpoint_id, &info,
- &options, &listener,
- &connection_token,
- &latch]() {
- if (endpoints_.contains(endpoint_id)) {
- NEARBY_LOGS(WARNING) << "Registering duplicate endpoint " << endpoint_id;
- // We must remove old endpoint state before registering a new one for the
- // same endpoint_id.
- RemoveEndpointState(endpoint_id);
- }
-
- absl::Duration keep_alive_interval =
- absl::Milliseconds(options.keep_alive_interval_millis);
- absl::Duration keep_alive_timeout =
- absl::Milliseconds(options.keep_alive_timeout_millis);
- NEARBY_LOGS(INFO) << "Registering endpoint " << endpoint_id
- << " for client " << client->GetClientId()
- << " with keep-alive frame as interval="
- << absl::FormatDuration(keep_alive_interval)
- << ", timeout="
- << absl::FormatDuration(keep_alive_timeout);
-
- // Pass ownership of channel to EndpointChannelManager
- NEARBY_LOGS(INFO) << "Registering endpoint with channel manager: endpoint "
- << endpoint_id;
- channel_manager_->RegisterChannelForEndpoint(
- client, endpoint_id, std::unique_ptr<EndpointChannel>(channel));
-
- EndpointState& endpoint_state =
- endpoints_
- .emplace(endpoint_id, EndpointState(endpoint_id, channel_manager_))
- .first->second;
-
- NEARBY_LOGS(INFO) << "Starting workers: endpoint " << endpoint_id;
- // For every endpoint, there's normally only one Read handler instance
- // running on a dedicated thread. This instance reads data from the
- // endpoint and delegates incoming frames to various FrameProcessors.
- // Once the frame has been properly handled, it starts reading again for
- // the next frame. If the handler fails its read and no other
- // EndpointChannels are available for this endpoint, a disconnection
- // will be initiated.
- endpoint_state.StartEndpointReader([this, client, endpoint_id]() {
- EndpointChannelLoopRunnable(
- "Read", client, endpoint_id,
- [this, client, endpoint_id](EndpointChannel* channel) {
- return HandleData(endpoint_id, client, channel);
- });
- });
-
- // For every endpoint, there's only one KeepAliveManager instance running on
- // a dedicated thread. This instance will periodically send out a ping* to
- // the endpoint while listening for an incoming pong**. If it fails to send
- // the ping, or if no pong is heard within keep_alive_timeout, it initiates
- // a disconnection.
- //
- // (*) Bluetooth requires a constant outgoing stream of messages. If
- // there's silence, Android will break the socket. This is why we ping.
- // (**) Wifi Hotspots can fail to notice a connection has been lost, and
- // they will happily keep writing to /dev/null. This is why we listen
- // for the pong.
- NEARBY_LOGS(VERBOSE) << "EndpointManager enabling KeepAlive for endpoint "
- << endpoint_id;
- endpoint_state.StartEndpointKeepAliveManager(
- [this, client, endpoint_id, keep_alive_interval, keep_alive_timeout](
- Mutex* keep_alive_waiter_mutex,
- ConditionVariable* keep_alive_waiter) {
- EndpointChannelLoopRunnable(
- "KeepAliveManager", client, endpoint_id,
- [this, keep_alive_interval, keep_alive_timeout,
- keep_alive_waiter_mutex,
- keep_alive_waiter](EndpointChannel* channel) {
- return HandleKeepAlive(
- channel, keep_alive_interval, keep_alive_timeout,
- keep_alive_waiter_mutex, keep_alive_waiter);
- });
- });
- NEARBY_LOGS(INFO) << "Registering endpoint " << endpoint_id
- << ", workers started and notifying client.";
-
- // It's now time to let the client know of this new connection so that
- // they can accept or reject it.
- client->OnConnectionInitiated(endpoint_id, info, options, listener,
- connection_token);
- latch.CountDown();
- });
- latch.Await();
-}
-
-void EndpointManager::UnregisterEndpoint(ClientProxy* client,
- const std::string& endpoint_id) {
- NEARBY_LOGS(INFO) << "UnregisterEndpoint for endpoint " << endpoint_id;
- CountDownLatch latch(1);
- RunOnEndpointManagerThread(
- "unregister-endpoint", [this, client, endpoint_id, &latch]() {
- RemoveEndpoint(client, endpoint_id,
- /*notify=*/client->IsConnectedToEndpoint(endpoint_id));
- latch.CountDown();
- });
- latch.Await();
-}
-
-int EndpointManager::GetMaxTransmitPacketSize(const std::string& endpoint_id) {
- std::shared_ptr<EndpointChannel> channel =
- channel_manager_->GetChannelForEndpoint(endpoint_id);
- if (channel == nullptr) {
- return 0;
- }
-
- return channel->GetMaxTransmitPacketSize();
-}
-
-std::vector<std::string> EndpointManager::SendPayloadChunk(
- const PayloadTransferFrame::PayloadHeader& payload_header,
- const PayloadTransferFrame::PayloadChunk& payload_chunk,
- const std::vector<std::string>& endpoint_ids) {
- ByteArray bytes =
- parser::ForDataPayloadTransfer(payload_header, payload_chunk);
-
- return SendTransferFrameBytes(
- endpoint_ids, bytes, payload_header.id(),
- /*offset=*/payload_chunk.offset(),
- /*packet_type=*/
- PayloadTransferFrame::PacketType_Name(PayloadTransferFrame::DATA));
-}
-
-// Designed to run asynchronously. It is called from IO thread pools, and
-// jobs in these pools may be waited for from the EndpointManager thread. If we
-// allow synchronous behavior here it will cause a live lock.
-void EndpointManager::DiscardEndpoint(ClientProxy* client,
- const std::string& endpoint_id) {
- NEARBY_LOGS(VERBOSE) << "DiscardEndpoint for endpoint " << endpoint_id;
- RunOnEndpointManagerThread("discard-endpoint", [this, client, endpoint_id]() {
- RemoveEndpoint(client, endpoint_id,
- /*notify=*/client->IsConnectedToEndpoint(endpoint_id));
- });
-}
-
-std::vector<std::string> EndpointManager::SendControlMessage(
- const PayloadTransferFrame::PayloadHeader& header,
- const PayloadTransferFrame::ControlMessage& control,
- const std::vector<std::string>& endpoint_ids) {
- ByteArray bytes = parser::ForControlPayloadTransfer(header, control);
-
- return SendTransferFrameBytes(
- endpoint_ids, bytes, header.id(),
- /*offset=*/control.offset(),
- /*packet_type=*/
- PayloadTransferFrame::PacketType_Name(PayloadTransferFrame::CONTROL));
-}
-
-// @EndpointManagerThread
-void EndpointManager::RemoveEndpoint(ClientProxy* client,
- const std::string& endpoint_id,
- bool notify) {
- NEARBY_LOGS(INFO) << "RemoveEndpoint for endpoint " << endpoint_id;
- // Unregistering from channel_manager_ will also serve to terminate
- // the dedicated handler and KeepAlive threads we started when we registered
- // this endpoint.
- if (channel_manager_->UnregisterChannelForEndpoint(endpoint_id)) {
- // Notify all frame processors of the disconnection immediately and wait
- // for them to clean up state. Only once all processors are done cleaning
- // up, we can remove the endpoint from ClientProxy after which there
- // should be no further interactions with the endpoint.
- // (See b/37352254 for history)
- WaitForEndpointDisconnectionProcessing(client, endpoint_id);
-
- client->OnDisconnected(endpoint_id, notify);
- NEARBY_LOGS(INFO) << "Removed endpoint for endpoint " << endpoint_id;
- }
- RemoveEndpointState(endpoint_id);
-}
-
-// @EndpointManagerThread
-void EndpointManager::WaitForEndpointDisconnectionProcessing(
- ClientProxy* client, const std::string& endpoint_id) {
- NEARBY_LOGS(INFO) << "Wait: client=" << client
- << "; endpoint_id=" << endpoint_id;
- CountDownLatch barrier =
- NotifyFrameProcessorsOnEndpointDisconnect(client, endpoint_id);
-
- NEARBY_LOGS(INFO)
- << "Waiting for frame processors to disconnect from endpoint "
- << endpoint_id;
- if (!barrier.Await(kProcessEndpointDisconnectionTimeout).result()) {
- NEARBY_LOGS(INFO) << "Failed to disconnect frame processors from endpoint "
- << endpoint_id;
- } else {
- NEARBY_LOGS(INFO)
- << "Finished waiting for frame processors to disconnect from endpoint "
- << endpoint_id;
- }
-}
-
-CountDownLatch EndpointManager::NotifyFrameProcessorsOnEndpointDisconnect(
- ClientProxy* client, const std::string& endpoint_id) {
- NEARBY_LOGS(INFO) << "NotifyFrameProcessorsOnEndpointDisconnect: client="
- << client << "; endpoint_id=" << endpoint_id;
- MutexLock lock(&frame_processors_lock_);
- auto total_size = frame_processors_.size();
- NEARBY_LOGS(INFO) << "Total frame processors: " << total_size;
- CountDownLatch barrier(total_size);
-
- int valid = 0;
- for (auto& item : frame_processors_) {
- LockedFrameProcessor processor(&item.second);
- NEARBY_LOGS(INFO) << "processor=" << processor.get()
- << "; frame type=" << V1Frame::FrameType_Name(item.first);
- if (processor) {
- valid++;
- processor->OnEndpointDisconnect(client, endpoint_id, barrier);
- } else {
- barrier.CountDown();
- }
- }
-
- if (!valid) {
- NEARBY_LOGS(INFO) << "No valid frame processors.";
- } else {
- NEARBY_LOGS(INFO) << "Valid frame processors: " << valid;
- }
- return barrier;
-}
-
-std::vector<std::string> EndpointManager::SendTransferFrameBytes(
- const std::vector<std::string>& endpoint_ids, const ByteArray& bytes,
- std::int64_t payload_id, std::int64_t offset,
- const std::string& packet_type) {
- std::vector<std::string> failed_endpoint_ids;
- for (const std::string& endpoint_id : endpoint_ids) {
- std::shared_ptr<EndpointChannel> channel =
- channel_manager_->GetChannelForEndpoint(endpoint_id);
-
- if (channel == nullptr) {
- // We no longer know about this endpoint (it was either explicitly
- // unregistered, or a read/write error made us unregister it internally).
- NEARBY_LOGS(ERROR) << "EndpointManager failed to find EndpointChannel "
- "over which to write "
- << packet_type << " at offset " << offset
- << " of Payload " << payload_id << " to endpoint "
- << endpoint_id;
-
- failed_endpoint_ids.push_back(endpoint_id);
- continue;
- }
-
- Exception write_exception = channel->Write(bytes);
- if (!write_exception.Ok()) {
- failed_endpoint_ids.push_back(endpoint_id);
- NEARBY_LOGS(INFO) << "Failed to send packet; endpoint_id=" << endpoint_id;
- continue;
- }
- }
-
- return failed_endpoint_ids;
-}
-
-EndpointManager::EndpointState::~EndpointState() {
- // We must unregister the endpoint first to signal the runnables that they
- // should exit their loops. SingleThreadExecutor destructors will wait for the
- // workers to finish. |channel_manager_| is null after moved from this object
- // (in move constructor) which prevents unregistering the channel prematurely.
- if (channel_manager_) {
- NEARBY_LOG(VERBOSE, "EndpointState destructor %s", endpoint_id_.c_str());
- channel_manager_->UnregisterChannelForEndpoint(endpoint_id_);
- }
-
- // Make sure the KeepAlive thread isn't blocking shutdown.
- if (keep_alive_waiter_mutex_ && keep_alive_waiter_) {
- MutexLock lock(keep_alive_waiter_mutex_.get());
- keep_alive_waiter_->Notify();
- }
-}
-
-void EndpointManager::EndpointState::StartEndpointReader(Runnable&& runnable) {
- reader_thread_.Execute("reader", std::move(runnable));
-}
-
-void EndpointManager::EndpointState::StartEndpointKeepAliveManager(
- std::function<void(Mutex*, ConditionVariable*)> runnable) {
- keep_alive_thread_.Execute(
- "keep-alive",
- [runnable, keep_alive_waiter_mutex = keep_alive_waiter_mutex_.get(),
- keep_alive_waiter = keep_alive_waiter_.get()]() {
- runnable(keep_alive_waiter_mutex, keep_alive_waiter);
- });
-}
-
-void EndpointManager::RunOnEndpointManagerThread(const std::string& name,
- Runnable runnable) {
- serial_executor_.Execute(name, std::move(runnable));
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/endpoint_manager.h b/chromium/third_party/nearby/src/cpp/core/internal/endpoint_manager.h
deleted file mode 100644
index ec1a16197f5..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/endpoint_manager.h
+++ /dev/null
@@ -1,284 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_ENDPOINT_MANAGER_H_
-#define CORE_INTERNAL_ENDPOINT_MANAGER_H_
-
-#include <cstdint>
-#include <memory>
-
-#include "absl/base/thread_annotations.h"
-#include "absl/container/flat_hash_map.h"
-#include "absl/container/flat_hash_set.h"
-#include "absl/time/time.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/endpoint_channel.h"
-#include "core/internal/endpoint_channel_manager.h"
-#include "core/listeners.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/runnable.h"
-#include "platform/public/condition_variable.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/multi_thread_executor.h"
-#include "platform/public/single_thread_executor.h"
-#include "platform/public/system_clock.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Manages all operations related to the remote endpoints with which we are
-// interacting.
-//
-// All processing of incoming and outgoing payloads is spread across this and
-// the PayloadManager as described below.
-//
-// The sending of outgoing payloads originates in
-// PayloadManager::SendPayload() before control is transferred over to
-// EndpointManager::SendPayloadChunk(). This work happens on one of three
-// dedicated writer threads belonging to the PayloadManager. The writer thread
-// that is used depends on the Payload::Type.
-//
-// The EndpointManager has one dedicated reader thread for each registered
-// endpoint, and the receiving of every incoming payload (and its subsequent
-// chunks) originates on one of those threads before control is transferred over
-// to PayloadManager::ProcessFrame() (still running on that
-// same dedicated reader thread).
-
-class EndpointManager {
- public:
- class FrameProcessor {
- public:
- virtual ~FrameProcessor() = default;
-
- // @EndpointManagerReaderThread
- // Called for every incoming frame of registered type.
- // NOTE(OfflineFrame& frame):
- // For large payload in data phase, resources may be saved if data is moved,
- // rather than copied (if passing data by reference is not an option).
- // To achieve that, OfflineFrame needs to be either mutabe lvalue reference,
- // or rvalue reference. Rvalue references are discouraged by go/cstyle,
- // and that leaves us with mutable lvalue reference.
- virtual void OnIncomingFrame(OfflineFrame& offline_frame,
- const std::string& from_endpoint_id,
- ClientProxy* to_client,
- proto::connections::Medium current_medium) = 0;
-
- // Implementations must call barrier.CountDown() once
- // they're done. This parallelizes the disconnection event across all frame
- // processors.
- //
- // @EndpointManagerThread
- virtual void OnEndpointDisconnect(ClientProxy* client,
- const std::string& endpoint_id,
- CountDownLatch barrier) = 0;
- };
-
- explicit EndpointManager(EndpointChannelManager* manager);
- ~EndpointManager();
-
- // Invoked from the constructors of the various *Manager components that make
- // up the OfflineServiceController implementation.
- // FrameProcessor* instances are of dynamic duration and survive all sessions.
- // Blocks until registration is complete.
- void RegisterFrameProcessor(V1Frame::FrameType frame_type,
- FrameProcessor* processor);
- void UnregisterFrameProcessor(V1Frame::FrameType frame_type,
- const FrameProcessor* processor);
-
- // Invoked from the different PcpHandler implementations (of which there can
- // be only one at a time).
- // Blocks until registration is complete.
- void RegisterEndpoint(ClientProxy* client, const std::string& endpoint_id,
- const ConnectionResponseInfo& info,
- const ConnectionOptions& options,
- std::unique_ptr<EndpointChannel> channel,
- const ConnectionListener& listener,
- const std::string& connection_token);
- // Called when a client explicitly asks to disconnect from this endpoint. In
- // this case, we do not notify the client of onDisconnected().
- void UnregisterEndpoint(ClientProxy* client, const std::string& endpoint_id);
-
- // Returns the maximum supported transmit packet size(MTU) for the underlying
- // transport.
- int GetMaxTransmitPacketSize(const std::string& endpoint_id);
-
- // Returns the list of endpoints to which sending this chunk failed.
- //
- // Invoked from the PayloadManager's sendPayload() method.
- std::vector<std::string> SendPayloadChunk(
- const PayloadTransferFrame::PayloadHeader& payload_header,
- const PayloadTransferFrame::PayloadChunk& payload_chunk,
- const std::vector<std::string>& endpoint_ids);
- std::vector<std::string> SendControlMessage(
- const PayloadTransferFrame::PayloadHeader& payload_header,
- const PayloadTransferFrame::ControlMessage& control_message,
- const std::vector<std::string>& endpoint_ids);
-
- // Called when we internally want to get rid of the endpoint, without the
- // client directly telling us to. For example...
- // a) We failed to read from the endpoint in its dedicated reader thread.
- // b) We failed to write to the endpoint in PayloadManager.
- // c) The connection was rejected in PCPHandler.
- // d) The dedicated KeepAlive thread exceeded its period of inactivity.
- // Or in the numerous other cases where a failure occurred and we no longer
- // believe the endpoint is in a healthy state.
- //
- // Note: This must not block. Otherwise we can get into a deadlock where we
- // ask everyone who's registered an FrameProcessor to
- // processEndpointDisconnection() while the caller of DiscardEndpoint() is
- // blocked here.
- void DiscardEndpoint(ClientProxy* client, const std::string& endpoint_id);
-
- private:
- class EndpointState {
- public:
- EndpointState(const std::string& endpoint_id,
- EndpointChannelManager* channel_manager)
- : endpoint_id_{endpoint_id},
- channel_manager_{channel_manager},
- keep_alive_waiter_mutex_{std::make_unique<Mutex>()},
- keep_alive_waiter_{std::make_unique<ConditionVariable>(
- keep_alive_waiter_mutex_.get())} {}
-
- EndpointState(const EndpointState&) = delete;
- // The default move constructor would not reset |channel_manager_|, for
- // example. This needs to be nullified so the destructor shutdown logic is
- // bypassed when objects are moved.
- EndpointState(EndpointState&& other)
- : endpoint_id_{std::move(other.endpoint_id_)},
- channel_manager_{std::exchange(other.channel_manager_, nullptr)},
- reader_thread_{std::move(other.reader_thread_)},
- keep_alive_waiter_mutex_{
- std::exchange(other.keep_alive_waiter_mutex_, nullptr)},
- keep_alive_waiter_{std::exchange(other.keep_alive_waiter_, nullptr)},
- keep_alive_thread_{std::move(other.keep_alive_thread_)} {}
- EndpointState& operator=(const EndpointState&) = delete;
- EndpointState&& operator=(EndpointState&&) = delete;
- ~EndpointState();
-
- void StartEndpointReader(Runnable&& runnable);
- void StartEndpointKeepAliveManager(
- std::function<void(Mutex*, ConditionVariable*)> runnable);
-
- private:
- const std::string endpoint_id_;
- EndpointChannelManager* channel_manager_;
- SingleThreadExecutor reader_thread_;
-
- // Use a condition variable so we can wait on the thread but still be able
- // to wake it up before shutting down. We don't want to just sleep and risk
- // blocking shutdown. Note: Create the mutex/condition variable on the heap
- // so raw pointers sent to HandleKeepAlive() aren't invalidated during
- // std::move operations.
- mutable std::unique_ptr<Mutex> keep_alive_waiter_mutex_;
- std::unique_ptr<ConditionVariable> keep_alive_waiter_;
- SingleThreadExecutor keep_alive_thread_;
- };
-
- // RAII accessor for FrameProcessor
- class LockedFrameProcessor;
-
- // Provides a mutex per FrameProcessor to prevent unregistering (and
- // destroying) a FrameProcessor when it's in use.
- class FrameProcessorWithMutex {
- public:
- explicit FrameProcessorWithMutex(FrameProcessor* frame_processor = nullptr)
- : frame_processor_{frame_processor} {}
-
- private:
- FrameProcessor* frame_processor_;
- Mutex mutex_;
- friend class LockedFrameProcessor;
- };
-
- LockedFrameProcessor GetFrameProcessor(V1Frame::FrameType frame_type);
-
- ExceptionOr<bool> HandleData(const std::string& endpoint_id,
- ClientProxy* client_proxy,
- EndpointChannel* endpoint_channel);
-
- ExceptionOr<bool> HandleKeepAlive(EndpointChannel* endpoint_channel,
- absl::Duration keep_alive_interval,
- absl::Duration keep_alive_timeout,
- Mutex* keep_alive_waiter_mutex,
- ConditionVariable* keep_alive_waiter);
-
- // Waits for a given endpoint EndpointChannelLoopRunnable() workers to
- // terminate.
- // Is called from RegisterEndpoint to avoid races; also called from
- // RemoveEndpoint as part of proper endpoint shutdown sequence.
- // @EndpointManagerThread
- void RemoveEndpointState(const std::string& endpoint_id);
-
- void EndpointChannelLoopRunnable(
- const std::string& runnable_name, ClientProxy* client_proxy,
- const std::string& endpoint_id,
- std::function<ExceptionOr<bool>(EndpointChannel*)> handler);
-
- static void WaitForLatch(const std::string& method_name,
- CountDownLatch* latch);
- static void WaitForLatch(const std::string& method_name,
- CountDownLatch* latch, std::int32_t timeout_millis);
-
- static constexpr absl::Duration kProcessEndpointDisconnectionTimeout =
- absl::Milliseconds(2000);
- static constexpr absl::Time kInvalidTimestamp = absl::InfinitePast();
-
- // It should be noted that this method may be called multiple times (because
- // invoking this method closes the endpoint channel, which causes the
- // dedicated reader and KeepAlive threads to terminate, which in turn leads to
- // this method being called), but that's alright because the implementation of
- // this method is idempotent.
- // @EndpointManagerThread
- void RemoveEndpoint(ClientProxy* client, const std::string& endpoint_id,
- bool notify);
-
- void WaitForEndpointDisconnectionProcessing(ClientProxy* client,
- const std::string& endpoint_id);
-
- CountDownLatch NotifyFrameProcessorsOnEndpointDisconnect(
- ClientProxy* client, const std::string& endpoint_id);
-
- std::vector<std::string> SendTransferFrameBytes(
- const std::vector<std::string>& endpoint_ids,
- const ByteArray& payload_transfer_frame_bytes, std::int64_t payload_id,
- std::int64_t offset, const std::string& packet_type);
-
- // Executes all jobs sequentially, on a serial_executor_.
- void RunOnEndpointManagerThread(const std::string& name, Runnable runnable);
-
- EndpointChannelManager* channel_manager_;
-
- RecursiveMutex frame_processors_lock_;
- absl::flat_hash_map<V1Frame::FrameType, FrameProcessorWithMutex>
- frame_processors_ ABSL_GUARDED_BY(frame_processors_lock_);
-
- // We keep track of all registered channel endpoints here.
- absl::flat_hash_map<std::string, EndpointState> endpoints_;
-
- SingleThreadExecutor serial_executor_;
-};
-
-// Operator overloads when comparing FrameProcessor*.
-bool operator==(const EndpointManager::FrameProcessor& lhs,
- const EndpointManager::FrameProcessor& rhs);
-bool operator<(const EndpointManager::FrameProcessor& lhs,
- const EndpointManager::FrameProcessor& rhs);
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_ENDPOINT_MANAGER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/endpoint_manager_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/endpoint_manager_test.cc
deleted file mode 100644
index dae1057b411..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/endpoint_manager_test.cc
+++ /dev/null
@@ -1,282 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/endpoint_manager.h"
-
-#include <atomic>
-#include <memory>
-#include <string>
-#include <utility>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/synchronization/mutex.h"
-#include "absl/time/clock.h"
-#include "absl/time/time.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/endpoint_channel_manager.h"
-#include "core/internal/offline_frames.h"
-#include "core/options.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/exception.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/logging.h"
-#include "platform/public/pipe.h"
-#include "proto/connections_enums.pb.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-
-using ::location::nearby::proto::connections::DisconnectionReason;
-using ::location::nearby::proto::connections::Medium;
-using ::testing::_;
-using ::testing::MockFunction;
-using ::testing::Return;
-using ::testing::StrictMock;
-
-class MockEndpointChannel : public EndpointChannel {
- public:
- MOCK_METHOD(ExceptionOr<ByteArray>, Read, (), (override));
- MOCK_METHOD(Exception, Write, (const ByteArray& data), (override));
- MOCK_METHOD(void, Close, (), (override));
- MOCK_METHOD(void, Close, (DisconnectionReason reason), (override));
- MOCK_METHOD(std::string, GetType, (), (const override));
- MOCK_METHOD(std::string, GetName, (), (const override));
- MOCK_METHOD(Medium, GetMedium, (), (const override));
- MOCK_METHOD(int, GetMaxTransmitPacketSize, (), (const override));
- MOCK_METHOD(void, EnableEncryption,
- (std::shared_ptr<EncryptionContext> context), (override));
- MOCK_METHOD(void, DisableEncryption, (), (override));
- MOCK_METHOD(bool, IsPaused, (), (const override));
- MOCK_METHOD(void, Pause, (), (override));
- MOCK_METHOD(void, Resume, (), (override));
- MOCK_METHOD(absl::Time, GetLastReadTimestamp, (), (const override));
- MOCK_METHOD(absl::Time, GetLastWriteTimestamp, (), (const override));
- MOCK_METHOD(void, SetAnalyticsRecorder,
- (analytics::AnalyticsRecorder*, const std::string&), (override));
-
- bool IsClosed() const {
- absl::MutexLock lock(&mutex_);
- return closed_;
- }
- void DoClose() {
- absl::MutexLock lock(&mutex_);
- closed_ = true;
- }
-
- private:
- mutable absl::Mutex mutex_;
- bool closed_ = false;
-};
-
-class MockFrameProcessor : public EndpointManager::FrameProcessor {
- public:
- MOCK_METHOD(void, OnIncomingFrame,
- (OfflineFrame & offline_frame,
- const std::string& from_endpoint_id, ClientProxy* to_client,
- Medium current_medium),
- (override));
-
- MOCK_METHOD(void, OnEndpointDisconnect,
- (ClientProxy * client, const std::string& endpoint_id,
- CountDownLatch barrier),
- (override));
-};
-
-class EndpointManagerTest : public ::testing::Test {
- protected:
- void RegisterEndpoint(std::unique_ptr<MockEndpointChannel> channel,
- bool should_close = true) {
- CountDownLatch done(1);
- if (should_close) {
- ON_CALL(*channel, Close(_))
- .WillByDefault(
- [&done](DisconnectionReason reason) { done.CountDown(); });
- }
- EXPECT_CALL(*channel, GetMedium()).WillRepeatedly(Return(Medium::BLE));
- EXPECT_CALL(*channel, GetLastReadTimestamp())
- .WillRepeatedly(Return(start_time_));
- EXPECT_CALL(*channel, GetLastWriteTimestamp())
- .WillRepeatedly(Return(start_time_));
- EXPECT_CALL(mock_listener_.initiated_cb, Call).Times(1);
- em_.RegisterEndpoint(&client_, endpoint_id_, info_, options_,
- std::move(channel), listener_, connection_token);
- if (should_close) {
- EXPECT_TRUE(done.Await(absl::Milliseconds(1000)).result());
- }
- }
-
- ClientProxy client_;
- ConnectionOptions options_{
- .keep_alive_interval_millis = 5000,
- .keep_alive_timeout_millis = 30000,
- };
- std::vector<std::unique_ptr<EndpointManager::FrameProcessor>> processors_;
- EndpointChannelManager ecm_;
- EndpointManager em_{&ecm_};
- std::string endpoint_id_ = "endpoint_id";
- ConnectionResponseInfo info_ = {
- .remote_endpoint_info = ByteArray{"info"},
- .authentication_token = "auth_token",
- .raw_authentication_token = ByteArray{"auth_token"},
- .is_incoming_connection = true,
- };
- struct MockConnectionListener {
- StrictMock<MockFunction<void(const std::string& endpoint_id,
- const ConnectionResponseInfo& info)>>
- initiated_cb;
- StrictMock<MockFunction<void(const std::string& endpoint_id)>> accepted_cb;
- StrictMock<MockFunction<void(const std::string& endpoint_id,
- const Status& status)>>
- rejected_cb;
- StrictMock<MockFunction<void(const std::string& endpoint_id)>>
- disconnected_cb;
- StrictMock<MockFunction<void(const std::string& endpoint_id,
- std::int32_t quality)>>
- bandwidth_changed_cb;
- } mock_listener_;
- ConnectionListener listener_{
- .initiated_cb = mock_listener_.initiated_cb.AsStdFunction(),
- .accepted_cb = mock_listener_.accepted_cb.AsStdFunction(),
- .rejected_cb = mock_listener_.rejected_cb.AsStdFunction(),
- .disconnected_cb = mock_listener_.disconnected_cb.AsStdFunction(),
- .bandwidth_changed_cb =
- mock_listener_.bandwidth_changed_cb.AsStdFunction(),
- };
- std::string connection_token = "conntokn";
- absl::Time start_time_{absl::Now()};
-};
-
-TEST_F(EndpointManagerTest, ConstructorDestructorWorks) { SUCCEED(); }
-
-TEST_F(EndpointManagerTest, RegisterEndpointCallsOnConnectionInitiated) {
- auto endpoint_channel = std::make_unique<MockEndpointChannel>();
- EXPECT_CALL(*endpoint_channel, Read())
- .WillRepeatedly(Return(ExceptionOr<ByteArray>(Exception::kIo)));
- EXPECT_CALL(*endpoint_channel, Close(_)).Times(1);
- RegisterEndpoint(std::move(endpoint_channel));
-}
-
-TEST_F(EndpointManagerTest, UnregisterEndpointCallsOnDisconnected) {
- auto endpoint_channel = std::make_unique<MockEndpointChannel>();
- EXPECT_CALL(*endpoint_channel, Read())
- .WillRepeatedly(Return(ExceptionOr<ByteArray>(Exception::kIo)));
- RegisterEndpoint(std::make_unique<MockEndpointChannel>());
- // NOTE: disconnect_cb is not called, because we did not reach fully connected
- // state. On top of that, UnregisterEndpoint is suppressing this notification.
- // (IMO, it should be called as long as any connection callback was called
- // before. (in this case initiated_cb is called)).
- // Test captures current protocol behavior.
- em_.UnregisterEndpoint(&client_, endpoint_id_);
-}
-
-TEST_F(EndpointManagerTest, RegisterFrameProcessorWorks) {
- auto endpoint_channel = std::make_unique<MockEndpointChannel>();
- auto connect_request = std::make_unique<MockFrameProcessor>();
- ByteArray endpoint_info{"endpoint_name"};
- auto read_data =
- parser::ForConnectionRequest("endpoint_id", endpoint_info, 1234, false,
- "", std::vector{Medium::BLE}, 0, 0);
- EXPECT_CALL(*connect_request, OnIncomingFrame);
- EXPECT_CALL(*connect_request, OnEndpointDisconnect);
- EXPECT_CALL(*endpoint_channel, Read())
- .WillOnce(Return(ExceptionOr<ByteArray>(read_data)))
- .WillRepeatedly(Return(ExceptionOr<ByteArray>(Exception::kIo)));
- EXPECT_CALL(*endpoint_channel, Write(_))
- .WillRepeatedly(Return(Exception{Exception::kSuccess}));
- // Register frame processor, then register endpoint.
- // Endpoint will read one frame, then fail to read more and terminate.
- // On disconnection, it will notify frame processor and we verify that.
- em_.RegisterFrameProcessor(V1Frame::CONNECTION_REQUEST,
- connect_request.get());
- processors_.emplace_back(std::move(connect_request));
- RegisterEndpoint(std::move(endpoint_channel));
-}
-
-TEST_F(EndpointManagerTest, UnregisterFrameProcessorWorks) {
- auto endpoint_channel = std::make_unique<MockEndpointChannel>();
- EXPECT_CALL(*endpoint_channel, Read())
- .WillRepeatedly(Return(ExceptionOr<ByteArray>(Exception::kIo)));
- EXPECT_CALL(*endpoint_channel, Write(_))
- .WillRepeatedly(Return(Exception{Exception::kSuccess}));
-
- // We should not receive any notifications to frame processor.
- auto connect_request = std::make_unique<StrictMock<MockFrameProcessor>>();
-
- // Register frame processor and immediately unregister it.
- em_.RegisterFrameProcessor(V1Frame::CONNECTION_REQUEST,
- connect_request.get());
- em_.UnregisterFrameProcessor(V1Frame::CONNECTION_REQUEST,
- connect_request.get());
-
- processors_.emplace_back(std::move(connect_request));
- // Endpoint will not send OnDisconnect notification to frame processor.
- RegisterEndpoint(std::move(endpoint_channel), false);
- em_.UnregisterEndpoint(&client_, endpoint_id_);
-}
-
-TEST_F(EndpointManagerTest, SendControlMessageWorks) {
- auto endpoint_channel = std::make_unique<MockEndpointChannel>();
- PayloadTransferFrame::PayloadHeader header;
- PayloadTransferFrame::ControlMessage control;
- header.set_id(12345);
- header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
- header.set_total_size(1024);
- control.set_offset(150);
- control.set_event(PayloadTransferFrame::ControlMessage::PAYLOAD_CANCELED);
-
- ON_CALL(*endpoint_channel, Read())
- .WillByDefault([channel = endpoint_channel.get()]() {
- if (channel->IsClosed()) return ExceptionOr<ByteArray>(Exception::kIo);
- NEARBY_LOG(INFO, "Simulate read delay: wait");
- absl::SleepFor(absl::Milliseconds(100));
- NEARBY_LOG(INFO, "Simulate read delay: done");
- if (channel->IsClosed()) return ExceptionOr<ByteArray>(Exception::kIo);
- return ExceptionOr<ByteArray>(ByteArray{});
- });
- ON_CALL(*endpoint_channel, Close(_))
- .WillByDefault(
- [channel = endpoint_channel.get()](DisconnectionReason reason) {
- channel->DoClose();
- NEARBY_LOG(INFO, "Channel closed");
- });
- EXPECT_CALL(*endpoint_channel, Write(_))
- .WillRepeatedly(Return(Exception{Exception::kSuccess}));
-
- RegisterEndpoint(std::move(endpoint_channel), false);
- auto failed_ids =
- em_.SendControlMessage(header, control, std::vector{endpoint_id_});
- EXPECT_EQ(failed_ids, std::vector<std::string>{});
- NEARBY_LOG(INFO, "Will unregister endpoint now");
- em_.UnregisterEndpoint(&client_, endpoint_id_);
- NEARBY_LOG(INFO, "Will call destructors now");
-}
-
-TEST_F(EndpointManagerTest, SingleReadOnInvalidPayload) {
- auto endpoint_channel = std::make_unique<MockEndpointChannel>();
- EXPECT_CALL(*endpoint_channel, Read())
- .WillOnce(
- Return(ExceptionOr<ByteArray>(Exception::kInvalidProtocolBuffer)));
- EXPECT_CALL(*endpoint_channel, Write(_))
- .WillRepeatedly(Return(Exception{Exception::kSuccess}));
- EXPECT_CALL(*endpoint_channel, Close(_)).Times(1);
- RegisterEndpoint(std::move(endpoint_channel));
-}
-
-} // namespace
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/injected_bluetooth_device_store.cc b/chromium/third_party/nearby/src/cpp/core/internal/injected_bluetooth_device_store.cc
deleted file mode 100644
index 1ba0a4229e5..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/injected_bluetooth_device_store.cc
+++ /dev/null
@@ -1,90 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/injected_bluetooth_device_store.h"
-
-#include <string>
-
-#include "core/internal/bluetooth_device_name.h"
-#include "platform/api/bluetooth_classic.h"
-#include "platform/base/bluetooth_utils.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-
-// api::BluetoothDevice implementation which stores a name and address passed to
-// its constructor and trivially returns them to implement virtual functions.
-class InjectedBluetoothDevice : public api::BluetoothDevice {
- public:
- InjectedBluetoothDevice(const std::string& name,
- const std::string& mac_address)
- : name_(name), mac_address_(mac_address) {}
-
- ~InjectedBluetoothDevice() override = default;
-
- // api::BluetoothDevice:
- std::string GetName() const override { return name_; }
-
- std::string GetMacAddress() const override { return mac_address_; }
-
- private:
- const std::string name_;
- const std::string mac_address_;
-};
-
-} // namespace
-
-InjectedBluetoothDeviceStore::InjectedBluetoothDeviceStore() = default;
-
-InjectedBluetoothDeviceStore::~InjectedBluetoothDeviceStore() = default;
-
-BluetoothDevice InjectedBluetoothDeviceStore::CreateInjectedBluetoothDevice(
- const ByteArray& remote_bluetooth_mac_address,
- const std::string& endpoint_id, const ByteArray& endpoint_info,
- const ByteArray& service_id_hash, Pcp pcp) {
- std::string remote_bluetooth_mac_address_str =
- BluetoothUtils::ToString(remote_bluetooth_mac_address);
-
- // Valid MAC address is required.
- if (remote_bluetooth_mac_address_str.empty())
- return BluetoothDevice(/*device=*/nullptr);
-
- // Non-empty endpoint info is required.
- if (endpoint_info.Empty()) return BluetoothDevice(/*device=*/nullptr);
-
- BluetoothDeviceName name(BluetoothDeviceName::Version::kV1, pcp, endpoint_id,
- service_id_hash, endpoint_info,
- /*uwb_address=*/ByteArray(),
- WebRtcState::kConnectable);
-
- // Note: BluetoothDeviceName internally verifies that |endpoint_id| and
- // |service_id_hash| are valid; the check below will fail if they are
- // malformed.
- if (!name.IsValid()) return BluetoothDevice(/*device=*/nullptr);
-
- auto injected_device = std::make_unique<InjectedBluetoothDevice>(
- static_cast<std::string>(name), remote_bluetooth_mac_address_str);
- BluetoothDevice device_to_return(injected_device.get());
-
- // Store underlying device to ensure that it is kept alive for future use.
- devices_.emplace_back(std::move(injected_device));
-
- return device_to_return;
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/injected_bluetooth_device_store.h b/chromium/third_party/nearby/src/cpp/core/internal/injected_bluetooth_device_store.h
deleted file mode 100644
index cc61c2fef33..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/injected_bluetooth_device_store.h
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_INJECTED_BLUETOOTH_DEVICE_STORE_H_
-#define CORE_INTERNAL_INJECTED_BLUETOOTH_DEVICE_STORE_H_
-
-#include <memory>
-#include <vector>
-
-#include "core/internal/pcp.h"
-#include "platform/base/byte_array.h"
-#include "platform/public/bluetooth_adapter.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Creates and stores BluetoothDevice objects which have been "injected" (i.e.,
-// passed to Nearby Connections manually by the client instead of through the
-// normal discovery flow).
-class InjectedBluetoothDeviceStore {
- public:
- InjectedBluetoothDeviceStore();
- ~InjectedBluetoothDeviceStore();
-
- // Creates an injected BluetoothDevice given the provided parameters:
- // |remote_bluetooth_mac_address|: A 6-byte MAC address.
- // |endpoint_id|: A string of length 4.
- // |endpoint_info|: A non-empty ByteArray whose length is <=131 bytes.
- // |service_id_hash|: A ByteArray whose length is 3.
- // |pcp|: PCP value to be used for the connection to this device.
- //
- // If the provided parameters are malformed or of incorrect length, this
- // function returns an invalid BluetoothDevice. Clients should use
- // BluetoothDevice::IsValid() with the returned device to verify that the
- // parameters were successfully processed.
- //
- // Note that successfully-injected devices stay valid for the lifetime of the
- // InjectedBluetoothDeviceStore and are not cleared until this object is
- // deleted.
- BluetoothDevice CreateInjectedBluetoothDevice(
- const ByteArray& remote_bluetooth_mac_address,
- const std::string& endpoint_id, const ByteArray& endpoint_info,
- const ByteArray& service_id_hash, Pcp pcp);
-
- private:
- // Devices created by this class. BluetoothDevice objects returned by
- // CreateInjectedBluetoothDevice() store pointers to underlying
- // api::BluetoothDevice objects, so this maintains these underlying devices
- // to ensure that they are not deleted before they are referenced.
- std::vector<std::unique_ptr<api::BluetoothDevice>> devices_;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_INJECTED_BLUETOOTH_DEVICE_STORE_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/injected_bluetooth_device_store_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/injected_bluetooth_device_store_test.cc
deleted file mode 100644
index a5e45f47884..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/injected_bluetooth_device_store_test.cc
+++ /dev/null
@@ -1,123 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/injected_bluetooth_device_store.h"
-
-#include <array>
-
-#include "gtest/gtest.h"
-#include "core/internal/bluetooth_device_name.h"
-#include "platform/base/bluetooth_utils.h"
-#include "platform/base/byte_array.h"
-#include "platform/public/bluetooth_adapter.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-
-// Need to wrap with static_cast<char> to silence -Wc++11-narrowing issue.
-constexpr std::array<char, 6> kTestRemoteBluetoothMacAddress{
- 0x01, 0x23, 0x45, 0x67, static_cast<char>(0x89), static_cast<char>(0xab)};
-constexpr std::array<char, 2> kTestEndpointInfo{static_cast<char>(0xcd),
- static_cast<char>(0xef)};
-constexpr std::array<char, 3> kTestServiceIdHash{0x01, 0x23, 0x45};
-
-const char kTestEndpointId[] = "abcd";
-
-class InjectedBluetoothDeviceStoreTest : public testing::Test {
- protected:
- InjectedBluetoothDeviceStore store_;
-};
-
-TEST_F(InjectedBluetoothDeviceStoreTest, Success) {
- ByteArray remote_bluetooth_mac_address(kTestRemoteBluetoothMacAddress);
- ByteArray endpoint_info(kTestEndpointInfo);
- ByteArray service_id_hash(kTestServiceIdHash);
-
- BluetoothDevice device = store_.CreateInjectedBluetoothDevice(
- remote_bluetooth_mac_address, kTestEndpointId, endpoint_info,
- service_id_hash, Pcp::kP2pPointToPoint);
- EXPECT_TRUE(device.IsValid());
-
- EXPECT_EQ(BluetoothUtils::ToString(remote_bluetooth_mac_address),
- device.GetMacAddress());
-
- BluetoothDeviceName name(device.GetName());
- EXPECT_TRUE(name.IsValid());
- EXPECT_EQ(kTestEndpointId, name.GetEndpointId());
- EXPECT_EQ(endpoint_info, name.GetEndpointInfo());
- EXPECT_EQ(service_id_hash, name.GetServiceIdHash());
- EXPECT_EQ(Pcp::kP2pPointToPoint, name.GetPcp());
-}
-
-TEST_F(InjectedBluetoothDeviceStoreTest, Fail_InvalidBluetoothMac) {
- // Use address with only 1 byte.
- ByteArray remote_bluetooth_mac_address(std::array<char, 1>{0x00});
- ByteArray endpoint_info(kTestEndpointInfo);
- ByteArray service_id_hash(kTestServiceIdHash);
-
- BluetoothDevice device = store_.CreateInjectedBluetoothDevice(
- remote_bluetooth_mac_address, kTestEndpointId, endpoint_info,
- service_id_hash, Pcp::kP2pPointToPoint);
- EXPECT_FALSE(device.IsValid());
-}
-
-TEST_F(InjectedBluetoothDeviceStoreTest, Fail_InvalidEndpointId) {
- ByteArray remote_bluetooth_mac_address(kTestRemoteBluetoothMacAddress);
- ByteArray endpoint_info(kTestEndpointInfo);
- ByteArray service_id_hash(kTestServiceIdHash);
-
- // Use empty endpoint ID.
- BluetoothDevice device1 = store_.CreateInjectedBluetoothDevice(
- remote_bluetooth_mac_address, /*endpoint_id=*/std::string(),
- endpoint_info, service_id_hash, Pcp::kP2pPointToPoint);
- EXPECT_FALSE(device1.IsValid());
-
- // Use endpoint ID of wrong length.
- const std::string too_long_endpoint_id = "abcde";
- BluetoothDevice device2 = store_.CreateInjectedBluetoothDevice(
- remote_bluetooth_mac_address, too_long_endpoint_id, endpoint_info,
- service_id_hash, Pcp::kP2pPointToPoint);
- EXPECT_FALSE(device2.IsValid());
-}
-
-TEST_F(InjectedBluetoothDeviceStoreTest, Fail_EmptyEndpointInfo) {
- ByteArray remote_bluetooth_mac_address(kTestRemoteBluetoothMacAddress);
- // Use empty endpoint info.
- ByteArray endpoint_info;
- ByteArray service_id_hash(kTestServiceIdHash);
-
- BluetoothDevice device = store_.CreateInjectedBluetoothDevice(
- remote_bluetooth_mac_address, kTestEndpointId, endpoint_info,
- service_id_hash, Pcp::kP2pPointToPoint);
- EXPECT_FALSE(device.IsValid());
-}
-
-TEST_F(InjectedBluetoothDeviceStoreTest, Fail_InvalidServiceIdHash) {
- ByteArray remote_bluetooth_mac_address(kTestRemoteBluetoothMacAddress);
- ByteArray endpoint_info(kTestEndpointInfo);
- // Use address with only 1 byte.
- ByteArray service_id_hash(std::array<char, 1>{0x00});
-
- BluetoothDevice device = store_.CreateInjectedBluetoothDevice(
- remote_bluetooth_mac_address, kTestEndpointId, endpoint_info,
- service_id_hash, Pcp::kP2pPointToPoint);
- EXPECT_FALSE(device.IsValid());
-}
-
-} // namespace
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/internal_payload.cc b/chromium/third_party/nearby/src/cpp/core/internal/internal_payload.cc
deleted file mode 100644
index fcb700256c4..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/internal_payload.cc
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/internal_payload.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// The definition is necessary before C++17.
-constexpr int InternalPayload::kIndeterminateSize;
-
-InternalPayload::InternalPayload(Payload payload)
- : payload_(std::move(payload)), payload_id_(payload_.GetId()) {}
-
-Payload InternalPayload::ReleasePayload() { return std::move(payload_); }
-
-Payload::Id InternalPayload::GetId() const { return payload_id_; }
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/internal_payload.h b/chromium/third_party/nearby/src/cpp/core/internal/internal_payload.h
deleted file mode 100644
index d4c25b2395c..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/internal_payload.h
+++ /dev/null
@@ -1,106 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_INTERNAL_PAYLOAD_H_
-#define CORE_INTERNAL_INTERNAL_PAYLOAD_H_
-
-#include <cstdint>
-
-#include "core/payload.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/exception.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Defines the operations layered atop a Payload, for use inside the
-// OfflineServiceController.
-//
-// <p>There will be an extension of this abstract base class per type of
-// Payload.
-class InternalPayload {
- public:
- static constexpr int kIndeterminateSize = -1;
-
- explicit InternalPayload(Payload payload);
- virtual ~InternalPayload() = default;
-
- Payload ReleasePayload();
-
- Payload::Id GetId() const;
-
- // Returns the PayloadType of the Payload to which this object is bound.
- //
- // <p>Note that this is supposed to return the type from the OfflineFrame
- // proto rather than what is already available via
- // Payload::getType().
- //
- // @return The PayloadType.
- virtual PayloadTransferFrame::PayloadHeader::PayloadType GetType() const = 0;
-
- // Deduces the total size of the Payload to which this object is bound.
- //
- // @return The total size, or -1 if it cannot be deduced (for example, when
- // dealing with streaming data).
- virtual std::int64_t GetTotalSize() const = 0;
-
- // Breaks off the next chunk from the Payload to which this object is bound.
- //
- // <p>Used when we have a complete Payload that we want to break into smaller
- // byte blobs for sending across a hard boundary (like the other side of
- // a Binder, or another device altogether).
- //
- // @param chunk_size The preferred size of the next chunk. Depending on
- // payload type, the provided size may be ignored.
- // @return The next chunk from the Payload, or null if we've reached the end.
- virtual ByteArray DetachNextChunk(int chunk_size) = 0;
-
- // Adds the next chunk that comprises the Payload to which this object is
- // bound.
- //
- // <p>Used when we are trying to reconstruct a Payload that lives on the
- // other side of a hard boundary (like the other side of a Binder, or another
- // device altogether), one byte blob at a time.
- //
- // @param chunk The next chunk; this being null signals that this is the last
- // chunk, which will typically be used as a trigger to perform whatever state
- // cleanup may be required by the concrete implementation.
- virtual Exception AttachNextChunk(const ByteArray& chunk) = 0;
-
- // Skips current stream pointer to the offset.
- //
- // Used when this is a resume outgoing transfer, so we want to skip
- // some data until the offset position.
- //
- // @return the offset really skipped
- virtual ExceptionOr<size_t> SkipToOffset(size_t offset) = 0;
-
- // Cleans up any resources used by this Payload. Called when we're stopping
- // early, e.g. after being cancelled or having no more recipients left.
- virtual void Close() {}
-
- protected:
- Payload payload_;
- // We're caching the payload ID here because the backing payload will be
- // released to another owner during the lifetime of an incoming
- // InternalPayload.
- Payload::Id payload_id_;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_INTERNAL_PAYLOAD_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/internal_payload_factory.cc b/chromium/third_party/nearby/src/cpp/core/internal/internal_payload_factory.cc
deleted file mode 100644
index 8895992d917..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/internal_payload_factory.cc
+++ /dev/null
@@ -1,350 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/internal_payload_factory.h"
-
-#include <cstdint>
-#include <memory>
-
-#include "absl/memory/memory.h"
-#include "core/payload.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/exception.h"
-#include "platform/public/condition_variable.h"
-#include "platform/public/file.h"
-#include "platform/public/logging.h"
-#include "platform/public/mutex.h"
-#include "platform/public/pipe.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-namespace {
-
-class BytesInternalPayload : public InternalPayload {
- public:
- explicit BytesInternalPayload(Payload payload)
- : InternalPayload(std::move(payload)),
- total_size_(payload_.AsBytes().size()),
- detached_only_chunk_(false) {}
-
- PayloadTransferFrame::PayloadHeader::PayloadType GetType() const override {
- return PayloadTransferFrame::PayloadHeader::BYTES;
- }
-
- std::int64_t GetTotalSize() const override { return total_size_; }
-
- // Relinquishes ownership of the payload_; retrieves and returns the stored
- // ByteArray.
- ByteArray DetachNextChunk(int chunk_size) override {
- if (detached_only_chunk_) {
- return {};
- }
-
- detached_only_chunk_ = true;
- return std::move(payload_).AsBytes();
- }
-
- // Does nothing.
- Exception AttachNextChunk(const ByteArray& chunk) override {
- return {Exception::kSuccess};
- }
-
- ExceptionOr<size_t> SkipToOffset(size_t offset) override {
- NEARBY_LOGS(WARNING) << "Bytes payload does not support offsets";
- return {Exception::kIo};
- }
-
- private:
- // We're caching the total size here because the backing payload will be
- // moved to another owner during the lifetime of an incoming
- // InternalPayload.
- const std::int64_t total_size_;
- bool detached_only_chunk_;
-};
-
-class OutgoingStreamInternalPayload : public InternalPayload {
- public:
- explicit OutgoingStreamInternalPayload(Payload payload)
- : InternalPayload(std::move(payload)) {}
-
- PayloadTransferFrame::PayloadHeader::PayloadType GetType() const override {
- return PayloadTransferFrame::PayloadHeader::STREAM;
- }
-
- std::int64_t GetTotalSize() const override { return -1; }
-
- ByteArray DetachNextChunk(int chunk_size) override {
- InputStream* input_stream = payload_.AsStream();
- if (!input_stream) return {};
-
- ExceptionOr<ByteArray> bytes_read = input_stream->Read(chunk_size);
- if (!bytes_read.ok()) {
- input_stream->Close();
- return {};
- }
-
- ByteArray scoped_bytes_read = std::move(bytes_read.result());
-
- if (scoped_bytes_read.Empty()) {
- NEARBY_LOGS(INFO) << "No more data for outgoing payload " << this
- << ", closing InputStream.";
-
- input_stream->Close();
- return {};
- }
-
- return scoped_bytes_read;
- }
-
- Exception AttachNextChunk(const ByteArray& chunk) override {
- return {Exception::kIo};
- }
-
- ExceptionOr<size_t> SkipToOffset(size_t offset) override {
- InputStream* stream = payload_.AsStream();
- if (stream == nullptr) return {Exception::kIo};
-
- ExceptionOr<size_t> real_offset = stream->Skip(offset);
- if (real_offset.ok() && real_offset.GetResult() == offset) {
- return real_offset;
- }
- // Close the outgoing stream on any error
- stream->Close();
- if (!real_offset.ok()) {
- return real_offset;
- }
- NEARBY_LOGS(WARNING) << "Skip offset: " << real_offset.GetResult()
- << ", expected offset: " << offset << " for payload "
- << this;
- return {Exception::kIo};
- }
-
- void Close() override {
- // Ignore the potential Exception returned by close(), as a counterpart
- // to Java's closeQuietly().
- InputStream* stream = payload_.AsStream();
- if (stream) stream->Close();
- }
-};
-
-class IncomingStreamInternalPayload : public InternalPayload {
- public:
- IncomingStreamInternalPayload(Payload payload, OutputStream& output_stream)
- : InternalPayload(std::move(payload)), output_stream_(&output_stream) {}
-
- PayloadTransferFrame::PayloadHeader::PayloadType GetType() const override {
- return PayloadTransferFrame::PayloadHeader::STREAM;
- }
-
- std::int64_t GetTotalSize() const override { return -1; }
-
- ByteArray DetachNextChunk(int chunk_size) override { return {}; }
-
- Exception AttachNextChunk(const ByteArray& chunk) override {
- if (chunk.Empty()) {
- NEARBY_LOGS(INFO) << "Received null last chunk for incoming payload "
- << this << ", closing OutputStream.";
- output_stream_->Close();
- return {Exception::kSuccess};
- }
-
- return output_stream_->Write(chunk);
- }
-
- ExceptionOr<size_t> SkipToOffset(size_t offset) override {
- NEARBY_LOGS(WARNING) << "Cannot skip offset for an incoming Payload "
- << this;
- return {Exception::kIo};
- }
-
- void Close() override { output_stream_->Close(); }
-
- private:
- OutputStream* output_stream_;
-};
-
-class OutgoingFileInternalPayload : public InternalPayload {
- public:
- explicit OutgoingFileInternalPayload(Payload payload)
- : InternalPayload(std::move(payload)),
- total_size_{payload_.AsFile()->GetTotalSize()} {}
-
- PayloadTransferFrame::PayloadHeader::PayloadType GetType() const override {
- return PayloadTransferFrame::PayloadHeader::FILE;
- }
-
- std::int64_t GetTotalSize() const override { return total_size_; }
-
- ByteArray DetachNextChunk(int chunk_size) override {
- InputFile* file = payload_.AsFile();
- if (!file) return {};
-
- ExceptionOr<ByteArray> bytes_read = file->Read(chunk_size);
- if (!bytes_read.ok()) {
- return {};
- }
-
- ByteArray bytes = std::move(bytes_read.result());
-
- if (bytes.Empty()) {
- // No more data for outgoing payload.
-
- file->Close();
- return {};
- }
-
- return bytes;
- }
-
- Exception AttachNextChunk(const ByteArray& chunk) override {
- return {Exception::kIo};
- }
-
- ExceptionOr<size_t> SkipToOffset(size_t offset) override {
- NEARBY_LOGS(INFO) << "SkipToOffset " << offset;
- InputFile* file = payload_.AsFile();
- if (!file) {
- return {Exception::kIo};
- }
-
- ExceptionOr<size_t> real_offset = file->Skip(offset);
- if (real_offset.ok() && real_offset.GetResult() == offset) {
- return real_offset;
- }
- // Close the outgoing file on any error
- file->Close();
- if (!real_offset.ok()) {
- return real_offset;
- }
- NEARBY_LOGS(WARNING) << "Skip offset: " << real_offset.GetResult()
- << ", expected offset: " << offset
- << " for file payload " << this;
- return {Exception::kIo};
- }
-
- void Close() override {
- InputFile* file = payload_.AsFile();
- if (file) file->Close();
- }
-
- private:
- std::int64_t total_size_;
-};
-
-class IncomingFileInternalPayload : public InternalPayload {
- public:
- IncomingFileInternalPayload(Payload payload, OutputFile output_file,
- std::int64_t total_size)
- : InternalPayload(std::move(payload)),
- output_file_(std::move(output_file)),
- total_size_(total_size) {}
-
- PayloadTransferFrame::PayloadHeader::PayloadType GetType() const override {
- return PayloadTransferFrame::PayloadHeader::FILE;
- }
-
- std::int64_t GetTotalSize() const override { return total_size_; }
-
- ByteArray DetachNextChunk(int chunk_size) override { return {}; }
-
- Exception AttachNextChunk(const ByteArray& chunk) override {
- if (chunk.Empty()) {
- // Received null last chunk for incoming payload.
- output_file_.Close();
- return {Exception::kSuccess};
- }
-
- return output_file_.Write(chunk);
- }
-
- ExceptionOr<size_t> SkipToOffset(size_t offset) override {
- NEARBY_LOGS(WARNING) << "Cannot skip offset for an incoming file Payload "
- << this;
- return {Exception::kIo};
- }
-
- void Close() override { output_file_.Close(); }
-
- private:
- OutputFile output_file_;
- const std::int64_t total_size_;
-};
-
-} // namespace
-
-std::unique_ptr<InternalPayload> CreateOutgoingInternalPayload(
- Payload payload) {
- switch (payload.GetType()) {
- case Payload::Type::kBytes:
- return absl::make_unique<BytesInternalPayload>(std::move(payload));
-
- case Payload::Type::kFile: {
- InputFile* file = payload.AsFile();
- const PayloadId file_payload_id = file ? file->GetPayloadId() : 0;
- const PayloadId payload_id = payload.GetId();
- CHECK(payload_id == file_payload_id);
- return absl::make_unique<OutgoingFileInternalPayload>(std::move(payload));
- }
-
- case Payload::Type::kStream:
- return absl::make_unique<OutgoingStreamInternalPayload>(
- std::move(payload));
-
- default:
- DCHECK(false); // This should never happen.
- return {};
- }
-}
-
-std::unique_ptr<InternalPayload> CreateIncomingInternalPayload(
- const PayloadTransferFrame& frame) {
- if (frame.packet_type() != PayloadTransferFrame::DATA) {
- return {};
- }
-
- const Payload::Id payload_id = frame.payload_header().id();
- switch (frame.payload_header().type()) {
- case PayloadTransferFrame::PayloadHeader::BYTES: {
- return absl::make_unique<BytesInternalPayload>(
- Payload(payload_id, ByteArray(frame.payload_chunk().body())));
- }
-
- case PayloadTransferFrame::PayloadHeader::STREAM: {
- auto pipe = std::make_shared<Pipe>();
-
- return absl::make_unique<IncomingStreamInternalPayload>(
- Payload(payload_id,
- [pipe]() -> InputStream& {
- return pipe->GetInputStream(); // NOLINT
- }),
- pipe->GetOutputStream());
- }
-
- case PayloadTransferFrame::PayloadHeader::FILE: {
- std::int64_t total_size = frame.payload_header().total_size();
- return absl::make_unique<IncomingFileInternalPayload>(
- Payload(payload_id, InputFile(payload_id, total_size)),
- OutputFile(payload_id), total_size);
- }
- default:
- DCHECK(false); // This should never happen.
- return {};
- }
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/internal_payload_factory.h b/chromium/third_party/nearby/src/cpp/core/internal/internal_payload_factory.h
deleted file mode 100644
index a0387b77ed4..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/internal_payload_factory.h
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_INTERNAL_PAYLOAD_FACTORY_H_
-#define CORE_INTERNAL_INTERNAL_PAYLOAD_FACTORY_H_
-
-#include "core/internal/internal_payload.h"
-#include "core/payload.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Creates an InternalPayload representing an outgoing Payload.
-std::unique_ptr<InternalPayload> CreateOutgoingInternalPayload(Payload payload);
-
-// Creates an InternalPayload representing an incoming Payload from a remote
-// endpoint.
-std::unique_ptr<InternalPayload> CreateIncomingInternalPayload(
- const PayloadTransferFrame& frame);
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_INTERNAL_PAYLOAD_FACTORY_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/internal_payload_factory_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/internal_payload_factory_test.cc
deleted file mode 100644
index adfbe9b264a..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/internal_payload_factory_test.cc
+++ /dev/null
@@ -1,182 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/internal_payload_factory.h"
-
-#include <string>
-#include <utility>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "core/internal/offline_frames.h"
-#include "platform/base/byte_array.h"
-#include "platform/public/pipe.h"
-#include "proto/connections/offline_wire_formats.pb.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-
-constexpr char kText[] = "data chunk";
-
-TEST(InternalPayloadFActoryTest, CanCreateIternalPayloadFromBytePayload) {
- ByteArray data(kText);
- std::unique_ptr<InternalPayload> internal_payload =
- CreateOutgoingInternalPayload(Payload{data});
- EXPECT_NE(internal_payload, nullptr);
- Payload payload = internal_payload->ReleasePayload();
- EXPECT_EQ(payload.AsFile(), nullptr);
- EXPECT_EQ(payload.AsStream(), nullptr);
- EXPECT_EQ(payload.AsBytes(), ByteArray(kText));
-}
-
-TEST(InternalPayloadFActoryTest, CanCreateIternalPayloadFromStreamPayload) {
- auto pipe = std::make_shared<Pipe>();
- std::unique_ptr<InternalPayload> internal_payload =
- CreateOutgoingInternalPayload(Payload{[pipe]() -> InputStream& {
- return pipe->GetInputStream(); // NOLINT
- }});
- EXPECT_NE(internal_payload, nullptr);
- Payload payload = internal_payload->ReleasePayload();
- EXPECT_EQ(payload.AsFile(), nullptr);
- EXPECT_NE(payload.AsStream(), nullptr);
- EXPECT_EQ(payload.AsBytes(), ByteArray());
-}
-
-TEST(InternalPayloadFActoryTest, CanCreateIternalPayloadFromFilePayload) {
- Payload::Id payload_id = Payload::GenerateId();
- std::unique_ptr<InternalPayload> internal_payload =
- CreateOutgoingInternalPayload(
- Payload{payload_id, InputFile(payload_id, 512)});
- EXPECT_NE(internal_payload, nullptr);
- Payload payload = internal_payload->ReleasePayload();
- EXPECT_NE(payload.AsFile(), nullptr);
- EXPECT_EQ(payload.AsStream(), nullptr);
- EXPECT_EQ(payload.AsBytes(), ByteArray());
- EXPECT_EQ(payload.GetId(), payload_id);
- EXPECT_EQ(payload.AsFile()->GetPayloadId(), payload_id);
-}
-
-TEST(InternalPayloadFActoryTest, CanCreateIternalPayloadFromByteMessage) {
- PayloadTransferFrame frame;
- frame.set_packet_type(PayloadTransferFrame::DATA);
- std::int64_t payload_chunk_offset = 0;
- ByteArray data(kText);
- PayloadTransferFrame::PayloadChunk payload_chunk;
- payload_chunk.set_offset(payload_chunk_offset);
- payload_chunk.set_body(std::string(std::move(data)));
- payload_chunk.set_flags(0);
- auto& header = *frame.mutable_payload_header();
- header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
- header.set_id(12345);
- header.set_total_size(512);
- *frame.mutable_payload_chunk() = std::move(payload_chunk);
- std::unique_ptr<InternalPayload> internal_payload =
- CreateIncomingInternalPayload(frame);
- EXPECT_NE(internal_payload, nullptr);
- Payload payload = internal_payload->ReleasePayload();
- EXPECT_EQ(payload.AsFile(), nullptr);
- EXPECT_EQ(payload.AsStream(), nullptr);
- EXPECT_EQ(payload.AsBytes(), ByteArray(kText));
-}
-
-TEST(InternalPayloadFActoryTest, CanCreateIternalPayloadFromStreamMessage) {
- PayloadTransferFrame frame;
- frame.set_packet_type(PayloadTransferFrame::DATA);
- auto& header = *frame.mutable_payload_header();
- header.set_type(PayloadTransferFrame::PayloadHeader::STREAM);
- header.set_id(12345);
- header.set_total_size(0);
- std::unique_ptr<InternalPayload> internal_payload =
- CreateIncomingInternalPayload(frame);
- EXPECT_NE(internal_payload, nullptr);
- Payload payload = internal_payload->ReleasePayload();
- EXPECT_EQ(payload.AsFile(), nullptr);
- EXPECT_NE(payload.AsStream(), nullptr);
- EXPECT_EQ(payload.AsBytes(), ByteArray());
- EXPECT_EQ(payload.GetType(), Payload::Type::kStream);
-}
-
-TEST(InternalPayloadFActoryTest, CanCreateIternalPayloadFromFileMessage) {
- PayloadTransferFrame frame;
- frame.set_packet_type(PayloadTransferFrame::DATA);
- auto& header = *frame.mutable_payload_header();
- header.set_type(PayloadTransferFrame::PayloadHeader::FILE);
- header.set_id(12345);
- header.set_total_size(512);
- std::unique_ptr<InternalPayload> internal_payload =
- CreateIncomingInternalPayload(frame);
- EXPECT_NE(internal_payload, nullptr);
- Payload payload = internal_payload->ReleasePayload();
- EXPECT_NE(payload.AsFile(), nullptr);
- EXPECT_EQ(payload.AsStream(), nullptr);
- EXPECT_EQ(payload.AsBytes(), ByteArray());
- EXPECT_EQ(payload.GetType(), Payload::Type::kFile);
- EXPECT_EQ(payload.GetId(), payload.AsFile()->GetPayloadId());
-}
-
-void CreateFileWithContents(Payload::Id payload_id, const ByteArray& contents) {
- OutputFile file(payload_id);
- EXPECT_TRUE(file.Write(contents).Ok());
- EXPECT_TRUE(file.Close().Ok());
-}
-
-TEST(InternalPayloadFActoryTest,
- SkipToOffset_FilePayloadValidOffset_SkipsOffset) {
- ByteArray contents("0123456789");
- constexpr size_t kOffset = 4;
- size_t size_after_skip = contents.size() - kOffset;
- Payload::Id payload_id = Payload::GenerateId();
- CreateFileWithContents(payload_id, contents);
- std::unique_ptr<InternalPayload> internal_payload =
- CreateOutgoingInternalPayload(
- Payload{payload_id, InputFile(payload_id, contents.size())});
- EXPECT_NE(internal_payload, nullptr);
-
- ExceptionOr<size_t> result = internal_payload->SkipToOffset(kOffset);
-
- EXPECT_TRUE(result.ok());
- EXPECT_EQ(result.GetResult(), kOffset);
- EXPECT_EQ(internal_payload->GetTotalSize(), contents.size());
- ByteArray contents_after_skip =
- internal_payload->DetachNextChunk(size_after_skip);
- EXPECT_EQ(contents_after_skip, ByteArray("456789"));
-}
-
-TEST(InternalPayloadFActoryTest,
- SkipToOffset_StreamPayloadValidOffset_SkipsOffset) {
- ByteArray contents("0123456789");
- constexpr size_t kOffset = 6;
- auto pipe = std::make_shared<Pipe>();
- std::unique_ptr<InternalPayload> internal_payload =
- CreateOutgoingInternalPayload(Payload{[pipe]() -> InputStream& {
- return pipe->GetInputStream(); // NOLINT
- }});
- EXPECT_NE(internal_payload, nullptr);
- pipe->GetOutputStream().Write(contents);
-
- ExceptionOr<size_t> result = internal_payload->SkipToOffset(kOffset);
-
- EXPECT_TRUE(result.ok());
- EXPECT_EQ(result.GetResult(), kOffset);
- EXPECT_EQ(internal_payload->GetTotalSize(), -1);
- ByteArray contents_after_skip = internal_payload->DetachNextChunk(512);
- EXPECT_EQ(contents_after_skip, ByteArray("6789"));
-}
-
-} // namespace
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/BUILD b/chromium/third_party/nearby/src/cpp/core/internal/mediums/BUILD
deleted file mode 100644
index 7f5307234a3..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/BUILD
+++ /dev/null
@@ -1,142 +0,0 @@
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# https://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-licenses(["notice"])
-
-cc_library(
- name = "mediums",
- srcs = [
- "ble.cc",
- "bloom_filter.cc",
- "bluetooth_classic.cc",
- "bluetooth_radio.cc",
- "mediums.cc",
- "uuid.cc",
- "webrtc.cc",
- "wifi_lan.cc",
- ],
- hdrs = [
- "ble.h",
- "bloom_filter.h",
- "bluetooth_classic.h",
- "bluetooth_radio.h",
- "lost_entity_tracker.h",
- "mediums.h",
- "uuid.h",
- "webrtc.h",
- "wifi_lan.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- visibility = [
- "//core/internal:__subpackages__",
- ],
- deps = [
- ":utils",
- "//absl/container:flat_hash_map",
- "//absl/container:flat_hash_set",
- "//absl/functional:bind_front",
- "//absl/numeric:int128",
- "//absl/strings",
- "//absl/strings:str_format",
- "//absl/time",
- "//core:core_types",
- "//core/internal/mediums/ble_v2",
- "//core/internal/mediums/webrtc",
- "//core/internal/mediums/webrtc:data_types",
- "//platform/base",
- "//platform/base:cancellation_flag",
- "//platform/public:comm",
- "//platform/public:logging",
- "//platform/public:types",
- "//proto/connections:offline_wire_formats_portable_proto",
- "//proto/mediums:web_rtc_signaling_frames_cc_proto",
- "//smhasher:libmurmur3",
- "//webrtc/api:libjingle_peerconnection_api",
- ],
-)
-
-cc_library(
- name = "utils",
- srcs = [
- "utils.cc",
- "webrtc_peer_id.cc",
- ],
- hdrs = [
- "utils.h",
- "webrtc_peer_id.h",
- "webrtc_socket_wrapper.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- visibility = [
- "//core/internal:__pkg__",
- "//core/internal/mediums:__pkg__",
- "//core/internal/mediums/webrtc:__pkg__",
- ],
- deps = [
- "//absl/strings",
- "//core/internal/mediums/webrtc:data_types",
- "//platform/base",
- "//platform/public:types",
- "//proto/connections:offline_wire_formats_portable_proto",
- ],
-)
-
-cc_test(
- name = "core_internal_mediums_test",
- size = "small",
- srcs = [
- "ble_test.cc",
- "bloom_filter_test.cc",
- "bluetooth_classic_test.cc",
- "bluetooth_radio_test.cc",
- "lost_entity_tracker_test.cc",
- "uuid_test.cc",
- "wifi_lan_test.cc",
- ],
- shard_count = 16,
- deps = [
- ":mediums",
- ":utils",
- "//testing/base/public:gunit_main",
- "//absl/strings",
- "//absl/time",
- "//platform/base",
- "//platform/base:test_util",
- "//platform/impl/g3", # build_cleaner: keep
- "//platform/public:comm",
- "//platform/public:types",
- ],
-)
-
-cc_test(
- name = "core_internal_mediums_webrtc_test",
- size = "small",
- srcs = [
- "webrtc_peer_id_test.cc",
- "webrtc_test.cc",
- ],
- shard_count = 16,
- tags = [
- "notsan", # NOTE(b/139734036): known data race in usrsctplib.
- "requires-net:external",
- ],
- deps = [
- ":mediums",
- ":utils",
- "//testing/base/public:gunit_main",
- "//platform/base",
- "//platform/base:test_util",
- "//platform/impl/g3", # build_cleaner: keep
- "//platform/public:types",
- ],
-)
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble.cc
deleted file mode 100644
index 63e54f8dce7..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble.cc
+++ /dev/null
@@ -1,361 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/ble.h"
-
-#include <memory>
-#include <string>
-#include <utility>
-
-#include "absl/strings/escaping.h"
-#include "core/internal/mediums/ble_v2/ble_advertisement.h"
-#include "core/internal/mediums/utils.h"
-#include "platform/base/prng.h"
-#include "platform/public/logging.h"
-#include "platform/public/mutex_lock.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-ByteArray Ble::GenerateHash(const std::string& source, size_t size) {
- return Utils::Sha256Hash(source, size);
-}
-
-ByteArray Ble::GenerateDeviceToken() {
- return Utils::Sha256Hash(std::to_string(Prng().NextUint32()),
- mediums::BleAdvertisement::kDeviceTokenLength);
-}
-
-Ble::Ble(BluetoothRadio& radio) : radio_(radio) {}
-
-bool Ble::IsAvailable() const {
- MutexLock lock(&mutex_);
-
- return IsAvailableLocked();
-}
-
-bool Ble::IsAvailableLocked() const { return medium_.IsValid(); }
-
-bool Ble::StartAdvertising(const std::string& service_id,
- const ByteArray& advertisement_bytes,
- const std::string& fast_advertisement_service_uuid) {
- MutexLock lock(&mutex_);
-
- if (advertisement_bytes.Empty()) {
- NEARBY_LOGS(INFO)
- << "Refusing to turn on BLE advertising. Empty advertisement data.";
- return false;
- }
-
- if (advertisement_bytes.size() > kMaxAdvertisementLength) {
- NEARBY_LOG(INFO,
- "Refusing to start BLE advertising because the advertisement "
- "was too long. Expected at most %d bytes but received %d.",
- kMaxAdvertisementLength, advertisement_bytes.size());
- return false;
- }
-
- if (IsAdvertisingLocked(service_id)) {
- NEARBY_LOGS(INFO)
- << "Failed to BLE advertise because we're already advertising.";
- return false;
- }
-
- if (!radio_.IsEnabled()) {
- NEARBY_LOGS(INFO)
- << "Can't start BLE scanning because Bluetooth was never turned on";
- return false;
- }
-
- if (!IsAvailableLocked()) {
- NEARBY_LOGS(INFO) << "Can't turn on BLE advertising. BLE is not available.";
- return false;
- }
-
- NEARBY_LOGS(INFO) << "Turning on BLE advertising (advertisement size="
- << advertisement_bytes.size() << ")"
- << ", service id=" << service_id
- << ", fast advertisement service uuid="
- << fast_advertisement_service_uuid;
-
- // Wrap the connections advertisement to the medium advertisement.
- const bool fast_advertisement = !fast_advertisement_service_uuid.empty();
- ByteArray service_id_hash{GenerateHash(
- service_id, mediums::BleAdvertisement::kServiceIdHashLength)};
- ByteArray medium_advertisement_bytes{mediums::BleAdvertisement{
- mediums::BleAdvertisement::Version::kV2,
- mediums::BleAdvertisement::SocketVersion::kV2,
- fast_advertisement ? ByteArray{} : service_id_hash, advertisement_bytes,
- GenerateDeviceToken()}};
- if (medium_advertisement_bytes.Empty()) {
- NEARBY_LOGS(INFO) << "Failed to BLE advertise because we could not "
- "create a medium advertisement.";
- return false;
- }
-
- if (!medium_.StartAdvertising(service_id, medium_advertisement_bytes,
- fast_advertisement_service_uuid)) {
- NEARBY_LOGS(ERROR)
- << "Failed to turn on BLE advertising with advertisement bytes="
- << absl::BytesToHexString(advertisement_bytes.data())
- << ", size=" << advertisement_bytes.size()
- << ", fast advertisement service uuid="
- << fast_advertisement_service_uuid;
- return false;
- }
-
- advertising_info_.Add(service_id);
- return true;
-}
-
-bool Ble::StopAdvertising(const std::string& service_id) {
- MutexLock lock(&mutex_);
-
- if (!IsAdvertisingLocked(service_id)) {
- NEARBY_LOGS(INFO) << "Can't turn off BLE advertising; it is already off";
- return false;
- }
-
- NEARBY_LOGS(INFO) << "Turned off BLE advertising with service id="
- << service_id;
- bool ret = medium_.StopAdvertising(service_id);
- // Reset our bundle of advertising state to mark that we're no longer
- // advertising.
- advertising_info_.Remove(service_id);
- return ret;
-}
-
-bool Ble::IsAdvertising(const std::string& service_id) {
- MutexLock lock(&mutex_);
-
- return IsAdvertisingLocked(service_id);
-}
-
-bool Ble::IsAdvertisingLocked(const std::string& service_id) {
- return advertising_info_.Existed(service_id);
-}
-
-bool Ble::StartScanning(const std::string& service_id,
- const std::string& fast_advertisement_service_uuid,
- DiscoveredPeripheralCallback callback) {
- MutexLock lock(&mutex_);
-
- discovered_peripheral_callback_ = std::move(callback);
-
- if (service_id.empty()) {
- NEARBY_LOGS(INFO)
- << "Refusing to start BLE scanning with empty service id.";
- return false;
- }
-
- if (IsScanningLocked(service_id)) {
- NEARBY_LOGS(INFO) << "Refusing to start scan of BLE peripherals because "
- "another scanning is already in-progress.";
- return false;
- }
-
- if (!radio_.IsEnabled()) {
- NEARBY_LOGS(INFO)
- << "Can't start BLE scanning because Bluetooth was never turned on";
- return false;
- }
-
- if (!IsAvailableLocked()) {
- NEARBY_LOGS(INFO)
- << "Can't scan BLE peripherals because BLE isn't available.";
- return false;
- }
-
- if (!medium_.StartScanning(
- service_id, fast_advertisement_service_uuid,
- {
- .peripheral_discovered_cb =
- [this](BlePeripheral& peripheral,
- const std::string& service_id,
- const ByteArray& medium_advertisement_bytes,
- bool fast_advertisement) {
- // Don't bother trying to parse zero byte advertisements.
- if (medium_advertisement_bytes.size() == 0) {
- NEARBY_LOGS(INFO) << "Skipping zero byte advertisement "
- << "with service_id: " << service_id;
- return;
- }
- // Unwrap connection BleAdvertisement from medium
- // BleAdvertisement.
- auto connection_advertisement_bytes =
- UnwrapAdvertisementBytes(medium_advertisement_bytes);
- discovered_peripheral_callback_.peripheral_discovered_cb(
- peripheral, service_id, connection_advertisement_bytes,
- fast_advertisement);
- },
- .peripheral_lost_cb =
- [this](BlePeripheral& peripheral,
- const std::string& service_id) {
- discovered_peripheral_callback_.peripheral_lost_cb(
- peripheral, service_id);
- },
- })) {
- NEARBY_LOGS(INFO) << "Failed to start scan of BLE services.";
- return false;
- }
-
- NEARBY_LOGS(INFO) << "Turned on BLE scanning with service id=" << service_id;
- // Mark the fact that we're currently performing a BLE discovering.
- scanning_info_.Add(service_id);
- return true;
-}
-
-bool Ble::StopScanning(const std::string& service_id) {
- MutexLock lock(&mutex_);
-
- if (!IsScanningLocked(service_id)) {
- NEARBY_LOGS(INFO) << "Can't turn off BLE sacanning because we never "
- "started scanning.";
- return false;
- }
-
- NEARBY_LOG(INFO, "Turned off BLE scanning with service id=%s",
- service_id.c_str());
- bool ret = medium_.StopScanning(service_id);
- scanning_info_.Clear();
- return ret;
-}
-
-bool Ble::IsScanning(const std::string& service_id) {
- MutexLock lock(&mutex_);
-
- return IsScanningLocked(service_id);
-}
-
-bool Ble::IsScanningLocked(const std::string& service_id) {
- return scanning_info_.Existed(service_id);
-}
-
-bool Ble::StartAcceptingConnections(const std::string& service_id,
- AcceptedConnectionCallback callback) {
- MutexLock lock(&mutex_);
-
- if (service_id.empty()) {
- NEARBY_LOGS(INFO)
- << "Refusing to start accepting BLE connections with empty service id.";
- return false;
- }
-
- if (IsAcceptingConnectionsLocked(service_id)) {
- NEARBY_LOGS(INFO)
- << "Refusing to start accepting BLE connections for " << service_id
- << " because another BLE peripheral socket is already in-progress.";
- return false;
- }
-
- if (!radio_.IsEnabled()) {
- NEARBY_LOGS(INFO) << "Can't start accepting BLE connections for "
- << service_id << " because Bluetooth isn't enabled.";
- return false;
- }
-
- if (!IsAvailableLocked()) {
- NEARBY_LOGS(INFO) << "Can't start accepting BLE connections for "
- << service_id << " because BLE isn't available.";
- return false;
- }
-
- if (!medium_.StartAcceptingConnections(service_id, callback)) {
- NEARBY_LOGS(INFO) << "Failed to accept connections callback for "
- << service_id << " .";
- return false;
- }
-
- accepting_connections_info_.Add(service_id);
- return true;
-}
-
-bool Ble::StopAcceptingConnections(const std::string& service_id) {
- MutexLock lock(&mutex_);
-
- if (!IsAcceptingConnectionsLocked(service_id)) {
- NEARBY_LOGS(INFO)
- << "Can't stop accepting BLE connections because it was never started.";
- return false;
- }
-
- bool ret = medium_.StopAcceptingConnections(service_id);
- // Reset our bundle of accepting connections state to mark that we're no
- // longer accepting connections.
- accepting_connections_info_.Remove(service_id);
- return ret;
-}
-
-bool Ble::IsAcceptingConnections(const std::string& service_id) {
- MutexLock lock(&mutex_);
-
- return IsAcceptingConnectionsLocked(service_id);
-}
-
-bool Ble::IsAcceptingConnectionsLocked(const std::string& service_id) {
- return accepting_connections_info_.Existed(service_id);
-}
-
-BleSocket Ble::Connect(BlePeripheral& peripheral, const std::string& service_id,
- CancellationFlag* cancellation_flag) {
- MutexLock lock(&mutex_);
- NEARBY_LOGS(INFO) << "BLE::Connect: service=" << &peripheral;
- // Socket to return. To allow for NRVO to work, it has to be a single object.
- BleSocket socket;
-
- if (service_id.empty()) {
- NEARBY_LOGS(INFO) << "Refusing to create BLE socket with empty service_id.";
- return socket;
- }
-
- if (!radio_.IsEnabled()) {
- NEARBY_LOGS(INFO) << "Can't create client BLE socket to " << &peripheral
- << " because Bluetooth isn't enabled.";
- return socket;
- }
-
- if (!IsAvailableLocked()) {
- NEARBY_LOGS(INFO) << "Can't create client BLE socket [service_id="
- << service_id << "]; BLE isn't available.";
- return socket;
- }
-
- if (cancellation_flag->Cancelled()) {
- NEARBY_LOGS(INFO) << "Can't create client BLE socket due to cancel.";
- return socket;
- }
-
- socket = medium_.Connect(peripheral, service_id, cancellation_flag);
- if (!socket.IsValid()) {
- NEARBY_LOGS(INFO) << "Failed to Connect via BLE [service=" << service_id
- << "]";
- }
-
- return socket;
-}
-
-ByteArray Ble::UnwrapAdvertisementBytes(
- const ByteArray& medium_advertisement_data) {
- mediums::BleAdvertisement medium_ble_advertisement{medium_advertisement_data};
- if (!medium_ble_advertisement.IsValid()) {
- return ByteArray{};
- }
-
- return medium_ble_advertisement.GetData();
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble.h b/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble.h
deleted file mode 100644
index bfacb340bfb..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble.h
+++ /dev/null
@@ -1,188 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_MEDIUMS_BLE_H_
-#define CORE_INTERNAL_MEDIUMS_BLE_H_
-
-#include <cstdint>
-#include <string>
-
-#include "absl/container/flat_hash_map.h"
-#include "absl/container/flat_hash_set.h"
-#include "core/internal/mediums/bluetooth_radio.h"
-#include "core/listeners.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/cancellation_flag.h"
-#include "platform/public/ble.h"
-#include "platform/public/multi_thread_executor.h"
-#include "platform/public/mutex.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-class Ble {
- public:
- using DiscoveredPeripheralCallback = BleMedium::DiscoveredPeripheralCallback;
- using AcceptedConnectionCallback = BleMedium::AcceptedConnectionCallback;
-
- explicit Ble(BluetoothRadio& bluetooth_radio);
- ~Ble() = default;
-
- // Returns true, if Ble communications are supported by a platform.
- bool IsAvailable() const ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Sets custom advertisement data, and then enables Ble advertising.
- // Returns true, if data is successfully set, and false otherwise.
- bool StartAdvertising(const std::string& service_id,
- const ByteArray& advertisement_bytes,
- const std::string& fast_advertisement_service_uuid)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Disables Ble advertising.
- bool StopAdvertising(const std::string& service_id)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- bool IsAdvertising(const std::string& service_id) ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Enables Ble scanning mode. Will report any discoverable peripherals in
- // range through a callback. Returns true, if scanning mode was enabled,
- // false otherwise.
- bool StartScanning(const std::string& service_id,
- const std::string& fast_advertisement_service_uuid,
- DiscoveredPeripheralCallback callback)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Disables Ble discovery mode.
- bool StopScanning(const std::string& service_id) ABSL_LOCKS_EXCLUDED(mutex_);
-
- bool IsScanning(const std::string& service_id) ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Starts a worker thread, creates a Ble socket, associates it with a
- // service id.
- bool StartAcceptingConnections(const std::string& service_id,
- AcceptedConnectionCallback callback)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Closes socket corresponding to a service id.
- bool StopAcceptingConnections(const std::string& service_id)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- bool IsAcceptingConnections(const std::string& service_id)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns true if this object owns a valid platform implementation.
- bool IsMediumValid() const ABSL_LOCKS_EXCLUDED(mutex_) {
- MutexLock lock(&mutex_);
- return medium_.IsValid();
- }
-
- // Returns true if this object has a valid BluetoothAdapter reference.
- bool IsAdapterValid() const ABSL_LOCKS_EXCLUDED(mutex_) {
- MutexLock lock(&mutex_);
- return adapter_.IsValid();
- }
-
- // Establishes connection to Ble peripheral that was might be started on
- // another peripheral with StartAcceptingConnections() using the same
- // service_id. Blocks until connection is established, or server-side is
- // terminated. Returns socket instance. On success, BleSocket.IsValid() return
- // true.
- BleSocket Connect(BlePeripheral& peripheral, const std::string& service_id,
- CancellationFlag* cancellation_flag)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- private:
- struct AdvertisingInfo {
- bool Empty() const { return service_ids.empty(); }
- void Clear() { service_ids.clear(); }
- void Add(const std::string& service_id) { service_ids.emplace(service_id); }
- void Remove(const std::string& service_id) {
- service_ids.erase(service_id);
- }
- bool Existed(const std::string& service_id) const {
- return service_ids.contains(service_id);
- }
-
- absl::flat_hash_set<std::string> service_ids;
- };
-
- struct ScanningInfo {
- bool Empty() const { return service_ids.empty(); }
- void Clear() { service_ids.clear(); }
- void Add(const std::string& service_id) { service_ids.emplace(service_id); }
- void Remove(const std::string& service_id) {
- service_ids.erase(service_id);
- }
- bool Existed(const std::string& service_id) const {
- return service_ids.contains(service_id);
- }
-
- absl::flat_hash_set<std::string> service_ids;
- };
-
- struct AcceptingConnectionsInfo {
- bool Empty() const { return service_ids.empty(); }
- void Clear() { service_ids.clear(); }
- void Add(const std::string& service_id) { service_ids.emplace(service_id); }
- void Remove(const std::string& service_id) {
- service_ids.erase(service_id);
- }
- bool Existed(const std::string& service_id) const {
- return service_ids.contains(service_id);
- }
-
- absl::flat_hash_set<std::string> service_ids;
- };
-
- static constexpr int kMaxAdvertisementLength = 512;
-
- static ByteArray GenerateHash(const std::string& source, size_t size);
- static ByteArray GenerateDeviceToken();
-
- // Same as IsAvailable(), but must be called with mutex_ held.
- bool IsAvailableLocked() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Same as IsAdvertising(), but must be called with mutex_ held.
- bool IsAdvertisingLocked(const std::string& service_id)
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Same as IsDiscovering(), but must be called with mutex_ held.
- bool IsScanningLocked(const std::string& service_id)
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Same as IsAcceptingConnections(), but must be called with mutex_ held.
- bool IsAcceptingConnectionsLocked(const std::string& service_id)
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Extract connection advertisement from medium advertisement.
- ByteArray UnwrapAdvertisementBytes(
- const ByteArray& medium_advertisement_data);
-
- mutable Mutex mutex_;
- BluetoothRadio& radio_ ABSL_GUARDED_BY(mutex_);
- BluetoothAdapter& adapter_ ABSL_GUARDED_BY(mutex_){
- radio_.GetBluetoothAdapter()};
- BleMedium medium_ ABSL_GUARDED_BY(mutex_){adapter_};
- AdvertisingInfo advertising_info_ ABSL_GUARDED_BY(mutex_);
- ScanningInfo scanning_info_ ABSL_GUARDED_BY(mutex_);
- DiscoveredPeripheralCallback discovered_peripheral_callback_;
- AcceptingConnectionsInfo accepting_connections_info_ ABSL_GUARDED_BY(mutex_);
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_MEDIUMS_BLE_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_test.cc
deleted file mode 100644
index 6f03e677617..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_test.cc
+++ /dev/null
@@ -1,263 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/ble.h"
-
-#include <string>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "core/internal/mediums/bluetooth_radio.h"
-#include "platform/base/medium_environment.h"
-#include "platform/public/ble.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-
-using FeatureFlags = FeatureFlags::Flags;
-
-constexpr FeatureFlags kTestCases[] = {
- FeatureFlags{
- .enable_cancellation_flag = true,
- },
- FeatureFlags{
- .enable_cancellation_flag = false,
- },
-};
-
-constexpr absl::Duration kWaitDuration = absl::Milliseconds(1000);
-constexpr absl::string_view kServiceID{"com.google.location.nearby.apps.test"};
-constexpr absl::string_view kAdvertisementString{"\x0a\x0b\x0c\x0d"};
-constexpr absl::string_view kFastAdvertisementServiceUuid{"\xf3\xfe"};
-
-class BleTest : public ::testing::TestWithParam<FeatureFlags> {
- protected:
- using DiscoveredPeripheralCallback = BleMedium::DiscoveredPeripheralCallback;
-
- BleTest() { env_.Stop(); }
-
- MediumEnvironment& env_{MediumEnvironment::Instance()};
-};
-
-TEST_P(BleTest, CanStartAcceptingConnectionsAndConnect) {
- FeatureFlags feature_flags = GetParam();
- env_.SetFeatureFlags(feature_flags);
- env_.Start();
- BluetoothRadio radio_a;
- BluetoothRadio radio_b;
- Ble ble_a{radio_a};
- Ble ble_b{radio_b};
- radio_a.Enable();
- radio_b.Enable();
- std::string service_id(kServiceID);
- ByteArray advertisement_bytes{std::string(kAdvertisementString)};
- std::string fast_advertisement_service_uuid(kFastAdvertisementServiceUuid);
- CountDownLatch found_latch(1);
- CountDownLatch accept_latch(1);
-
- ble_a.StartAdvertising(service_id, advertisement_bytes,
- fast_advertisement_service_uuid);
- ble_a.StartAcceptingConnections(
- service_id,
- {
- .accepted_cb = [&accept_latch](
- BleSocket socket,
- const std::string&) { accept_latch.CountDown(); },
- });
- BlePeripheral discovered_peripheral;
- ble_b.StartScanning(
- service_id, fast_advertisement_service_uuid,
- {
- .peripheral_discovered_cb =
- [&found_latch, &discovered_peripheral](
- BlePeripheral& peripheral, const std::string& service_id,
- const ByteArray& advertisement_bytes,
- bool fast_advertisement) {
- discovered_peripheral = peripheral;
- NEARBY_LOG(
- INFO,
- "Discovered peripheral=%p [impl=%p], fast advertisement=%d",
- &peripheral, &peripheral.GetImpl(), fast_advertisement);
- found_latch.CountDown();
- },
- });
-
- EXPECT_TRUE(found_latch.Await(kWaitDuration).result());
- ASSERT_TRUE(discovered_peripheral.IsValid());
- CancellationFlag flag;
- BleSocket socket = ble_b.Connect(discovered_peripheral, service_id, &flag);
- EXPECT_TRUE(accept_latch.Await(kWaitDuration).result());
- EXPECT_TRUE(socket.IsValid());
- ble_b.StopScanning(service_id);
- ble_a.StopAdvertising(service_id);
- env_.Stop();
-}
-
-TEST_P(BleTest, CanCancelConnect) {
- FeatureFlags feature_flags = GetParam();
- env_.SetFeatureFlags(feature_flags);
- env_.Start();
- BluetoothRadio radio_a;
- BluetoothRadio radio_b;
- Ble ble_a{radio_a};
- Ble ble_b{radio_b};
- radio_a.Enable();
- radio_b.Enable();
- std::string service_id(kServiceID);
- ByteArray advertisement_bytes{std::string(kAdvertisementString)};
- std::string fast_advertisement_service_uuid(kFastAdvertisementServiceUuid);
- CountDownLatch found_latch(1);
- CountDownLatch accept_latch(1);
-
- ble_a.StartAdvertising(service_id, advertisement_bytes,
- fast_advertisement_service_uuid);
- ble_a.StartAcceptingConnections(
- service_id,
- {
- .accepted_cb = [&accept_latch](
- BleSocket socket,
- const std::string&) { accept_latch.CountDown(); },
- });
- BlePeripheral discovered_peripheral;
- ble_b.StartScanning(
- service_id, fast_advertisement_service_uuid,
- {
- .peripheral_discovered_cb =
- [&found_latch, &discovered_peripheral](
- BlePeripheral& peripheral, const std::string& service_id,
- const ByteArray& advertisement_bytes,
- bool fast_advertisement) {
- discovered_peripheral = peripheral;
- NEARBY_LOG(
- INFO,
- "Discovered peripheral=%p [impl=%p], fast advertisement=%d",
- &peripheral, &peripheral.GetImpl(), fast_advertisement);
- found_latch.CountDown();
- },
- });
-
- EXPECT_TRUE(found_latch.Await(kWaitDuration).result());
- ASSERT_TRUE(discovered_peripheral.IsValid());
- CancellationFlag flag(true);
- BleSocket socket = ble_b.Connect(discovered_peripheral, service_id, &flag);
- // If FeatureFlag is disabled, Cancelled is false as no-op.
- if (!feature_flags.enable_cancellation_flag) {
- EXPECT_TRUE(accept_latch.Await(kWaitDuration).result());
- EXPECT_TRUE(socket.IsValid());
- } else {
- EXPECT_FALSE(accept_latch.Await(kWaitDuration).result());
- EXPECT_FALSE(socket.IsValid());
- }
- ble_b.StopScanning(service_id);
- ble_a.StopAdvertising(service_id);
- env_.Stop();
-}
-
-INSTANTIATE_TEST_SUITE_P(ParametrisedBleTest, BleTest,
- ::testing::ValuesIn(kTestCases));
-
-TEST_F(BleTest, CanConstructValidObject) {
- env_.Start();
- BluetoothRadio radio_a;
- BluetoothRadio radio_b;
- Ble ble_a{radio_a};
- Ble ble_b{radio_b};
-
- EXPECT_TRUE(ble_a.IsMediumValid());
- EXPECT_TRUE(ble_a.IsAdapterValid());
- EXPECT_TRUE(ble_a.IsAvailable());
- EXPECT_TRUE(ble_b.IsMediumValid());
- EXPECT_TRUE(ble_b.IsAdapterValid());
- EXPECT_TRUE(ble_b.IsAvailable());
- EXPECT_NE(&radio_a.GetBluetoothAdapter(), &radio_b.GetBluetoothAdapter());
- env_.Stop();
-}
-
-TEST_F(BleTest, CanStartAdvertising) {
- env_.Start();
- BluetoothRadio radio_a;
- BluetoothRadio radio_b;
- Ble ble_a{radio_a};
- Ble ble_b{radio_b};
- radio_a.Enable();
- radio_b.Enable();
- std::string service_id(kServiceID);
- ByteArray advertisement_bytes{std::string(kAdvertisementString)};
- std::string fast_advertisement_service_uuid(kFastAdvertisementServiceUuid);
- CountDownLatch found_latch(1);
-
- ble_b.StartScanning(
- service_id, fast_advertisement_service_uuid,
- DiscoveredPeripheralCallback{
- .peripheral_discovered_cb =
- [&found_latch](
- BlePeripheral& peripheral, const std::string& service_id,
- const ByteArray& advertisement_bytes,
- bool fast_advertisement) { found_latch.CountDown(); },
- });
-
- EXPECT_TRUE(ble_a.StartAdvertising(service_id, advertisement_bytes,
- fast_advertisement_service_uuid));
- EXPECT_TRUE(found_latch.Await(kWaitDuration).result());
- EXPECT_TRUE(ble_a.StopAdvertising(service_id));
- EXPECT_TRUE(ble_b.StopScanning(service_id));
- env_.Stop();
-}
-
-TEST_F(BleTest, CanStartDiscovery) {
- env_.Start();
- BluetoothRadio radio_a;
- BluetoothRadio radio_b;
- Ble ble_a{radio_a};
- Ble ble_b{radio_b};
- radio_a.Enable();
- radio_b.Enable();
- std::string service_id(kServiceID);
- ByteArray advertisement_bytes{std::string(kAdvertisementString)};
- std::string fast_advertisement_service_uuid(kFastAdvertisementServiceUuid);
- CountDownLatch accept_latch(1);
- CountDownLatch lost_latch(1);
-
- ble_b.StartAdvertising(service_id, advertisement_bytes,
- fast_advertisement_service_uuid);
-
- EXPECT_TRUE(ble_a.StartScanning(
- service_id, fast_advertisement_service_uuid,
- DiscoveredPeripheralCallback{
- .peripheral_discovered_cb =
- [&accept_latch](
- BlePeripheral& peripheral, const std::string& service_id,
- const ByteArray& advertisement_bytes,
- bool fast_advertisement) { accept_latch.CountDown(); },
- .peripheral_lost_cb =
- [&lost_latch](BlePeripheral& peripheral,
- const std::string& service_id) {
- lost_latch.CountDown();
- },
- }));
- EXPECT_TRUE(accept_latch.Await(kWaitDuration).result());
- ble_b.StopAdvertising(service_id);
- EXPECT_TRUE(lost_latch.Await(kWaitDuration).result());
- EXPECT_TRUE(ble_a.StopScanning(service_id));
- env_.Stop();
-}
-
-} // namespace
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/BUILD b/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/BUILD
deleted file mode 100644
index 6aff35972f6..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/BUILD
+++ /dev/null
@@ -1,67 +0,0 @@
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# https://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-licenses(["notice"])
-
-cc_library(
- name = "ble_v2",
- srcs = [
- "advertisement_read_result.cc",
- "ble_advertisement.cc",
- "ble_advertisement_header.cc",
- "ble_packet.cc",
- ],
- hdrs = [
- "advertisement_read_result.h",
- "ble_advertisement.h",
- "ble_advertisement_header.h",
- "ble_packet.h",
- "ble_peripheral.h",
- "discovered_peripheral_callback.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- copts = ["-DCORE_ADAPTER_DLL"],
- visibility = [
- "//core/internal:__subpackages__",
- ],
- deps = [
- "//absl/container:flat_hash_map",
- "//absl/container:flat_hash_set",
- "//absl/strings",
- "//absl/time",
- "//core:core_types",
- "//platform/base",
- "//platform/base:util",
- "//platform/public:logging",
- "//platform/public:types",
- ],
-)
-
-cc_test(
- name = "ble_v2_test",
- srcs = [
- "advertisement_read_result_test.cc",
- "ble_advertisement_header_test.cc",
- "ble_advertisement_test.cc",
- "ble_packet_test.cc",
- "ble_peripheral_test.cc",
- ],
- deps = [
- ":ble_v2",
- "//testing/base/public:gunit_main",
- "//absl/time",
- "//platform/base",
- "//platform/impl/g3", # buildcleaner: keep
- "//platform/public:comm",
- ],
-)
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/advertisement_read_result.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/advertisement_read_result.cc
deleted file mode 100644
index aa82f0ed522..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/advertisement_read_result.cc
+++ /dev/null
@@ -1,139 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/ble_v2/advertisement_read_result.h"
-
-#include <algorithm>
-#include <vector>
-
-#include "absl/container/flat_hash_set.h"
-#include "absl/time/clock.h"
-#include "platform/public/mutex_lock.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-const AdvertisementReadResult::Config AdvertisementReadResult::kDefaultConfig{
- .backoff_multiplier = 2.0,
- .base_backoff_duration = absl::Seconds(1),
- .max_backoff_duration = absl::Minutes(5),
-};
-
-// Adds a successfully read advertisement for the specified slot to this read
-// result. This is fundamentally different from RecordLastReadStatus() because
-// we can report a read failure, but still manage to read some advertisements.
-void AdvertisementReadResult::AddAdvertisement(std::int32_t slot,
- const ByteArray& advertisement) {
- MutexLock lock(&mutex_);
-
- // Blindly remove from the advertisements map to make sure any existing
- // key-value pair is destroyed.
- advertisements_.emplace(slot, advertisement);
-}
-
-// Determines whether or not an advertisement was successfully read at the
-// specified slot.
-bool AdvertisementReadResult::HasAdvertisement(std::int32_t slot) const {
- MutexLock lock(&mutex_);
-
- return advertisements_.contains(slot);
-}
-
-// Retrieves all raw advertisements that were successfully read.
-std::vector<const ByteArray*> AdvertisementReadResult::GetAdvertisements()
- const {
- MutexLock lock(&mutex_);
-
- std::vector<const ByteArray*> all_advertisements;
- all_advertisements.reserve(advertisements_.size());
- for (const auto& item : advertisements_) {
- all_advertisements.emplace_back(&item.second);
- }
-
- return all_advertisements;
-}
-
-// Determines what stage we're in for retrying a read from an advertisement
-// GATT server.
-AdvertisementReadResult::RetryStatus
-AdvertisementReadResult::EvaluateRetryStatus() const {
- MutexLock lock(&mutex_);
-
- // Check if we have already succeeded reading this advertisement.
- if (status_ == Status::kSuccess) {
- return RetryStatus::kPreviouslySucceeded;
- }
-
- // Check if we have recently failed to read this advertisement.
- if (GetDurationSinceReadLocked() < backoff_duration_) {
- return RetryStatus::kTooSoon;
- }
-
- return RetryStatus::kRetry;
-}
-
-// Records the status of the latest read, and updates the next backoff
-// duration for subsequent reads. Be sure to also call
-// AddAdvertisement() if any advertisements were read.
-void AdvertisementReadResult::RecordLastReadStatus(bool is_success) {
- MutexLock lock(&mutex_);
-
- // Update the last read timestamp.
- last_read_timestamp_ = SystemClock::ElapsedRealtime();
-
- // Update the backoff duration.
- if (is_success) {
- // Reset the backoff duration now that we had a successful read.
- backoff_duration_ = config_.base_backoff_duration;
- } else {
- // Determine whether or not we were already failing before. If we were, we
- // should increase the backoff duration.
- if (status_ == Status::kFailure) {
- // Use exponential backoff to determine the next backoff duration. This
- // simply involves multiplying our current backoff duration by some
- // multiplier.
- absl::Duration next_backoff_duration =
- config_.backoff_multiplier * backoff_duration_;
- // Update the backoff duration, making sure not to blow past the
- // ceiling.
- backoff_duration_ =
- std::min(next_backoff_duration, config_.max_backoff_duration);
- } else {
- // This is our first time failing, so we should only backoff for the
- // initial duration.
- backoff_duration_ = config_.base_backoff_duration;
- }
- }
-
- // Update the internal result.
- status_ = is_success ? Status::kSuccess : Status::kFailure;
-}
-
-// Returns how much time has passed since we last tried reading from an
-// advertisement GATT server.
-absl::Duration AdvertisementReadResult::GetDurationSinceRead() const {
- MutexLock lock(&mutex_);
- return GetDurationSinceReadLocked();
-}
-
-absl::Duration AdvertisementReadResult::GetDurationSinceReadLocked() const {
- return SystemClock::ElapsedRealtime() - last_read_timestamp_;
-}
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/advertisement_read_result.h b/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/advertisement_read_result.h
deleted file mode 100644
index afd8bb848e8..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/advertisement_read_result.h
+++ /dev/null
@@ -1,104 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_MEDIUMS_BLE_V2_ADVERTISEMENT_READ_RESULT_H_
-#define CORE_INTERNAL_MEDIUMS_BLE_V2_ADVERTISEMENT_READ_RESULT_H_
-
-#include <cstdint>
-#include <vector>
-
-#include "absl/container/flat_hash_map.h"
-#include "absl/container/flat_hash_set.h"
-#include "absl/time/clock.h"
-#include "platform/base/byte_array.h"
-#include "platform/public/mutex.h"
-#include "platform/public/system_clock.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-// Representation of a GATT advertisement read result. This object helps us
-// determine whether or not we need to retry GATT reads.
-class AdvertisementReadResult {
- public:
- // We need a long enough duration such that we always trigger a read
- // retry AND we always connect to it without delay. The former case
- // helps us initialize an AdvertisementReadResult so that we
- // unconditionally try reading on the first sighting. And the latter
- // case helps us connect immediately when we initialize a dummy read
- // result for fast advertisements (which don't use the GATT server).
-
- struct Config {
- // How much to multiply the backoff duration by with every failure to read
- // from the advertisement GATT server. This should never be below 1!
- float backoff_multiplier;
- // The initial backoff duration when we fail to read from an advertisement
- // GATT server.
- absl::Duration base_backoff_duration;
- // The maximum backoff duration allowed between advertisement GATT server
- // reads.
- absl::Duration max_backoff_duration;
- };
-
- static const Config kDefaultConfig;
- explicit AdvertisementReadResult(const Config& config = kDefaultConfig)
- : config_(config) {}
- ~AdvertisementReadResult() = default;
-
- enum class RetryStatus {
- kUnknown = 0,
- kRetry = 1,
- kPreviouslySucceeded = 2,
- kTooSoon = 3,
- };
-
- void AddAdvertisement(std::int32_t slot, const ByteArray& advertisement)
- ABSL_LOCKS_EXCLUDED(mutex_);
- bool HasAdvertisement(std::int32_t slot) const ABSL_LOCKS_EXCLUDED(mutex_);
- std::vector<const ByteArray*> GetAdvertisements() const
- ABSL_LOCKS_EXCLUDED(mutex_);
- RetryStatus EvaluateRetryStatus() const ABSL_LOCKS_EXCLUDED(mutex_);
- void RecordLastReadStatus(bool is_success) ABSL_LOCKS_EXCLUDED(mutex_);
- absl::Duration GetDurationSinceRead() const ABSL_LOCKS_EXCLUDED(mutex_);
-
- private:
- enum class Status {
- kUnknown = 0,
- kSuccess = 1,
- kFailure = 2,
- };
-
- absl::Duration GetDurationSinceReadLocked() const
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- mutable Mutex mutex_;
-
- // Maps slot numbers to the GATT advertisement found in that slot.
- absl::flat_hash_map<std::int32_t, ByteArray> advertisements_
- ABSL_GUARDED_BY(mutex_);
-
- Config config_;
- absl::Duration backoff_duration_ ABSL_GUARDED_BY(mutex_);
- absl::Time last_read_timestamp_ ABSL_GUARDED_BY(mutex_);
- Status status_ ABSL_GUARDED_BY(mutex_) = Status::kUnknown;
-};
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_MEDIUMS_BLE_V2_ADVERTISEMENT_READ_RESULT_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/advertisement_read_result_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/advertisement_read_result_test.cc
deleted file mode 100644
index 90ce51c9a74..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/advertisement_read_result_test.cc
+++ /dev/null
@@ -1,143 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/ble_v2/advertisement_read_result.h"
-
-#include "gtest/gtest.h"
-#include "absl/time/clock.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-namespace {
-
-constexpr char kAdvertisementBytes[] = "\x0A\x0B\x0C";
-
-// Default values may be too big and impractical to wait for in the test.
-// For the test platform, we redefine them to some reasonable values.
-const absl::Duration kAdvertisementBaseBackoffDuration = absl::Seconds(1);
-const absl::Duration kAdvertisementMaxBackoffDuration = absl::Seconds(6);
-
-const AdvertisementReadResult::Config test_config{
- .backoff_multiplier =
- AdvertisementReadResult::kDefaultConfig.backoff_multiplier,
- .base_backoff_duration = kAdvertisementBaseBackoffDuration,
- .max_backoff_duration = kAdvertisementMaxBackoffDuration,
-};
-
-TEST(AdvertisementReadResultTest, AdvertisementExists) {
- AdvertisementReadResult advertisement_read_result(test_config);
- advertisement_read_result.RecordLastReadStatus(/* is_success= */ true);
-
- std::int32_t slot = 6;
- advertisement_read_result.AddAdvertisement(slot,
- ByteArray(kAdvertisementBytes));
-
- EXPECT_TRUE(advertisement_read_result.HasAdvertisement(slot));
-}
-
-TEST(AdvertisementReadResultTest, AdvertisementNonExistent) {
- AdvertisementReadResult advertisement_read_result(test_config);
- advertisement_read_result.RecordLastReadStatus(/* is_success= */ true);
-
- std::int32_t slot = 6;
-
- EXPECT_FALSE(advertisement_read_result.HasAdvertisement(slot));
-}
-
-TEST(AdvertisementReadResultTest, EvaluateRetryStatusInitialized) {
- AdvertisementReadResult advertisement_read_result(test_config);
-
- EXPECT_EQ(advertisement_read_result.EvaluateRetryStatus(),
- AdvertisementReadResult::RetryStatus::kRetry);
-}
-
-TEST(AdvertisementReadResultTest, EvaluateRetryStatusSuccess) {
- AdvertisementReadResult advertisement_read_result(test_config);
- advertisement_read_result.RecordLastReadStatus(/* is_success= */ true);
-
- EXPECT_EQ(advertisement_read_result.EvaluateRetryStatus(),
- AdvertisementReadResult::RetryStatus::kPreviouslySucceeded);
-}
-
-TEST(AdvertisementReadResultTest, EvaluateRetryStatusTooSoon) {
- AdvertisementReadResult advertisement_read_result(test_config);
- advertisement_read_result.RecordLastReadStatus(/* is_success= */ false);
-
- // Sleep for some time, but not long enough to warrant a retry.
- absl::SleepFor(kAdvertisementBaseBackoffDuration / 2);
-
- EXPECT_EQ(advertisement_read_result.EvaluateRetryStatus(),
- AdvertisementReadResult::RetryStatus::kTooSoon);
-}
-
-TEST(AdvertisementReadResultTest, EvaluateRetryStatusRetry) {
- AdvertisementReadResult advertisement_read_result(test_config);
- advertisement_read_result.RecordLastReadStatus(/* is_success= */ false);
-
- // Sleep long enough to warrant a retry.
- absl::SleepFor(kAdvertisementBaseBackoffDuration);
-
- EXPECT_EQ(advertisement_read_result.EvaluateRetryStatus(),
- AdvertisementReadResult::RetryStatus::kRetry);
-}
-
-TEST(AdvertisementReadResultTest, ReportStatusExponentialBackoff) {
- AdvertisementReadResult advertisement_read_result(test_config);
- advertisement_read_result.RecordLastReadStatus(/* is_success= */ false);
-
- // Record an additional failure so our backoff duration increases.
- advertisement_read_result.RecordLastReadStatus(/* is_success= */ false);
-
- // Sleep for the backoff duration. We shouldn't trigger a retry because the
- // backoff should have increased from failing a second time.
- absl::SleepFor(kAdvertisementBaseBackoffDuration);
-
- EXPECT_EQ(advertisement_read_result.EvaluateRetryStatus(),
- AdvertisementReadResult::RetryStatus::kTooSoon);
-}
-
-TEST(AdvertisementReadResultTest, ReportStatusExponentialBackoffMax) {
- AdvertisementReadResult advertisement_read_result(test_config);
- advertisement_read_result.RecordLastReadStatus(/* is_success= */ false);
-
- // Record an absurd amount of failures so we hit the maximum backoff duration.
- for (std::int32_t i = 0; i < 1000; i++) {
- advertisement_read_result.RecordLastReadStatus(/* is_success= */ false);
- }
-
- // Sleep for the maximum backoff duration. This should be enough to warrant a
- // retry.
- absl::SleepFor(kAdvertisementMaxBackoffDuration);
-
- EXPECT_EQ(advertisement_read_result.EvaluateRetryStatus(),
- AdvertisementReadResult::RetryStatus::kRetry);
-}
-
-TEST(AdvertisementReadResultTest, GetDurationSinceRead) {
- AdvertisementReadResult advertisement_read_result(test_config);
- advertisement_read_result.RecordLastReadStatus(/* is_success= */ true);
-
- absl::Duration sleepTime = absl::Milliseconds(420);
- absl::SleepFor(sleepTime);
-
- EXPECT_GE(advertisement_read_result.GetDurationSinceRead(), sleepTime);
-}
-
-} // namespace
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_advertisement.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_advertisement.cc
deleted file mode 100644
index f6280611954..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_advertisement.cc
+++ /dev/null
@@ -1,245 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/ble_v2/ble_advertisement.h"
-
-#include <inttypes.h>
-
-#include "absl/strings/str_cat.h"
-#include "platform/base/base_input_stream.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-BleAdvertisement::BleAdvertisement(Version version,
- SocketVersion socket_version,
- const ByteArray &service_id_hash,
- const ByteArray &data,
- const ByteArray &device_token) {
- DoInitialize(/*fast_advertisement=*/service_id_hash.Empty(), version,
- socket_version, service_id_hash, data, device_token);
-}
-
-void BleAdvertisement::DoInitialize(bool fast_advertisement, Version version,
- SocketVersion socket_version,
- const ByteArray &service_id_hash,
- const ByteArray &data,
- const ByteArray &device_token) {
- // Check that the given input is valid.
- fast_advertisement_ = fast_advertisement;
- if (!fast_advertisement_) {
- if (service_id_hash.size() != kServiceIdHashLength) return;
- }
- if (!IsSupportedVersion(version) ||
- !IsSupportedSocketVersion(socket_version) ||
- (!device_token.Empty() && device_token.size() != kDeviceTokenLength)) {
- return;
- }
-
- int advertisement_Length = ComputeAdvertisementLength(
- data.size(), device_token.size(), fast_advertisement_);
- int max_advertisement_length = fast_advertisement
- ? kMaxFastAdvertisementLength
- : kMaxAdvertisementLength;
- if (advertisement_Length > max_advertisement_length) {
- return;
- }
-
- version_ = version;
- socket_version_ = socket_version;
- if (!fast_advertisement_) service_id_hash_ = service_id_hash;
- data_ = data;
- device_token_ = device_token;
-}
-
-BleAdvertisement::BleAdvertisement(const ByteArray &ble_advertisement_bytes) {
- if (ble_advertisement_bytes.Empty()) {
- NEARBY_LOG(INFO,
- "Cannot deserialize BleAdvertisement: null bytes passed in.");
- return;
- }
-
- if (ble_advertisement_bytes.size() < kVersionLength) {
- NEARBY_LOG(
- INFO,
- "Cannot deserialize BleAdvertisement: expecting min %d raw bytes to "
- "parse the version, got %" PRIu64,
- kVersionLength, ble_advertisement_bytes.size());
- return;
- }
-
- ByteArray advertisement_bytes{ble_advertisement_bytes};
- BaseInputStream base_input_stream{advertisement_bytes};
- // The first 1 byte is supposed to be the version, socket version and the fast
- // advertisement flag.
- auto version_byte = static_cast<char>(base_input_stream.ReadUint8());
-
- // Version.
- version_ = static_cast<Version>((version_byte & kVersionBitmask) >> 5);
- if (!IsSupportedVersion(version_)) {
- NEARBY_LOG(INFO,
- "Cannot deserialize BleAdvertisement: unsupported Version %u",
- version_);
- return;
- }
-
- // Socket version.
- socket_version_ =
- static_cast<SocketVersion>((version_byte & kSocketVersionBitmask) >> 2);
- if (!IsSupportedSocketVersion(socket_version_)) {
- NEARBY_LOG(
- INFO,
- "Cannot deserialize BleAdvertisement: unsupported SocketVersion %u",
- socket_version_);
- version_ = Version::kUndefined;
- return;
- }
-
- // Fast advertisement flag.
- fast_advertisement_ =
- static_cast<bool>((version_byte & kFastAdvertisementFlagBitmask) >> 1);
-
- // The next 3 bytes are supposed to be the service_id_hash if not fast
- // advertisement.
- if (!fast_advertisement_) {
- service_id_hash_ = base_input_stream.ReadBytes(kServiceIdHashLength);
- }
-
- // Data length.
- int expected_data_size =
- fast_advertisement_
- ? static_cast<int>(
- base_input_stream.ReadBytes(kFastDataSizeLength).data()[0])
- : static_cast<int>(base_input_stream.ReadUint32());
- if (expected_data_size < 0) {
- NEARBY_LOG(INFO,
- "Cannot deserialize BleAdvertisement: negative data size %d",
- expected_data_size);
- version_ = Version::kUndefined;
- return;
- }
-
- // Data.
- // Check that the stated data size is the same as what we received.
- data_ = base_input_stream.ReadBytes(expected_data_size);
- if (data_.size() != expected_data_size) {
- NEARBY_LOG(INFO,
- "Cannot deserialize BleAdvertisement: expected data to be %u "
- "bytes, got %" PRIu64 " bytes ",
- expected_data_size, data_.size());
- version_ = Version::kUndefined;
- return;
- }
-
- // Device token. If the number of remaining bytes are valid for device token,
- // then read it.
- if (base_input_stream.IsAvailable(kDeviceTokenLength)) {
- device_token_ = base_input_stream.ReadBytes(kDeviceTokenLength);
- }
-}
-
-BleAdvertisement::operator ByteArray() const {
- if (!IsValid()) {
- return ByteArray{};
- }
-
- // The first 3 bits are the Version.
- char version_byte = (static_cast<char>(version_) << 5) & kVersionBitmask;
- // The next 3 bits are the Socket version. 2 bits left are reserved.
- version_byte |=
- (static_cast<char>(socket_version_) << 2) & kSocketVersionBitmask;
- // The next 1 bit is the fast advertisement flag. 1 bit left is reserved.
- version_byte |= (static_cast<char>(fast_advertisement_ ? 1 : 0) << 1) &
- kFastAdvertisementFlagBitmask;
-
- // Serialize Data size bytes
- ByteArray data_size_bytes{static_cast<size_t>(
- fast_advertisement_ ? kFastDataSizeLength : kDataSizeLength)};
- auto *data_size_bytes_write_ptr = data_size_bytes.data();
- SerializeDataSize(fast_advertisement_, data_size_bytes_write_ptr,
- data_.size());
-
- // clang-format on
- if (fast_advertisement_) {
- std::string out =
- absl::StrCat(std::string(1, version_byte), std::string(data_size_bytes),
- std::string(data_), std::string(device_token_));
- return ByteArray{std::move(out)};
- } else {
- std::string out = absl::StrCat(
- std::string(1, version_byte), std::string(service_id_hash_),
- std::string(data_size_bytes), std::string(data_),
- std::string(device_token_));
- return ByteArray{std::move(out)};
- }
- // clang-format on
-}
-
-bool BleAdvertisement::operator==(const BleAdvertisement &rhs) const {
- return this->GetVersion() == rhs.GetVersion() &&
- this->GetSocketVersion() == rhs.GetSocketVersion() &&
- this->GetServiceIdHash() == rhs.GetServiceIdHash() &&
- this->GetData() == rhs.GetData() &&
- this->GetDeviceToken() == rhs.GetDeviceToken();
-}
-
-bool BleAdvertisement::operator<(const BleAdvertisement &rhs) const {
- if (this->GetVersion() != rhs.GetVersion()) {
- return this->GetVersion() < rhs.GetVersion();
- }
- if (this->GetSocketVersion() != rhs.GetSocketVersion()) {
- return this->GetSocketVersion() < rhs.GetSocketVersion();
- }
- if (this->GetServiceIdHash() != rhs.GetServiceIdHash()) {
- return this->GetServiceIdHash() < rhs.GetServiceIdHash();
- }
- if (this->GetDeviceToken() != rhs.GetDeviceToken()) {
- return this->GetDeviceToken() < rhs.GetDeviceToken();
- }
- return this->GetData() < rhs.GetData();
-}
-
-bool BleAdvertisement::IsSupportedVersion(Version version) const {
- return version >= Version::kV1 && version <= Version::kV2;
-}
-
-bool BleAdvertisement::IsSupportedSocketVersion(
- SocketVersion socket_version) const {
- return socket_version >= SocketVersion::kV1 &&
- socket_version <= SocketVersion::kV2;
-}
-
-void BleAdvertisement::SerializeDataSize(bool fast_advertisement,
- char *data_size_bytes_write_ptr,
- size_t data_size) const {
- // Get a raw representation of the data size bytes in memory.
- char *data_size_bytes = reinterpret_cast<char *>(&data_size);
-
- const int data_size_length =
- fast_advertisement ? kFastDataSizeLength : kDataSizeLength;
-
- // Append these raw bytes to advertisement bytes, keeping in mind that we need
- // to convert from Little Endian to Big Endian in the process.
- for (int i = 0; i < data_size_length; ++i) {
- data_size_bytes_write_ptr[i] = data_size_bytes[data_size_length - i - 1];
- }
-}
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_advertisement.h b/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_advertisement.h
deleted file mode 100644
index 176f4bfd7b0..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_advertisement.h
+++ /dev/null
@@ -1,139 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_MEDIUMS_BLE_V2_BLE_ADVERTISEMENT_H_
-#define CORE_INTERNAL_MEDIUMS_BLE_V2_BLE_ADVERTISEMENT_H_
-
-#include <utility>
-
-#include "platform/base/byte_array.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-// Represents the format of the Mediums BLE Advertisement used in Advertising +
-// Discovery.
-//
-// [VERSION][SOCKET_VERSION][FAST_ADVERTISEMENT_FLAG][1_RESERVED_BIT][SERVICE_ID_HASH][DATA_SIZE][DATA][DEVICE_TOKEN]
-//
-// For fast advertisement, we remove SERVICE_ID_HASH since we already have one
-// copy in Nearby Connections(b/138447288)
-// [VERSION][SOCKET_VERSION][FAST_ADVERTISEMENT_FLAG][1_RESERVED_BIT][DATA_SIZE][DATA][DEVICE_TOKEN]
-//
-// See go/nearby-ble-design for more information.
-class BleAdvertisement {
- public:
- // Versions of the BleAdvertisement.
- enum class Version {
- kUndefined = 0,
- kV1 = 1,
- kV2 = 2,
- // Version is only allocated 3 bits in the BleAdvertisement, so this can
- // never go beyond V7.
- };
-
- // Versions of the BLESocket.
- enum class SocketVersion {
- kUndefined = 0,
- kV1 = 1,
- kV2 = 2,
- // SocketVersion is only allocated 3 bits in the BleAdvertisement, so this
- // can never go beyond V7.
- };
-
- static constexpr int kServiceIdHashLength = 3;
- static constexpr int kDeviceTokenLength = 2;
-
- BleAdvertisement() = default;
- BleAdvertisement(Version version, SocketVersion socket_version,
- const ByteArray &service_id_hash, const ByteArray &data,
- const ByteArray &device_token);
- explicit BleAdvertisement(const ByteArray &ble_advertisement_bytes);
- BleAdvertisement(const BleAdvertisement &) = default;
- BleAdvertisement &operator=(const BleAdvertisement &) = default;
- BleAdvertisement(BleAdvertisement &&) = default;
- BleAdvertisement &operator=(BleAdvertisement &&) = default;
- ~BleAdvertisement() = default;
-
- explicit operator ByteArray() const;
- // Operator overloads when comparing BleAdvertisement.
- bool operator==(const BleAdvertisement &rhs) const;
- bool operator<(const BleAdvertisement &rhs) const;
-
- bool IsValid() const { return IsSupportedVersion(version_); }
- Version GetVersion() const { return version_; }
- SocketVersion GetSocketVersion() const { return socket_version_; }
- bool IsFastAdvertisement() const { return fast_advertisement_; }
- ByteArray GetServiceIdHash() const { return service_id_hash_; }
- ByteArray &GetData() & { return data_; }
- const ByteArray &GetData() const & { return data_; }
- ByteArray &&GetData() && { return std::move(data_); }
- const ByteArray &&GetData() const && { return std::move(data_); }
- ByteArray GetDeviceToken() const { return device_token_; }
-
- private:
- void DoInitialize(bool fast_advertisement, Version version,
- SocketVersion socket_version,
- const ByteArray &service_id_hash, const ByteArray &data,
- const ByteArray &device_token);
- bool IsSupportedVersion(Version version) const;
- bool IsSupportedSocketVersion(SocketVersion socket_version) const;
- void SerializeDataSize(bool fast_advertisement,
- char *data_size_bytes_write_ptr,
- size_t data_size) const;
- int ComputeAdvertisementLength(int data_length, int total_optional_length,
- bool fast_advertisement) const {
- // The advertisement length is the minimum length + the length of the data +
- // the length of in-use optional fields.
- return fast_advertisement ? (kMinFastAdvertisementLegth + data_length +
- total_optional_length)
- : (kMinAdvertisementLength + data_length +
- total_optional_length);
- }
-
- static constexpr int kVersionLength = 1;
- static constexpr int kVersionBitmask = 0x0E0;
- static constexpr int kSocketVersionBitmask = 0x01C;
- static constexpr int kFastAdvertisementFlagBitmask = 0x002;
- static constexpr int kDataSizeLength = 4; // Length of one int.
- static constexpr int kFastDataSizeLength = 1; // Length of one byte.
- static constexpr int kMinAdvertisementLength =
- kVersionLength + kServiceIdHashLength + kDataSizeLength;
- // The maximum length for a Gatt characteristic value is 512 bytes, so make
- // sure the entire advertisement is less than that. The data can take up
- // whatever space is remaining after the bytes preceding it.
- static constexpr int kMaxAdvertisementLength = 512;
- static constexpr int kMinFastAdvertisementLegth =
- kVersionLength + kFastDataSizeLength;
- // The maximum length for the scan response is 31 bytes. However, with the
- // required header that comes before the service data, this leaves the
- // advertiser with 27 leftover bytes.
- static constexpr int kMaxFastAdvertisementLength = 27;
-
- Version version_{Version::kUndefined};
- SocketVersion socket_version_{SocketVersion::kUndefined};
- bool fast_advertisement_ = false;
- ByteArray service_id_hash_;
- ByteArray data_;
- ByteArray device_token_;
-};
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_MEDIUMS_BLE_V2_BLE_ADVERTISEMENT_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_advertisement_header.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_advertisement_header.cc
deleted file mode 100644
index 321924e4f90..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_advertisement_header.cc
+++ /dev/null
@@ -1,131 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/ble_v2/ble_advertisement_header.h"
-
-#include <inttypes.h>
-
-#include "absl/strings/str_cat.h"
-#include "platform/base/base64_utils.h"
-#include "platform/base/base_input_stream.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-BleAdvertisementHeader::BleAdvertisementHeader(
- Version version, int num_slots, const ByteArray &service_id_bloom_filter,
- const ByteArray &advertisement_hash) {
- if (version != Version::kV2 || num_slots <= 0 ||
- service_id_bloom_filter.size() != kServiceIdBloomFilterLength ||
- advertisement_hash.size() != kAdvertisementHashLength) {
- return;
- }
-
- version_ = version;
- num_slots_ = num_slots;
- service_id_bloom_filter_ = service_id_bloom_filter;
- advertisement_hash_ = advertisement_hash;
-}
-
-BleAdvertisementHeader::BleAdvertisementHeader(
- const std::string &ble_advertisement_header_string) {
- ByteArray ble_advertisement_header_bytes =
- Base64Utils::Decode(ble_advertisement_header_string);
-
- if (ble_advertisement_header_bytes.Empty()) {
- NEARBY_LOG(
- ERROR,
- "Cannot deserialize BLEAdvertisementHeader: failed Base64 decoding");
- return;
- }
-
- if (ble_advertisement_header_bytes.size() < kMinAdvertisementHeaderLength) {
- NEARBY_LOG(ERROR,
- "Cannot deserialize BleAdvertisementHeader: expecting min %u "
- "raw bytes, got %" PRIu64 " instead",
- kMinAdvertisementHeaderLength,
- ble_advertisement_header_bytes.size());
- return;
- }
-
- BaseInputStream base_input_stream{ble_advertisement_header_bytes};
- // The first 1 byte is supposed to be the version and number of slots.
- auto version_and_pcp_byte = static_cast<char>(base_input_stream.ReadUint8());
- // The upper 3 bits are supposed to be the version.
- version_ =
- static_cast<Version>((version_and_pcp_byte & kVersionBitmask) >> 5);
- if (version_ != Version::kV2) {
- NEARBY_LOG(
- ERROR,
- "Cannot deserialize BleAdvertisementHeader: unsupported Version %d",
- version_);
- return;
- }
- // The lower 5 bits are supposed to be the number of slots.
- num_slots_ = static_cast<int>(version_and_pcp_byte & kNumSlotsBitmask);
- if (num_slots_ <= 0) {
- version_ = Version::kUndefined;
- return;
- }
-
- // The next 10 bytes are supposed to be the service_id_bloom_filter.
- service_id_bloom_filter_ =
- base_input_stream.ReadBytes(kServiceIdBloomFilterLength);
-
- // The next 4 bytes are supposed to be the advertisement_hash.
- advertisement_hash_ = base_input_stream.ReadBytes(kAdvertisementHashLength);
-}
-
-BleAdvertisementHeader::operator std::string() const {
- if (!IsValid()) {
- return "";
- }
-
- // The first 3 bits are the Version.
- char version_and_num_slots_byte =
- (static_cast<char>(version_) << 5) & kVersionBitmask;
- // The next 5 bits are the number of slots.
- version_and_num_slots_byte |=
- static_cast<char>(num_slots_) & kNumSlotsBitmask;
-
- // clang-format off
- std::string out = absl::StrCat(std::string(1, version_and_num_slots_byte),
- std::string(service_id_bloom_filter_),
- std::string(advertisement_hash_));
- // clang-format on
-
- return Base64Utils::Encode(ByteArray(std::move(out)));
-}
-
-bool BleAdvertisementHeader::operator<(
- const BleAdvertisementHeader &rhs) const {
- if (this->GetVersion() != rhs.GetVersion()) {
- return this->GetVersion() < rhs.GetVersion();
- }
- if (this->GetNumSlots() != rhs.GetNumSlots()) {
- return this->GetNumSlots() < rhs.GetNumSlots();
- }
- if (this->GetServiceIdBloomFilter() != rhs.GetServiceIdBloomFilter()) {
- return this->GetServiceIdBloomFilter() < rhs.GetServiceIdBloomFilter();
- }
- return this->GetAdvertisementHash() < rhs.GetAdvertisementHash();
-}
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_advertisement_header.h b/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_advertisement_header.h
deleted file mode 100644
index fbf0d457599..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_advertisement_header.h
+++ /dev/null
@@ -1,97 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_MEDIUMS_BLE_V2_BLE_ADVERTISEMENT_HEADER_H_
-#define CORE_INTERNAL_MEDIUMS_BLE_V2_BLE_ADVERTISEMENT_HEADER_H_
-
-#include <string>
-
-#include "platform/base/byte_array.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-// Represents the format of the Mediums BLE Advertisement Header used in
-// Advertising + Discovery.
-//
-// [VERSION][NUM_SLOTS][SERVICE_ID_BLOOM_FILTER][ADVERTISEMENT_HASH]
-//
-// See go/nearby-ble-design for more information.
-//
-// Note. The object constructed by default constructor or the parameterized
-// constructor with invalid value(s) is treated as invalid instance. Caller
-// should be responsible to call IsValid() to check the instance is invalid in
-// advance before continue on.
-class BleAdvertisementHeader {
- public:
- // Versions of the BleAdvertisementHeader.
- enum class Version {
- kUndefined = 0,
- kV1 = 1,
- kV2 = 2,
- // Version is only allocated 3 bits in the BleAdvertisementHeader, so this
- // can never go beyond V7.
- //
- // V1 is not present because it's an old format used in Nearby Connections
- // before this logic was pushed down into Nearby Mediums. V1 put
- // everything in the service data, while V2 puts the data inside a GATT
- // characteristic so the two are not compatible.
- };
-
- BleAdvertisementHeader() = default;
- BleAdvertisementHeader(Version version, int num_slots,
- const ByteArray &service_id_bloom_filter,
- const ByteArray &advertisement_hash);
- explicit BleAdvertisementHeader(
- const std::string &ble_advertisement_header_string);
- BleAdvertisementHeader(const BleAdvertisementHeader &) = default;
- BleAdvertisementHeader &operator=(const BleAdvertisementHeader &) = default;
- BleAdvertisementHeader(BleAdvertisementHeader &&) = default;
- BleAdvertisementHeader &operator=(BleAdvertisementHeader &&) = default;
- ~BleAdvertisementHeader() = default;
-
- // Produces an encoded binary string which can be decoded by the explicit
- // constructor. The returned string is empty if BleAdvertisementHeader is not
- // valid - false on IsValid().
- explicit operator std::string() const;
- bool operator<(const BleAdvertisementHeader &rhs) const;
-
- bool IsValid() const { return version_ == Version::kV2; }
- Version GetVersion() const { return version_; }
- int GetNumSlots() const { return num_slots_; }
- ByteArray GetServiceIdBloomFilter() const { return service_id_bloom_filter_; }
- ByteArray GetAdvertisementHash() const { return advertisement_hash_; }
-
- private:
- static constexpr int kServiceIdBloomFilterLength = 10;
- static constexpr int kAdvertisementHashLength = 4;
- static constexpr int kMinAdvertisementHeaderLength =
- 1 + kServiceIdBloomFilterLength + kAdvertisementHashLength;
- static constexpr int kVersionBitmask = 0x0E0;
- static constexpr int kNumSlotsBitmask = 0x01F;
-
- Version version_ = Version::kUndefined;
- int num_slots_;
- ByteArray service_id_bloom_filter_;
- ByteArray advertisement_hash_;
-};
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_MEDIUMS_BLE_V2_BLE_ADVERTISEMENT_HEADER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_advertisement_header_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_advertisement_header_test.cc
deleted file mode 100644
index bfd9bb991aa..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_advertisement_header_test.cc
+++ /dev/null
@@ -1,202 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/ble_v2/ble_advertisement_header.h"
-
-#include "gtest/gtest.h"
-#include "platform/base/base64_utils.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-namespace {
-
-constexpr BleAdvertisementHeader::Version kVersion =
- BleAdvertisementHeader::Version::kV2;
-constexpr int kNumSlots = 2;
-constexpr absl::string_view kServiceIDBloomFilter{
- "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a"};
-constexpr absl::string_view kAdvertisementHash{"\x0a\x0b\x0c\x0d"};
-
-TEST(BleAdvertisementHeaderTest, ConstructionWorks) {
- ByteArray service_id_bloom_filter{std::string(kServiceIDBloomFilter)};
- ByteArray advertisement_hash{std::string(kAdvertisementHash)};
-
- BleAdvertisementHeader ble_advertisement_header{
- kVersion, kNumSlots, service_id_bloom_filter, advertisement_hash};
-
- EXPECT_TRUE(ble_advertisement_header.IsValid());
- EXPECT_EQ(kVersion, ble_advertisement_header.GetVersion());
- EXPECT_EQ(kNumSlots, ble_advertisement_header.GetNumSlots());
- EXPECT_EQ(service_id_bloom_filter,
- ble_advertisement_header.GetServiceIdBloomFilter());
- EXPECT_EQ(advertisement_hash,
- ble_advertisement_header.GetAdvertisementHash());
-}
-
-TEST(BleAdvertisementHeaderTest, ConstructionFailsWithBadVersion) {
- auto bad_version = static_cast<BleAdvertisementHeader::Version>(666);
-
- ByteArray service_id_bloom_filter{std::string(kServiceIDBloomFilter)};
- ByteArray advertisement_hash{std::string(kAdvertisementHash)};
-
- BleAdvertisementHeader ble_advertisement_header{
- bad_version, kNumSlots, service_id_bloom_filter, advertisement_hash};
-
- EXPECT_FALSE(ble_advertisement_header.IsValid());
-}
-
-TEST(BleAdvertisementHeaderTest, ConstructionFailsWitZeroNumSlot) {
- int num_slot = 0;
-
- ByteArray service_id_bloom_filter{std::string(kServiceIDBloomFilter)};
- ByteArray advertisement_hash{std::string(kAdvertisementHash)};
-
- BleAdvertisementHeader ble_advertisement_header{
- kVersion, num_slot, service_id_bloom_filter, advertisement_hash};
-
- EXPECT_FALSE(ble_advertisement_header.IsValid());
-}
-
-TEST(BleAdvertisementHeaderTest,
- ConstructionFailsWithShortServiceIdBloomFilter) {
- char short_service_id_bloom_filter[] = "\x01\x02\x03\x04\x05\x06\x07\x08\x09";
-
- ByteArray short_service_id_bloom_filter_bytes{short_service_id_bloom_filter};
- ByteArray advertisement_hash{std::string(kAdvertisementHash)};
-
- BleAdvertisementHeader ble_advertisement_header{
- kVersion, kNumSlots, short_service_id_bloom_filter_bytes,
- advertisement_hash};
-
- EXPECT_FALSE(ble_advertisement_header.IsValid());
-}
-
-TEST(BleAdvertisementHeaderTest,
- ConstructionFailsWithLongServiceIdBloomFilter) {
- char long_service_id_bloom_filter[] =
- "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b";
-
- ByteArray service_id_bloom_filter{long_service_id_bloom_filter};
- ByteArray advertisement_hash{std::string(kAdvertisementHash)};
-
- BleAdvertisementHeader ble_advertisement_header{
- kVersion, kNumSlots, service_id_bloom_filter, advertisement_hash};
-
- EXPECT_FALSE(ble_advertisement_header.IsValid());
-}
-
-TEST(BleAdvertisementHeaderTest, ConstructionFailsWithShortAdvertisementHash) {
- char short_advertisement_hash[] = "\x0a\x0b\x0c";
-
- ByteArray service_id_bloom_filter{std::string(kServiceIDBloomFilter)};
- ByteArray advertisement_hash{short_advertisement_hash};
-
- BleAdvertisementHeader ble_advertisement_header{
- kVersion, kNumSlots, service_id_bloom_filter, advertisement_hash};
-
- EXPECT_FALSE(ble_advertisement_header.IsValid());
-}
-
-TEST(BleAdvertisementHeaderTest, ConstructionFailsWithLongAdvertisementHash) {
- char long_advertisement_hash[] = "\x0a\x0b\x0c\x0d\x0e";
-
- ByteArray service_id_bloom_filter{std::string(kServiceIDBloomFilter)};
- ByteArray advertisement_hash{long_advertisement_hash};
- BleAdvertisementHeader ble_advertisement_header{
- kVersion, kNumSlots, service_id_bloom_filter, advertisement_hash};
-
- EXPECT_FALSE(ble_advertisement_header.IsValid());
-}
-
-TEST(BleAdvertisementHeaderTest, ConstructionFromSerializedStringWorks) {
- ByteArray service_id_bloom_filter{std::string(kServiceIDBloomFilter)};
- ByteArray advertisement_hash{std::string(kAdvertisementHash)};
-
- BleAdvertisementHeader org_ble_advertisement_header{
- kVersion, kNumSlots, service_id_bloom_filter, advertisement_hash};
- auto ble_advertisement_header_string =
- std::string(org_ble_advertisement_header);
-
- BleAdvertisementHeader ble_advertisement_header{
- ble_advertisement_header_string};
-
- EXPECT_TRUE(ble_advertisement_header.IsValid());
- EXPECT_EQ(kVersion, ble_advertisement_header.GetVersion());
- EXPECT_EQ(kNumSlots, ble_advertisement_header.GetNumSlots());
- EXPECT_EQ(service_id_bloom_filter,
- ble_advertisement_header.GetServiceIdBloomFilter());
- EXPECT_EQ(advertisement_hash,
- ble_advertisement_header.GetAdvertisementHash());
-}
-
-TEST(BleAdvertisementHeaderTest, ConstructionFromExtraBytesWorks) {
- ByteArray service_id_bloom_filter{std::string(kServiceIDBloomFilter)};
- ByteArray advertisement_hash{std::string(kAdvertisementHash)};
-
- BleAdvertisementHeader ble_advertisement_header{
- kVersion, kNumSlots, service_id_bloom_filter, advertisement_hash};
- auto ble_advertisement_header_string = std::string(ble_advertisement_header);
-
- // Base64 decode the string, add a character, and then re-encode it.
- ByteArray ble_advertisement_header_bytes =
- Base64Utils::Decode(ble_advertisement_header_string);
- ByteArray long_ble_advertisement_header_bytes{
- ble_advertisement_header_bytes.size() + 1};
- long_ble_advertisement_header_bytes.CopyAt(0, ble_advertisement_header_bytes);
- std::string long_ble_advertisement_header_string{
- Base64Utils::Encode(long_ble_advertisement_header_bytes)};
-
- BleAdvertisementHeader long_ble_advertisement_header{
- long_ble_advertisement_header_string};
-
- EXPECT_TRUE(long_ble_advertisement_header.IsValid());
- EXPECT_EQ(kVersion, long_ble_advertisement_header.GetVersion());
- EXPECT_EQ(kNumSlots, long_ble_advertisement_header.GetNumSlots());
- EXPECT_EQ(service_id_bloom_filter,
- long_ble_advertisement_header.GetServiceIdBloomFilter());
- EXPECT_EQ(advertisement_hash,
- long_ble_advertisement_header.GetAdvertisementHash());
-}
-
-TEST(BleAdvertisementHeaderTest, ConstructionFromShortLengthFails) {
- ByteArray service_id_bloom_filter{std::string(kServiceIDBloomFilter)};
- ByteArray advertisement_hash{std::string(kAdvertisementHash)};
-
- BleAdvertisementHeader ble_advertisement_header{
- kVersion, kNumSlots, service_id_bloom_filter, advertisement_hash};
- auto ble_advertisement_header_string = std::string(ble_advertisement_header);
-
- // Base64 decode the string, remove a character, and then re-encode it.
- ByteArray ble_advertisement_header_bytes =
- Base64Utils::Decode(ble_advertisement_header_string);
- ByteArray short_ble_advertisement_header_bytes{
- ble_advertisement_header_bytes.size() - 1};
- short_ble_advertisement_header_bytes.CopyAt(0,
- ble_advertisement_header_bytes);
- std::string short_ble_advertisement_header_string{
- Base64Utils::Encode(short_ble_advertisement_header_bytes)};
-
- BleAdvertisementHeader short_ble_advertisement_header{
- short_ble_advertisement_header_string};
-
- EXPECT_FALSE(short_ble_advertisement_header.IsValid());
-}
-
-} // namespace
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_advertisement_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_advertisement_test.cc
deleted file mode 100644
index b91e8d95ca5..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_advertisement_test.cc
+++ /dev/null
@@ -1,455 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/ble_v2/ble_advertisement.h"
-
-#include <algorithm>
-
-#include "gtest/gtest.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-namespace {
-
-constexpr BleAdvertisement::Version kVersion = BleAdvertisement::Version::kV2;
-constexpr BleAdvertisement::SocketVersion kSocketVersion =
- BleAdvertisement::SocketVersion::kV2;
-constexpr absl::string_view kServiceIDHashBytes{"\x0a\x0b\x0c"};
-constexpr absl::string_view kData{
- "How much wood can a woodchuck chuck if a wood chuck would chuck wood?"};
-constexpr absl::string_view kFastData{"Fast Advertise"};
-constexpr absl::string_view kDeviceToken{"\x04\x20"};
-// kAdvertisementLength/kFastAdvertisementLength corresponds to the length of a
-// specific BleAdvertisement packed with the kData/kFastData given above. Be
-// sure to update this if kData/kFastData ever changes.
-constexpr size_t kAdvertisementLength = 77;
-constexpr size_t kFastAdvertisementLength = 16;
-constexpr size_t kLongAdvertisementLength = kAdvertisementLength + 1000;
-
-TEST(BleAdvertisementTest, ConstructionWorksV1) {
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- ByteArray data{std::string(kData)};
- ByteArray device_token{std::string(kDeviceToken)};
-
- BleAdvertisement ble_advertisement{BleAdvertisement::Version::kV1,
- BleAdvertisement::SocketVersion::kV1,
- service_id_hash, data, device_token};
-
- EXPECT_TRUE(ble_advertisement.IsValid());
- EXPECT_FALSE(ble_advertisement.IsFastAdvertisement());
- EXPECT_EQ(BleAdvertisement::Version::kV1, ble_advertisement.GetVersion());
- EXPECT_EQ(BleAdvertisement::SocketVersion::kV1,
- ble_advertisement.GetSocketVersion());
- EXPECT_EQ(service_id_hash, ble_advertisement.GetServiceIdHash());
- EXPECT_EQ(data.size(), ble_advertisement.GetData().size());
- EXPECT_EQ(data, ble_advertisement.GetData());
- EXPECT_EQ(device_token, ble_advertisement.GetDeviceToken());
-}
-
-TEST(BleAdvertisementTest, ConstructionWorksV1ForFastAdvertisement) {
- ByteArray fast_data{std::string(kFastData)};
- ByteArray device_token{std::string(kDeviceToken)};
-
- BleAdvertisement ble_advertisement{BleAdvertisement::Version::kV1,
- BleAdvertisement::SocketVersion::kV1,
- ByteArray{}, fast_data, device_token};
-
- EXPECT_TRUE(ble_advertisement.IsValid());
- EXPECT_TRUE(ble_advertisement.IsFastAdvertisement());
- EXPECT_EQ(BleAdvertisement::Version::kV1, ble_advertisement.GetVersion());
- EXPECT_EQ(BleAdvertisement::SocketVersion::kV1,
- ble_advertisement.GetSocketVersion());
- EXPECT_EQ(fast_data.size(), ble_advertisement.GetData().size());
- EXPECT_EQ(fast_data, ble_advertisement.GetData());
- EXPECT_EQ(device_token, ble_advertisement.GetDeviceToken());
-}
-
-TEST(BleAdvertisementTest, ConstructionFailsWithBadVersion) {
- BleAdvertisement::Version bad_version =
- static_cast<BleAdvertisement::Version>(666);
-
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- ByteArray data{std::string(kData)};
- ByteArray device_token{std::string(kDeviceToken)};
-
- BleAdvertisement ble_advertisement{bad_version, kSocketVersion,
- service_id_hash, data, device_token};
- EXPECT_FALSE(ble_advertisement.IsValid());
-
- BleAdvertisement fast_ble_advertisement{bad_version, kSocketVersion,
- ByteArray{}, data, device_token};
- EXPECT_FALSE(fast_ble_advertisement.IsValid());
-}
-
-TEST(BleAdvertisementTest, ConstructionFailsWithBadSocketVersion) {
- BleAdvertisement::SocketVersion bad_socket_version =
- static_cast<BleAdvertisement::SocketVersion>(666);
-
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- ByteArray data{std::string(kData)};
- ByteArray device_token{std::string(kDeviceToken)};
-
- BleAdvertisement ble_advertisement{kVersion, bad_socket_version,
- service_id_hash, data, device_token};
- EXPECT_FALSE(ble_advertisement.IsValid());
-
- BleAdvertisement fast_ble_advertisement{kVersion, bad_socket_version,
- ByteArray{}, data, device_token};
- EXPECT_FALSE(fast_ble_advertisement.IsValid());
-}
-
-TEST(BleAdvertisementTest, ConstructionFailsWithShortServiceIdHash) {
- char short_service_id_hash_bytes[] = "\x0a\x0b";
-
- ByteArray bad_service_id_hash{short_service_id_hash_bytes};
- ByteArray data{std::string(kData)};
- ByteArray device_token{std::string(kDeviceToken)};
-
- BleAdvertisement ble_advertisement{kVersion, kSocketVersion,
- bad_service_id_hash, data, device_token};
-
- EXPECT_FALSE(ble_advertisement.IsValid());
-}
-
-TEST(BleAdvertisementTest, ConstructionFailsWithLongServiceIdHash) {
- char long_service_id_hash_bytes[] = "\x0a\x0b\x0c\x0d";
-
- ByteArray bad_service_id_hash{long_service_id_hash_bytes};
- ByteArray data{std::string(kData)};
- ByteArray device_token{std::string(kDeviceToken)};
-
- BleAdvertisement ble_advertisement{kVersion, kSocketVersion,
- bad_service_id_hash, data, device_token};
-
- EXPECT_FALSE(ble_advertisement.IsValid());
-}
-
-TEST(BleAdvertisementTest, ConstructionFailsWithLongData) {
- // BleAdvertisement shouldn't be able to support data with the max GATT
- // attribute length because it needs some room for the preceding fields.
- char long_data[512]{};
-
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- ByteArray bad_data{long_data, 512};
- ByteArray device_token{std::string(kDeviceToken)};
-
- BleAdvertisement ble_advertisement{kVersion, kSocketVersion, service_id_hash,
- bad_data, device_token};
- EXPECT_FALSE(ble_advertisement.IsValid());
-
- BleAdvertisement fast_ble_advertisement{kVersion, kSocketVersion, ByteArray{},
- bad_data, device_token};
- EXPECT_FALSE(fast_ble_advertisement.IsValid());
-}
-
-TEST(BleAdvertisementTest, ConstructionWorksWithEmptyDeviceToken) {
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- ByteArray data{std::string(kData)};
-
- BleAdvertisement ble_advertisement{kVersion, kSocketVersion, service_id_hash,
- data, ByteArray{}};
-
- EXPECT_TRUE(ble_advertisement.IsValid());
- EXPECT_FALSE(ble_advertisement.IsFastAdvertisement());
- EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
- EXPECT_EQ(kSocketVersion, ble_advertisement.GetSocketVersion());
- EXPECT_EQ(service_id_hash, ble_advertisement.GetServiceIdHash());
- EXPECT_EQ(data.size(), ble_advertisement.GetData().size());
- EXPECT_EQ(data, ble_advertisement.GetData());
- EXPECT_TRUE(ble_advertisement.GetDeviceToken().Empty());
-}
-
-TEST(BleAdvertisementTest,
- ConstructionWorksWithEmptyDeviceTokenForFastAdvertisement) {
- ByteArray fast_data{std::string(kFastData)};
-
- BleAdvertisement ble_advertisement{kVersion, kSocketVersion, ByteArray{},
- fast_data, ByteArray{}};
-
- EXPECT_TRUE(ble_advertisement.IsValid());
- EXPECT_TRUE(ble_advertisement.IsFastAdvertisement());
- EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
- EXPECT_EQ(kSocketVersion, ble_advertisement.GetSocketVersion());
- EXPECT_EQ(fast_data.size(), ble_advertisement.GetData().size());
- EXPECT_EQ(fast_data, ble_advertisement.GetData());
- EXPECT_TRUE(ble_advertisement.GetDeviceToken().Empty());
-}
-
-TEST(BleAdvertisementTest, ConstructionFailsWithWrongSizeofDeviceToken) {
- char wrong_device_token_bytes_1[] = "\x04\x2\x10"; // over 2 bytes
- char wrong_device_token_bytes_2[] = "\x04"; // 1 byte
-
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- ByteArray data{std::string(kData)};
- ByteArray bad_device_token_1{wrong_device_token_bytes_1};
- ByteArray bad_device_token_2{wrong_device_token_bytes_2};
-
- BleAdvertisement ble_advertisement_1{
- kVersion, kSocketVersion, service_id_hash, data, bad_device_token_1};
- EXPECT_FALSE(ble_advertisement_1.IsValid());
-
- BleAdvertisement ble_advertisement_2{
- kVersion, kSocketVersion, service_id_hash, data, bad_device_token_2};
- EXPECT_FALSE(ble_advertisement_2.IsValid());
-
- BleAdvertisement fast_ble_advertisement_1{
- kVersion, kSocketVersion, ByteArray{}, data, bad_device_token_1};
- EXPECT_FALSE(fast_ble_advertisement_1.IsValid());
-
- BleAdvertisement fast_ble_advertisement_2{
- kVersion, kSocketVersion, ByteArray{}, data, bad_device_token_2};
- EXPECT_FALSE(fast_ble_advertisement_2.IsValid());
-}
-
-TEST(BleAdvertisementTest, ConstructionFromSerializedBytesWorks) {
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- ByteArray data{std::string(kData)};
- ByteArray device_token{std::string(kDeviceToken)};
-
- BleAdvertisement org_ble_advertisement{kVersion, kSocketVersion,
- service_id_hash, data, device_token};
-
- ByteArray ble_advertisement_bytes{org_ble_advertisement};
- BleAdvertisement ble_advertisement{ble_advertisement_bytes};
-
- EXPECT_TRUE(ble_advertisement.IsValid());
- EXPECT_FALSE(ble_advertisement.IsFastAdvertisement());
- EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
- EXPECT_EQ(kSocketVersion, ble_advertisement.GetSocketVersion());
- EXPECT_EQ(service_id_hash, ble_advertisement.GetServiceIdHash());
- EXPECT_EQ(data.size(), ble_advertisement.GetData().size());
- EXPECT_EQ(data, ble_advertisement.GetData());
- EXPECT_EQ(device_token, ble_advertisement.GetDeviceToken());
-}
-
-TEST(BleAdvertisementTest,
- ConstructionFromSerializedBytesWorksForAdvertisement) {
- ByteArray fast_data{std::string(kFastData)};
- ByteArray device_token{std::string(kDeviceToken)};
-
- BleAdvertisement org_ble_advertisement{kVersion, kSocketVersion, ByteArray{},
- fast_data, device_token};
-
- ByteArray ble_advertisement_bytes{org_ble_advertisement};
- BleAdvertisement ble_advertisement{ble_advertisement_bytes};
-
- EXPECT_TRUE(ble_advertisement.IsValid());
- EXPECT_TRUE(ble_advertisement.IsFastAdvertisement());
- EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
- EXPECT_EQ(kSocketVersion, ble_advertisement.GetSocketVersion());
- EXPECT_EQ(fast_data.size(), ble_advertisement.GetData().size());
- EXPECT_EQ(fast_data, ble_advertisement.GetData());
- EXPECT_EQ(device_token, ble_advertisement.GetDeviceToken());
-}
-
-TEST(BleAdvertisementTest, ConstructionFromSerializedBytesWithEmptyDataWorks) {
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- ByteArray device_token{std::string(kDeviceToken)};
-
- BleAdvertisement org_ble_advertisement{
- kVersion, kSocketVersion, service_id_hash, ByteArray(), device_token};
- ByteArray ble_advertisement_bytes{org_ble_advertisement};
- BleAdvertisement ble_advertisement{ble_advertisement_bytes};
-
- EXPECT_TRUE(ble_advertisement.IsValid());
- EXPECT_FALSE(ble_advertisement.IsFastAdvertisement());
- EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
- EXPECT_EQ(kSocketVersion, ble_advertisement.GetSocketVersion());
- EXPECT_EQ(service_id_hash, ble_advertisement.GetServiceIdHash());
- EXPECT_TRUE(ble_advertisement.GetData().Empty());
- EXPECT_EQ(device_token, ble_advertisement.GetDeviceToken());
-}
-
-TEST(BleAdvertisementTest,
- ConstructionFromSerializedBytesWithEmptyDataWorksForFastAdvertisement) {
- ByteArray device_token{std::string(kDeviceToken)};
-
- BleAdvertisement org_ble_advertisement{kVersion, kSocketVersion, ByteArray{},
- ByteArray(), device_token};
- ByteArray ble_advertisement_bytes{org_ble_advertisement};
- BleAdvertisement ble_advertisement{ble_advertisement_bytes};
-
- EXPECT_TRUE(ble_advertisement.IsValid());
- EXPECT_TRUE(ble_advertisement.IsFastAdvertisement());
- EXPECT_EQ(kVersion, ble_advertisement.GetVersion());
- EXPECT_EQ(kSocketVersion, ble_advertisement.GetSocketVersion());
- EXPECT_TRUE(ble_advertisement.GetData().Empty());
- EXPECT_EQ(device_token, ble_advertisement.GetDeviceToken());
-}
-
-TEST(BleAdvertisementTest, ConstructionFromExtraSerializedBytesWorks) {
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- ByteArray data{std::string(kData)};
- ByteArray device_token{std::string(kDeviceToken)};
-
- BleAdvertisement org_ble_advertisement{kVersion, kSocketVersion,
- service_id_hash, data, device_token};
- ByteArray org_ble_advertisement_bytes{org_ble_advertisement};
-
- // Copy the bytes into a new array with extra bytes. We must explicitly
- // define how long our array is because we can't use variable length arrays.
- char raw_ble_advertisement_bytes[kLongAdvertisementLength]{};
- memcpy(raw_ble_advertisement_bytes, org_ble_advertisement_bytes.data(),
- std::min(sizeof(raw_ble_advertisement_bytes),
- org_ble_advertisement_bytes.size()));
-
- // Re-parse the Ble advertisement using our extra long advertisement bytes.
- ByteArray long_ble_advertisement_bytes{raw_ble_advertisement_bytes,
- kLongAdvertisementLength};
- BleAdvertisement long_ble_advertisement{long_ble_advertisement_bytes};
-
- EXPECT_TRUE(long_ble_advertisement.IsValid());
- EXPECT_FALSE(long_ble_advertisement.IsFastAdvertisement());
- EXPECT_EQ(kVersion, long_ble_advertisement.GetVersion());
- EXPECT_EQ(kSocketVersion, long_ble_advertisement.GetSocketVersion());
- EXPECT_EQ(service_id_hash, long_ble_advertisement.GetServiceIdHash());
- EXPECT_EQ(data.size(), long_ble_advertisement.GetData().size());
- EXPECT_EQ(data, long_ble_advertisement.GetData());
- EXPECT_EQ(device_token, long_ble_advertisement.GetDeviceToken());
-}
-
-TEST(BleAdvertisementTest,
- ConstructionFromExtraSerializedBytesWorksForFastAdvertisement) {
- ByteArray fast_data{std::string(kFastData)};
- ByteArray device_token{std::string(kDeviceToken)};
-
- BleAdvertisement org_ble_advertisement{kVersion, kSocketVersion, ByteArray{},
- fast_data, device_token};
- ByteArray org_ble_advertisement_bytes{org_ble_advertisement};
-
- // Copy the bytes into a new array with extra bytes. We must explicitly
- // define how long our array is because we can't use variable length arrays.
- char raw_ble_advertisement_bytes[kLongAdvertisementLength]{};
- memcpy(raw_ble_advertisement_bytes, org_ble_advertisement_bytes.data(),
- std::min(sizeof(raw_ble_advertisement_bytes),
- org_ble_advertisement_bytes.size()));
-
- // Re-parse the Ble advertisement using our extra long advertisement bytes.
- ByteArray long_ble_advertisement_bytes{raw_ble_advertisement_bytes,
- kLongAdvertisementLength};
- BleAdvertisement long_ble_advertisement{long_ble_advertisement_bytes};
-
- EXPECT_TRUE(long_ble_advertisement.IsValid());
- EXPECT_TRUE(long_ble_advertisement.IsFastAdvertisement());
- EXPECT_EQ(kVersion, long_ble_advertisement.GetVersion());
- EXPECT_EQ(kSocketVersion, long_ble_advertisement.GetSocketVersion());
- EXPECT_EQ(fast_data.size(), long_ble_advertisement.GetData().size());
- EXPECT_EQ(fast_data, long_ble_advertisement.GetData());
- EXPECT_EQ(device_token, long_ble_advertisement.GetDeviceToken());
-}
-
-TEST(BleAdvertisementTest, ConstructionFromNullBytesFails) {
- BleAdvertisement ble_advertisement{ByteArray{}};
-
- EXPECT_FALSE(ble_advertisement.IsValid());
-}
-
-TEST(BleAdvertisementTest, ConstructionFromShortLengthSerializedBytesFails) {
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- ByteArray data{std::string(kData)};
- ByteArray device_token{std::string(kDeviceToken)};
-
- BleAdvertisement org_ble_advertisement{kVersion, kSocketVersion,
- service_id_hash, data, device_token};
- ByteArray org_ble_advertisement_bytes{org_ble_advertisement};
-
- // Cut off the advertisement so that it's too short.
- ByteArray short_ble_advertisement_bytes{org_ble_advertisement_bytes.data(),
- 7};
- BleAdvertisement short_ble_advertisement{short_ble_advertisement_bytes};
-
- EXPECT_FALSE(short_ble_advertisement.IsValid());
-}
-
-TEST(BleAdvertisementTest,
- ConstructionFromShortLengthSerializedBytesFailsForFastAdvertisement) {
- ByteArray fast_data{std::string(kFastData)};
- ByteArray device_token{std::string(kDeviceToken)};
-
- BleAdvertisement org_ble_advertisement{kVersion, kSocketVersion, ByteArray{},
- fast_data, device_token};
- ByteArray org_ble_advertisement_bytes{org_ble_advertisement};
-
- // Cut off the advertisement so that it's too short.
- ByteArray short_ble_advertisement_bytes{org_ble_advertisement_bytes.data(),
- 2};
- BleAdvertisement short_ble_advertisement{short_ble_advertisement_bytes};
-
- EXPECT_FALSE(short_ble_advertisement.IsValid());
-}
-
-TEST(BleAdvertisementTest,
- ConstructionFromSerializedBytesWithInvalidDataLengthFails) {
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- ByteArray data{std::string(kData)};
- ByteArray device_token{std::string(kDeviceToken)};
-
- BleAdvertisement org_ble_advertisement{kVersion, kSocketVersion,
- service_id_hash, data, device_token};
- ByteArray org_ble_advertisement_bytes{org_ble_advertisement};
-
- // Corrupt the DATA_SIZE bits. Start by making a raw copy of the Ble
- // advertisement bytes so we can modify it. We must explicitly define how
- // long our array is because we can't use variable length arrays.
- char raw_ble_advertisement_bytes[kAdvertisementLength];
- memcpy(raw_ble_advertisement_bytes, org_ble_advertisement_bytes.data(),
- kAdvertisementLength);
-
- // The data size field lives in indices 4-7. Corrupt it.
- memset(raw_ble_advertisement_bytes + 4, 0xFF, 4);
-
- // Try to parse the Ble advertisement using our corrupted advertisement bytes.
- ByteArray corrupted_ble_advertisement_bytes{raw_ble_advertisement_bytes,
- kAdvertisementLength};
- BleAdvertisement corrupted_ble_advertisement{
- corrupted_ble_advertisement_bytes};
-
- EXPECT_FALSE(corrupted_ble_advertisement.IsValid());
-}
-
-TEST(BleAdvertisementTest,
- ConstructionFromSerializedBytesWithInvalidDataLengthFails2) {
- ByteArray fast_data{std::string(kFastData)};
- ByteArray device_token{std::string(kDeviceToken)};
-
- BleAdvertisement org_ble_advertisement{kVersion, kSocketVersion, ByteArray{},
- fast_data, device_token};
- ByteArray org_ble_advertisement_bytes{org_ble_advertisement};
-
- // Corrupt the DATA_SIZE bits. Start by making a raw copy of the Ble
- // advertisement bytes so we can modify it. We must explicitly define how
- // long our array is because we can't use variable length arrays.
- char raw_ble_advertisement_bytes[kFastAdvertisementLength];
- memcpy(raw_ble_advertisement_bytes, org_ble_advertisement_bytes.data(),
- kFastAdvertisementLength);
-
- // The data size field lives in index 1. Corrupt it.
- memset(raw_ble_advertisement_bytes + 1, 0xFF, 1);
-
- // Try to parse the Ble advertisement using our corrupted advertisement bytes.
- ByteArray corrupted_ble_advertisement_bytes{raw_ble_advertisement_bytes,
- kFastAdvertisementLength};
- BleAdvertisement corrupted_ble_advertisement{
- corrupted_ble_advertisement_bytes};
-
- EXPECT_FALSE(corrupted_ble_advertisement.IsValid());
-}
-
-} // namespace
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_packet.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_packet.cc
deleted file mode 100644
index 17ab10e3472..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_packet.cc
+++ /dev/null
@@ -1,73 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/ble_v2/ble_packet.h"
-
-#include "absl/strings/str_cat.h"
-#include "platform/base/base_input_stream.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-BlePacket::BlePacket(const ByteArray& service_id_hash, const ByteArray& data) {
- if (service_id_hash.size() != kServiceIdHashLength ||
- data.size() > kMaxDataSize) {
- return;
- }
- service_id_hash_ = service_id_hash;
- data_ = data;
-}
-
-BlePacket::BlePacket(const ByteArray& ble_packet_bytes) {
- if (ble_packet_bytes.Empty()) {
- NEARBY_LOG(ERROR, "Cannot deserialize BlePacket: null bytes passed in");
- return;
- }
-
- if (ble_packet_bytes.size() < kServiceIdHashLength) {
- NEARBY_LOG(
- INFO,
- "Cannot deserialize BlePacket: expecting min %u raw bytes, got %zu",
- kServiceIdHashLength, ble_packet_bytes.size());
- return;
- }
-
- ByteArray packet_bytes{ble_packet_bytes};
- BaseInputStream base_input_stream{packet_bytes};
- // The first 3 bytes are supposed to be the service_id_hash.
- service_id_hash_ = base_input_stream.ReadBytes(kServiceIdHashLength);
-
- // The rest bytes are supposed to be the data.
- data_ = base_input_stream.ReadBytes(ble_packet_bytes.size() -
- kServiceIdHashLength);
-}
-
-BlePacket::operator ByteArray() const {
- if (!IsValid()) {
- return ByteArray();
- }
-
- std::string out =
- absl::StrCat(std::string(service_id_hash_), std::string(data_));
-
- return ByteArray(std::move(out));
-}
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_packet.h b/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_packet.h
deleted file mode 100644
index b559d4adda3..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_packet.h
+++ /dev/null
@@ -1,64 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_MEDIUMS_BLE_V2_BLE_PACKET_H_
-#define CORE_INTERNAL_MEDIUMS_BLE_V2_BLE_PACKET_H_
-
-#include <limits>
-
-#include "platform/base/byte_array.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-// Represents the format of data sent over Ble sockets.
-//
-// [SERVICE_ID_HASH][DATA]
-//
-// See go/nearby-ble-design for more information.
-class BlePacket {
- public:
- static const std::uint32_t kServiceIdHashLength = 3;
-
- BlePacket() = default;
- BlePacket(const ByteArray& service_id_hash, const ByteArray& data);
- explicit BlePacket(const ByteArray& ble_packet_byte);
- BlePacket(const BlePacket&) = default;
- BlePacket& operator=(const BlePacket&) = default;
- BlePacket(BlePacket&&) = default;
- BlePacket& operator=(BlePacket&&) = default;
- ~BlePacket() = default;
-
- explicit operator ByteArray() const;
-
- bool IsValid() const { return !service_id_hash_.Empty(); }
- ByteArray GetServiceIdHash() const { return service_id_hash_; }
- ByteArray GetData() const { return data_; }
-
- private:
- static const std::uint32_t kMaxDataSize =
- std::numeric_limits<int32_t>::max() - kServiceIdHashLength;
-
- ByteArray service_id_hash_;
- ByteArray data_;
-};
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_MEDIUMS_BLE_V2_BLE_PACKET_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_packet_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_packet_test.cc
deleted file mode 100644
index df52c3d6743..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_packet_test.cc
+++ /dev/null
@@ -1,111 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/ble_v2/ble_packet.h"
-
-#include "gtest/gtest.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-constexpr absl::string_view kServiceIDHash{"\x0a\x0b\x0c"};
-constexpr absl::string_view kData{"\x01\x02\x03\x04\x05"};
-
-TEST(BlePacketTest, ConstructionWorks) {
- ByteArray service_id_hash{std::string(kServiceIDHash)};
- ByteArray data{std::string(kData)};
-
- BlePacket ble_packet{service_id_hash, data};
-
- EXPECT_TRUE(ble_packet.IsValid());
- EXPECT_EQ(service_id_hash, ble_packet.GetServiceIdHash());
- EXPECT_EQ(data, ble_packet.GetData());
-}
-
-TEST(BlePacketTest, ConstructionWorksWithEmptyData) {
- char empty_data[] = "";
-
- ByteArray service_id_hash{std::string(kServiceIDHash)};
- ByteArray data{empty_data};
-
- BlePacket ble_packet{service_id_hash, data};
-
- EXPECT_TRUE(ble_packet.IsValid());
- EXPECT_EQ(service_id_hash, ble_packet.GetServiceIdHash());
- EXPECT_EQ(data, ble_packet.GetData());
-}
-
-TEST(BlePacketTest, ConstructionFailsWithShortServiceIdHash) {
- char short_service_id_hash[] = "\x0a\x0b";
-
- ByteArray service_id_hash{short_service_id_hash};
- ByteArray data{std::string(kData)};
-
- BlePacket ble_packet(service_id_hash, data);
-
- EXPECT_FALSE(ble_packet.IsValid());
-}
-
-TEST(BlePacketTest, ConstructionFailsWithLongServiceIdHash) {
- char long_service_id_hash[] = "\x0a\x0b\x0c\x0d";
-
- ByteArray service_id_hash{long_service_id_hash};
- ByteArray data{std::string(kData)};
-
- BlePacket ble_packet{service_id_hash, data};
-
- EXPECT_FALSE(ble_packet.IsValid());
-}
-
-TEST(BlePacketTest, ConstructionFromSerializedBytesWorks) {
- ByteArray service_id_hash{std::string(kServiceIDHash)};
- ByteArray data{std::string(kData)};
-
- BlePacket org_ble_packet{service_id_hash, data};
- ByteArray ble_packet_bytes{org_ble_packet};
-
- BlePacket ble_packet{ble_packet_bytes};
-
- EXPECT_TRUE(ble_packet.IsValid());
- EXPECT_EQ(service_id_hash, ble_packet.GetServiceIdHash());
- EXPECT_EQ(data, ble_packet.GetData());
-}
-
-TEST(BlePacketTest, ConstructionFromNullBytesFails) {
- BlePacket ble_packet{ByteArray{}};
-
- EXPECT_FALSE(ble_packet.IsValid());
-}
-
-TEST(BlePacketTest, ConstructionFromShortLengthDataFails) {
- ByteArray service_id_hash{std::string(kServiceIDHash)};
- ByteArray data{std::string(kData)};
-
- BlePacket org_ble_packet{service_id_hash, data};
- ByteArray org_ble_packet_bytes{org_ble_packet};
-
- // Cut off the packet so that it's too short
- ByteArray short_ble_packet_bytes{ByteArray{org_ble_packet_bytes.data(), 2}};
-
- BlePacket short_ble_packet{short_ble_packet_bytes};
-
- EXPECT_FALSE(short_ble_packet.IsValid());
-}
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_peripheral.h b/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_peripheral.h
deleted file mode 100644
index e3b51a41466..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_peripheral.h
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_MEDIUMS_BLE_V2_BLE_PERIPHERAL_H_
-#define CORE_INTERNAL_MEDIUMS_BLE_V2_BLE_PERIPHERAL_H_
-
-#include "platform/base/byte_array.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-class BlePeripheral {
- public:
- BlePeripheral() = default;
- explicit BlePeripheral(const ByteArray& id) : id_(id) {}
- BlePeripheral(const BlePeripheral&) = default;
- BlePeripheral& operator=(const BlePeripheral&) = default;
- BlePeripheral(BlePeripheral&&) = default;
- BlePeripheral& operator=(BlePeripheral&&) = default;
- ~BlePeripheral() = default;
-
- bool IsValid() const { return !id_.Empty(); }
- ByteArray GetId() const { return id_; }
-
- private:
- // A unique identifier for this peripheral. It can be the BLE advertisement it
- // was found on, or even simply the BLE MAC address.
- ByteArray id_;
-};
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_MEDIUMS_BLE_V2_BLE_PERIPHERAL_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_peripheral_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_peripheral_test.cc
deleted file mode 100644
index c0a4ecb0899..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/ble_peripheral_test.cc
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/ble_v2/ble_peripheral.h"
-
-#include "gtest/gtest.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-namespace {
-
-constexpr absl::string_view kId{"AB12"};
-
-TEST(BlePeripheralTest, ConstructionWorks) {
- ByteArray id{std::string(kId)};
-
- BlePeripheral ble_peripheral{id};
-
- EXPECT_TRUE(ble_peripheral.IsValid());
- EXPECT_EQ(id, ble_peripheral.GetId());
-}
-
-TEST(BlePeripheralTest, ConstructionEmptyFails) {
- BlePeripheral ble_peripheral;
-
- EXPECT_FALSE(ble_peripheral.IsValid());
- EXPECT_TRUE(ble_peripheral.GetId().Empty());
-}
-
-} // namespace
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/discovered_peripheral_callback.h b/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/discovered_peripheral_callback.h
deleted file mode 100644
index 8aacfed4d2e..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/ble_v2/discovered_peripheral_callback.h
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_MEDIUMS_BLE_V2_DISCOVERED_PERIPHERAL_CALLBACK_H_
-#define CORE_INTERNAL_MEDIUMS_BLE_V2_DISCOVERED_PERIPHERAL_CALLBACK_H_
-
-#include "core/internal/mediums/ble_v2/ble_peripheral.h"
-#include "core/listeners.h"
-#include "platform/base/byte_array.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-/** Callback that is invoked when a {@link BlePeripheral} is discovered. */
-struct DiscoveredPeripheralCallback {
- std::function<void(BlePeripheral& peripheral, const std::string& service_id,
- const ByteArray& advertisement_byts,
- bool fast_advertisement)>
- peripheral_discovered_cb =
- DefaultCallback<BlePeripheral&, const std::string&, const ByteArray&,
- bool>();
- std::function<void(BlePeripheral& peripheral, const std::string& service_id)>
- peripheral_lost_cb =
- DefaultCallback<BlePeripheral&, const std::string&>();
-};
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_MEDIUMS_BLE_V2_DISCOVERED_PERIPHERAL_CALLBACK_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/bloom_filter.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/bloom_filter.cc
deleted file mode 100644
index 20a2370bf0a..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/bloom_filter.cc
+++ /dev/null
@@ -1,105 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/bloom_filter.h"
-
-#include "absl/numeric/int128.h"
-#include "absl/strings/numbers.h"
-#include "smhasher/src/MurmurHash3.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-BloomFilterBase::BloomFilterBase(const ByteArray& bytes, BitSet* bit_set)
- : bits_(bit_set) {
- const char* bytes_read_ptr = bytes.data();
- for (size_t byte_index = 0; byte_index < bytes.size(); byte_index++) {
- for (size_t bit_index = 0; bit_index < 8; bit_index++) {
- bits_->Set((byte_index * 8) + bit_index,
- (*bytes_read_ptr >> bit_index) & 0x01);
- }
- bytes_read_ptr++;
- }
-}
-
-BloomFilterBase::operator ByteArray() const {
- // Gets a binary string representation of the bitset where the leftmost
- // character corresponds to bitset position (total size) - 1.
- //
- // If the bitset's internal representation is:
- // [position 0] 0 0 1 1 0 0 0 1 0 1 0 1 [position 11]
- // The string representation will be outputted like this:
- // "1 0 1 0 1 0 0 0 1 1 0 0"
- std::string bitset_binary_string = bits_->ToString();
-
- ByteArray result_bytes(GetMinBytesForBits());
- char* result_bytes_write_ptr = result_bytes.data();
- // We go through the string backwards because the rightmost character
- // corresponds to position 0 in the bitset.
- for (size_t i = bits_->Size(); i > 0; i -= 8) {
- std::string byte_binary_string = bitset_binary_string.substr(i - 8, 8);
- std::uint32_t byte_value;
- absl::numbers_internal::safe_strtou32_base(byte_binary_string, &byte_value,
- /* base= */ 2);
- *result_bytes_write_ptr = static_cast<char>(byte_value & 0x000000FF);
- result_bytes_write_ptr++;
- }
- return result_bytes;
-}
-
-void BloomFilterBase::Add(const std::string& s) {
- std::vector<std::int32_t> hashes = GetHashes(s);
- for (int32_t hash : hashes) {
- size_t position = static_cast<size_t>(hash) % bits_->Size();
- bits_->Set(position, true);
- }
-}
-
-bool BloomFilterBase::PossiblyContains(const std::string& s) {
- std::vector<std::int32_t> hashes = GetHashes(s);
- for (int32_t hash : hashes) {
- size_t position = static_cast<size_t>(hash) % bits_->Size();
- if (!bits_->Test(position)) {
- return false;
- }
- }
- return true;
-}
-
-std::vector<std::int32_t> BloomFilterBase::GetHashes(const std::string& s) {
- std::vector<std::int32_t> hashes(kHasherNumberOfRepetitions, 0);
-
- absl::uint128 hash128;
- MurmurHash3_x64_128(s.data(), s.size(), 0, &hash128);
- std::uint64_t hash64 =
- absl::Uint128Low64(hash128); // the lower 64 bits of the 128-bit hash
- std::int32_t hash1 = static_cast<std::int32_t>(
- hash64 & 0x00000000FFFFFFFF); // the lower 32 bits of the 64-bit hash
- std::int32_t hash2 = static_cast<std::int32_t>(
- (hash64 >> 32) & 0x0FFFFFFFF); // the upper 32 bits of the 64-bit hash
- for (size_t i = 1; i <= kHasherNumberOfRepetitions; i++) {
- std::int32_t combinedHash = static_cast<std::int32_t>(hash1 + (i * hash2));
- // Flip all the bits if it's negative (guaranteed positive number)
- if (combinedHash < 0) combinedHash = ~combinedHash;
- hashes[i - 1] = combinedHash;
- }
- return hashes;
-}
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/bloom_filter.h b/chromium/third_party/nearby/src/cpp/core/internal/mediums/bloom_filter.h
deleted file mode 100644
index 3d3f45c9d36..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/bloom_filter.h
+++ /dev/null
@@ -1,101 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_MEDIUMS_BLOOM_FILTER_H_
-#define CORE_INTERNAL_MEDIUMS_BLOOM_FILTER_H_
-
-#include <bitset>
-#include <vector>
-
-#include "platform/base/byte_array.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-/**
- * A bloom filter that gives access to the underlying BitSet. The implementation
- * is copied from our Java version of Bloom filter, which in turn copies from
- * Guava's BloomFilter.
- *
- * BloomFilter is templatized on the size of the byte array and not the size of
- * the bit set to ensure the bit set's length is a multiple of 8 (and can
- * neatly be returned as a ByteArray).
- */
-class BloomFilterBase {
- public:
- explicit operator ByteArray() const;
-
- void Add(const std::string& s);
- bool PossiblyContains(const std::string& s);
-
- protected:
- class BitSet {
- public:
- virtual ~BitSet() = default;
- virtual std::string ToString() const = 0;
- virtual void Set(size_t pos, bool value) = 0;
- virtual bool Test(size_t pos) const = 0;
- virtual size_t Size() const = 0;
- };
-
- BloomFilterBase(const ByteArray& bytes, BitSet* bit_set);
- virtual ~BloomFilterBase() = default;
-
- constexpr static int kHasherNumberOfRepetitions = 5;
- std::vector<std::int32_t> GetHashes(const std::string& s);
-
- private:
- int GetMinBytesForBits() const { return (bits_->Size() + 7) >> 3; }
-
- BitSet* bits_;
-};
-
-template <size_t CapacityInBytes>
-class BloomFilter final : public BloomFilterBase {
- public:
- BloomFilter() : BloomFilterBase(ByteArray{}, &bits_) {}
- explicit BloomFilter(const ByteArray& bytes)
- : BloomFilterBase(bytes, &bits_) {}
- BloomFilter(const BloomFilter&) = default;
- BloomFilter& operator=(const BloomFilter&) = default;
- BloomFilter(BloomFilter&& other) : BloomFilterBase(ByteArray{}, &bits_) {
- *this = std::move(other);
- }
- BloomFilter& operator=(BloomFilter&& other) {
- std::swap((*this).bits_, other.bits_);
- return *this;
- }
- ~BloomFilter() override = default;
-
- private:
- class BitSetImpl final : public BitSet {
- public:
- std::string ToString() const override { return bits_.to_string(); }
- void Set(size_t pos, bool value) override { bits_.set(pos, value); }
- bool Test(size_t pos) const override { return bits_.test(pos); }
- size_t Size() const override { return bits_.size(); }
-
- private:
- std::bitset<CapacityInBytes * 8> bits_;
- } bits_;
-};
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_MEDIUMS_BLOOM_FILTER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/bloom_filter_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/bloom_filter_test.cc
deleted file mode 100644
index 70e846a69dc..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/bloom_filter_test.cc
+++ /dev/null
@@ -1,207 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/bloom_filter.h"
-
-#include <algorithm>
-
-#include "gtest/gtest.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-namespace {
-
-constexpr size_t kByteArrayLength = 100;
-
-TEST(BloomFilterTest, EmptyFilterReturnsEmptyArray) {
- BloomFilter<kByteArrayLength> bloom_filter;
-
- ByteArray bloom_filter_bytes(bloom_filter);
- std::string empty_string(kByteArrayLength, '\0');
-
- EXPECT_EQ(empty_string, std::string(bloom_filter_bytes));
-}
-
-TEST(BloomFilterTest, EmptyFilterNeverContains) {
- BloomFilter<kByteArrayLength> bloom_filter;
-
- EXPECT_FALSE(bloom_filter.PossiblyContains("ELEMENT_1"));
- EXPECT_FALSE(bloom_filter.PossiblyContains("ELEMENT_2"));
- EXPECT_FALSE(bloom_filter.PossiblyContains("ELEMENT_3"));
-}
-
-TEST(BloomFilterTest, AddSuccess) {
- BloomFilter<kByteArrayLength> bloom_filter;
-
- EXPECT_FALSE(bloom_filter.PossiblyContains("ELEMENT_1"));
-
- bloom_filter.Add("ELEMENT_1");
-
- EXPECT_TRUE(bloom_filter.PossiblyContains("ELEMENT_1"));
-}
-
-TEST(BloomFilterTest, AddOnlyGivenArg) {
- BloomFilter<kByteArrayLength> bloom_filter;
-
- bloom_filter.Add("ELEMENT_1");
-
- EXPECT_TRUE(bloom_filter.PossiblyContains("ELEMENT_1"));
- EXPECT_FALSE(bloom_filter.PossiblyContains("ELEMENT_2"));
- EXPECT_FALSE(bloom_filter.PossiblyContains("ELEMENT_3"));
-}
-
-TEST(BloomFilterTest, AddMultipleArgs) {
- BloomFilter<kByteArrayLength> bloom_filter;
-
- bloom_filter.Add("ELEMENT_1");
- bloom_filter.Add("ELEMENT_2");
-
- EXPECT_TRUE(bloom_filter.PossiblyContains("ELEMENT_1"));
- EXPECT_TRUE(bloom_filter.PossiblyContains("ELEMENT_2"));
- EXPECT_FALSE(bloom_filter.PossiblyContains("ELEMENT_3"));
-}
-
-TEST(BloomFilterTest, AddMultipleArgsReturnsNonemptyArray) {
- BloomFilter<10> bloom_filter;
-
- bloom_filter.Add("ELEMENT_1");
- bloom_filter.Add("ELEMENT_2");
- bloom_filter.Add("ELEMENT_3");
-
- ByteArray bloom_filter_bytes(bloom_filter);
- std::string empty_string(kByteArrayLength, '\0');
-
- EXPECT_NE(std::string(bloom_filter_bytes), empty_string);
-}
-
-TEST(BloomFilterTest, CopyConstructorAndAssignmentSuccess) {
- BloomFilter<kByteArrayLength> bloom_filter;
-
- EXPECT_FALSE(bloom_filter.PossiblyContains("ELEMENT_1"));
-
- bloom_filter.Add("ELEMENT_1");
-
- BloomFilter<kByteArrayLength> bloom_filter_copy_1{bloom_filter};
- BloomFilter<kByteArrayLength> bloom_filter_copy_2 = bloom_filter;
-
- EXPECT_TRUE(bloom_filter.PossiblyContains("ELEMENT_1"));
- EXPECT_TRUE(bloom_filter_copy_1.PossiblyContains("ELEMENT_1"));
- EXPECT_TRUE(bloom_filter_copy_2.PossiblyContains("ELEMENT_1"));
-}
-
-TEST(BloomFilterTest, MoveConstructorSuccess) {
- BloomFilter<kByteArrayLength> bloom_filter;
-
- bloom_filter.Add("ELEMENT_1");
-
- BloomFilter<kByteArrayLength> bloom_filter_move{std::move(bloom_filter)};
-
- EXPECT_TRUE(bloom_filter_move.PossiblyContains("ELEMENT_1"));
-}
-
-TEST(BloomFilterTest, MoveAssignmentSuccess) {
- BloomFilter<kByteArrayLength> bloom_filter;
-
- bloom_filter.Add("ELEMENT_1");
-
- BloomFilter<kByteArrayLength> bloom_filter_move = std::move(bloom_filter);
-
- EXPECT_TRUE(bloom_filter_move.PossiblyContains("ELEMENT_1"));
-}
-
-/**
- * This test was added because of a bug where the BloomFilter doesn't utilize
- * all bits given. Functionally, the filter still works, but we just have a much
- * higher false positive rate. The bug was caused by confusing bit length and
- * byte length, which made our BloomFilter only set bits on the first byteLength
- * (bitLength / 8) bits rather than the whole bitLength bits.
- *
- * <p>Here, we're verifying that the bits set are somewhat scattered. So instead
- * of something like [ 0, 1, 1, 0, 0, 0, 0, ..., 0 ], we should be getting
- * something like [ 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, ..., 1, 0].
- */
-TEST(BloomFilterTest, RandomnessNoEndBias) {
- BloomFilter<kByteArrayLength> bloom_filter;
-
- // Add one element to our BloomFilter.
- bloom_filter.Add("ELEMENT_1");
-
- std::int32_t non_zero_count = 0;
- std::int32_t longest_zero_streak = 0;
- std::int32_t current_zero_streak = 0;
-
- // Record the amount of non-zero bytes and the longest streak of zero bytes in
- // the resulting BloomFilter. This is an approximation of reasonable
- // distribution since we're recording by bytes instead of bits.
- ByteArray bloom_filter_bytes(bloom_filter);
- const char* bloom_filter_bytes_read_ptr = bloom_filter_bytes.data();
- for (int i = 0; i < bloom_filter_bytes.size(); i++) {
- if (*bloom_filter_bytes_read_ptr == '\0') {
- current_zero_streak++;
- } else {
- // Increment the number of non-zero bytes we've seen, update the longest
- // zero streak, and then reset the current zero streak.
- non_zero_count++;
- longest_zero_streak = std::max(longest_zero_streak, current_zero_streak);
- current_zero_streak = 0;
- }
- bloom_filter_bytes_read_ptr++;
- }
- // Update the longest zero streak again for the tail case.
- longest_zero_streak = std::min(longest_zero_streak, current_zero_streak);
-
- // Since randomness is hard to measure within one unit test, we instead do a
- // sanity check. All non-zero bytes should not be packed into one end of the
- // array.
- //
- // In this case, the size of one end is approximated to be:
- // kByteArrayLength / nonZeroCount.
- // Therefore, the longest zero streak should be less than:
- // kByteArrayLength - one end of the array.
- std::int32_t longest_acceptable_zero_streak =
- kByteArrayLength - (kByteArrayLength / non_zero_count);
-
- EXPECT_TRUE(longest_zero_streak <= longest_acceptable_zero_streak);
-}
-
-TEST(BloomFilterTest, RandomnessFalsePositiveRate) {
- BloomFilter<10> bloom_filter;
-
- // Add 5 distinct elements to the BloomFilter.
- bloom_filter.Add("ELEMENT_1");
- bloom_filter.Add("ELEMENT_2");
- bloom_filter.Add("ELEMENT_3");
- bloom_filter.Add("ELEMENT_4");
- bloom_filter.Add("ELEMENT_5");
-
- std::int32_t false_positives = 0;
- // Now test 100 other elements and record the number of false positives.
- for (int i = 5; i < 105; i++) {
- false_positives +=
- bloom_filter.PossiblyContains("ELEMENT_" + std::to_string(i)) ? 1 : 0;
- }
-
- // We expect the false positive rate to be 3% with 5 elements in a 10 byte
- // filter. Thus, we give a little leeway and verify that the false positive
- // rate is no more than 5%.
- EXPECT_LE(false_positives, 5);
-}
-
-} // namespace
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/bluetooth_classic.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/bluetooth_classic.cc
deleted file mode 100644
index bfa15992b26..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/bluetooth_classic.cc
+++ /dev/null
@@ -1,434 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/bluetooth_classic.h"
-
-#include <memory>
-#include <string>
-#include <utility>
-
-#include "core/internal/mediums/uuid.h"
-#include "platform/public/logging.h"
-#include "platform/public/mutex_lock.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-BluetoothClassic::BluetoothClassic(BluetoothRadio& radio) : radio_(radio) {}
-
-BluetoothClassic::~BluetoothClassic() {
- // Destructor is not taking locks, but methods it is calling are.
- StopDiscovery();
- while (!server_sockets_.empty()) {
- StopAcceptingConnections(server_sockets_.begin()->first);
- }
- TurnOffDiscoverability();
-
- // All the AcceptLoopRunnable objects in here should already have gotten an
- // opportunity to shut themselves down cleanly in the calls to
- // StopAcceptingConnections() above.
- accept_loops_runner_.Shutdown();
-}
-
-bool BluetoothClassic::IsAvailable() const {
- MutexLock lock(&mutex_);
-
- return IsAvailableLocked();
-}
-
-bool BluetoothClassic::IsAvailableLocked() const {
- return medium_.IsValid() && adapter_.IsValid();
-}
-
-bool BluetoothClassic::TurnOnDiscoverability(const std::string& device_name) {
- MutexLock lock(&mutex_);
-
- if (device_name.empty()) {
- NEARBY_LOG(INFO,
- "Refusing to turn on BT discoverability. Empty device name.");
- return false;
- }
-
- if (!radio_.IsEnabled()) {
- NEARBY_LOG(INFO, "Can't turn on BT discoverability. BT is off.");
- return false;
- }
-
- if (!IsAvailableLocked()) {
- NEARBY_LOG(INFO, "Can't turn on BT discoverability. BT is not available.");
- return false;
- }
-
- if (IsDiscoverable()) {
- NEARBY_LOG(INFO,
- "Refusing to turn on BT discoverability; new name='%s'; "
- "current name='%s'",
- device_name.c_str(), adapter_.GetName().c_str());
- return false;
- }
-
- if (!ModifyDeviceName(device_name)) {
- NEARBY_LOG(INFO,
- "Failed to turn on BT discoverability; "
- "failed to set name to %s",
- device_name.c_str());
- return false;
- }
-
- if (!ModifyScanMode(ScanMode::kConnectableDiscoverable)) {
- NEARBY_LOG(INFO,
- "Failed to turn on BT discoverability; "
- "failed to set scan_mode to %d",
- ScanMode::kConnectableDiscoverable);
-
- // Don't forget to perform this rollback of the partial state changes we've
- // made til now.
- RestoreDeviceName();
- return false;
- }
-
- NEARBY_LOG(INFO, "Turned on BT discoverability with device_name=%s",
- device_name.c_str());
- return true;
-}
-
-bool BluetoothClassic::TurnOffDiscoverability() {
- MutexLock lock(&mutex_);
-
- if (!IsDiscoverable()) {
- NEARBY_LOG(INFO, "Can't turn off BT discoverability; it is already off");
- return false;
- }
-
- RestoreScanMode();
- RestoreDeviceName();
-
- NEARBY_LOG(INFO, "Turned Bluetooth discoverability off");
- return true;
-}
-
-bool BluetoothClassic::IsDiscoverable() const {
- return (!original_device_name_.empty() &&
- (adapter_.GetScanMode() == ScanMode::kConnectableDiscoverable));
-}
-
-bool BluetoothClassic::ModifyDeviceName(const std::string& device_name) {
- if (original_device_name_.empty()) {
- original_device_name_ = adapter_.GetName();
- }
-
- return adapter_.SetName(device_name);
-}
-
-bool BluetoothClassic::ModifyScanMode(ScanMode scan_mode) {
- if (original_scan_mode_ == ScanMode::kUnknown) {
- original_scan_mode_ = adapter_.GetScanMode();
- }
-
- if (!adapter_.SetScanMode(scan_mode)) {
- original_scan_mode_ = ScanMode::kUnknown;
- return false;
- }
-
- return true;
-}
-
-bool BluetoothClassic::RestoreScanMode() {
- if (original_scan_mode_ == ScanMode::kUnknown ||
- !adapter_.SetScanMode(original_scan_mode_)) {
- NEARBY_LOG(INFO, "Failed to restore original Bluetooth scan mode to %d",
- original_scan_mode_);
- return false;
- }
-
- // Regardless of whether or not we could actually restore the Bluetooth scan
- // mode, reset our relevant state.
- original_scan_mode_ = ScanMode::kUnknown;
- return true;
-}
-
-bool BluetoothClassic::RestoreDeviceName() {
- if (original_device_name_.empty() ||
- !adapter_.SetName(original_device_name_)) {
- NEARBY_LOG(INFO, "Failed to restore original Bluetooth device name to %s",
- original_device_name_.c_str());
- return false;
- }
- original_device_name_.clear();
- return true;
-}
-
-bool BluetoothClassic::StartDiscovery(DiscoveredDeviceCallback callback) {
- MutexLock lock(&mutex_);
-
- if (!radio_.IsEnabled()) {
- NEARBY_LOG(INFO, "Can't discover BT devices because BT isn't enabled.");
- return false;
- }
-
- if (!IsAvailableLocked()) {
- NEARBY_LOG(INFO, "Can't discover BT devices because BT isn't available.");
- return false;
- }
-
- if (IsDiscovering()) {
- NEARBY_LOG(INFO,
- "Refusing to start discovery of BT devices because another "
- "discovery is already in-progress.");
- return false;
- }
-
- if (!medium_.StartDiscovery(callback)) {
- NEARBY_LOG(INFO, "Failed to start discovery of BT devices.");
- return false;
- }
-
- // Mark the fact that we're currently performing a Bluetooth scan.
- scan_info_.valid = true;
-
- return true;
-}
-
-bool BluetoothClassic::StopDiscovery() {
- MutexLock lock(&mutex_);
-
- if (!IsDiscovering()) {
- NEARBY_LOG(INFO,
- "Can't stop discovery of BT devices because it never started.");
- return false;
- }
-
- if (!medium_.StopDiscovery()) {
- NEARBY_LOG(INFO, "Failed to stop discovery of Bluetooth devices.");
- return false;
- }
-
- scan_info_.valid = false;
- return true;
-}
-
-bool BluetoothClassic::IsDiscovering() const { return scan_info_.valid; }
-
-bool BluetoothClassic::StartAcceptingConnections(
- const std::string& service_name, AcceptedConnectionCallback callback) {
- MutexLock lock(&mutex_);
-
- if (service_name.empty()) {
- NEARBY_LOG(
- INFO,
- "Refusing to start accepting BT connections; service name is empty.");
- return false;
- }
-
- if (!radio_.IsEnabled()) {
- NEARBY_LOG(INFO,
- "Can't create BT server socket [service=%s]; BT is disabled.",
- service_name.c_str());
- return false;
- }
-
- if (!IsAvailableLocked()) {
- NEARBY_LOG(
- INFO,
- "Can't start accepting BT connections [service=%s]; BT not available.",
- service_name.c_str());
- return false;
- }
-
- if (IsAcceptingConnectionsLocked(service_name)) {
- NEARBY_LOG(INFO,
- "Refusing to start accepting BT connections [service=%s]; BT "
- "server is already in-progress with the same name.",
- service_name.c_str());
- return false;
- }
-
- BluetoothServerSocket socket = medium_.ListenForService(
- service_name, GenerateUuidFromString(service_name));
- if (!socket.IsValid()) {
- NEARBY_LOG(INFO, "Failed to start accepting Bluetooth connections for %s.",
- service_name.c_str());
- return false;
- }
-
- // Mark the fact that there's an in-progress Bluetooth server accepting
- // connections.
- auto owned_socket =
- server_sockets_.emplace(service_name, std::move(socket)).first->second;
-
- // Start the accept loop on a dedicated thread - this stays alive and
- // listening for new incoming connections until StopAcceptingConnections() is
- // invoked.
- accept_loops_runner_.Execute(
- "bt-accept",
- [callback = std::move(callback), server_socket = std::move(owned_socket),
- service_name]() mutable {
- while (true) {
- BluetoothSocket client_socket = server_socket.Accept();
- if (!client_socket.IsValid()) {
- server_socket.Close();
- break;
- }
-
- callback.accepted_cb(std::move(client_socket));
- }
- });
-
- return true;
-}
-
-bool BluetoothClassic::IsAcceptingConnections(const std::string& service_name) {
- MutexLock lock(&mutex_);
-
- return IsAcceptingConnectionsLocked(service_name);
-}
-
-bool BluetoothClassic::IsAcceptingConnectionsLocked(
- const std::string& service_name) {
- return server_sockets_.find(service_name) != server_sockets_.end();
-}
-
-bool BluetoothClassic::StopAcceptingConnections(
- const std::string& service_name) {
- MutexLock lock(&mutex_);
-
- if (service_name.empty()) {
- NEARBY_LOG(INFO,
- "Unable to stop accepting BT connections because the "
- "service_name is empty.");
- return false;
- }
-
- const auto& it = server_sockets_.find(service_name);
- if (it == server_sockets_.end()) {
- NEARBY_LOG(INFO,
- "Can't stop accepting BT connections for %s because it was "
- "never started.",
- service_name.c_str());
- return false;
- }
-
- // Closing the BluetoothServerSocket will kick off the suicide of the thread
- // in accept_loops_thread_pool_ that blocks on BluetoothServerSocket.accept().
- // That may take some time to complete, but there's no particular reason to
- // wait around for it.
- auto item = server_sockets_.extract(it);
-
- // Store a handle to the BluetoothServerSocket, so we can use it after
- // removing the entry from server_sockets_; making it scoped
- // is a bonus that takes care of deallocation before we leave this method.
- BluetoothServerSocket& listening_socket = item.mapped();
-
- // Regardless of whether or not we fail to close the existing
- // BluetoothServerSocket, remove it from server_sockets_ so that it
- // frees up this service for another round.
-
- // Finally, close the BluetoothServerSocket.
- if (!listening_socket.Close().Ok()) {
- NEARBY_LOG(INFO, "Failed to close BT server socket for %s.",
- service_name.c_str());
- return false;
- }
-
- return true;
-}
-
-BluetoothSocket BluetoothClassic::Connect(BluetoothDevice& bluetooth_device,
- const std::string& service_name,
- CancellationFlag* cancellation_flag) {
- for (int attempts_count = 0; attempts_count < kConnectAttemptsLimit;
- attempts_count++) {
- auto wrapper_result =
- AttemptToConnect(bluetooth_device, service_name, cancellation_flag);
- if (wrapper_result.IsValid()) {
- return wrapper_result;
- }
- }
- return BluetoothSocket();
-}
-
-BluetoothSocket BluetoothClassic::AttemptToConnect(
- BluetoothDevice& bluetooth_device, const std::string& service_name,
- CancellationFlag* cancellation_flag) {
- MutexLock lock(&mutex_);
- NEARBY_LOG(INFO, "BluetoothClassic::Connect: device=%p", &bluetooth_device);
- // Socket to return. To allow for NRVO to work, it has to be a single object.
- BluetoothSocket socket;
-
- if (service_name.empty()) {
- NEARBY_LOG(
- INFO,
- "Refusing to create client BT socket because service_name is empty.");
- return socket;
- }
-
- if (!radio_.IsEnabled()) {
- NEARBY_LOG(INFO,
- "Can't create client BT socket [service=%s]: BT isn't enabled.",
- service_name.c_str());
- return socket;
- }
-
- if (!IsAvailableLocked()) {
- NEARBY_LOG(
- INFO, "Can't create client BT socket [service=%s]; BT isn't available.",
- service_name.c_str());
- return socket;
- }
-
- if (cancellation_flag->Cancelled()) {
- NEARBY_LOGS(INFO) << "Can't create client BT socket due to cancel.";
- return socket;
- }
-
- socket = medium_.ConnectToService(bluetooth_device,
- GenerateUuidFromString(service_name),
- cancellation_flag);
- if (!socket.IsValid()) {
- NEARBY_LOG(INFO, "Failed to Connect via BT [service=%s]",
- service_name.c_str());
- }
-
- return socket;
-}
-
-BluetoothDevice BluetoothClassic::GetRemoteDevice(
- const std::string& mac_address) {
- MutexLock lock(&mutex_);
-
- if (!IsAvailableLocked()) {
- return {};
- }
-
- return medium_.GetRemoteDevice(mac_address);
-}
-
-std::string BluetoothClassic::GetMacAddress() const {
- MutexLock lock(&mutex_);
-
- if (!IsAvailableLocked()) {
- return {};
- }
-
- return medium_.GetMacAddress();
-}
-
-std::string BluetoothClassic::GenerateUuidFromString(const std::string& data) {
- return std::string(Uuid(data));
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/bluetooth_classic.h b/chromium/third_party/nearby/src/cpp/core/internal/mediums/bluetooth_classic.h
deleted file mode 100644
index 8389b1a0b7c..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/bluetooth_classic.h
+++ /dev/null
@@ -1,210 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_MEDIUMS_BLUETOOTH_CLASSIC_H_
-#define CORE_INTERNAL_MEDIUMS_BLUETOOTH_CLASSIC_H_
-
-#include <cstdint>
-#include <string>
-
-#include "absl/container/flat_hash_map.h"
-#include "core/internal/mediums/bluetooth_radio.h"
-#include "core/listeners.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/cancellation_flag.h"
-#include "platform/public/bluetooth_adapter.h"
-#include "platform/public/bluetooth_classic.h"
-#include "platform/public/multi_thread_executor.h"
-#include "platform/public/mutex.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-class BluetoothClassic {
- public:
- using DiscoveredDeviceCallback = BluetoothClassicMedium::DiscoveryCallback;
- using ScanMode = BluetoothAdapter::ScanMode;
-
- // Callback that is invoked when a new connection is accepted.
- struct AcceptedConnectionCallback {
- std::function<void(BluetoothSocket socket)> accepted_cb =
- DefaultCallback<BluetoothSocket>();
- };
-
- explicit BluetoothClassic(BluetoothRadio& bluetooth_radio);
- ~BluetoothClassic();
-
- // Returns true, if BT communications are supported by a platform.
- bool IsAvailable() const ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Sets custom device name, and then enables BT discoverable mode.
- // Returns true, if name and scan mode are successfully set, and false
- // otherwise.
- // Called by server.
- bool TurnOnDiscoverability(const std::string& device_name)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Disables BT discoverability, and restores scan mode and device name to
- // what they were before the call to TurnOnDiscoverability().
- // Returns false if no successful call TurnOnDiscoverability() was previously
- // made, otherwise returns true.
- // Called by server.
- bool TurnOffDiscoverability() ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Enables BT discovery mode. Will report any discoverable devices in range
- // through a callback.
- // Returns true, if discovery mode was enabled, false otherwise.
- // Called by client.
- bool StartDiscovery(DiscoveredDeviceCallback callback)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Disables BT discovery mode.
- // Returns true, if discovery mode was previously enabled, false otherwise.
- // Called by client.
- bool StopDiscovery() ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Starts a worker thread, creates a BT server socket, associates it with a
- // service name; in a worker thread repeatedly calls ServerSocket::Accept().
- // Any connected sockets returned from Accept() are passed to a callback.
- // Returns true, if server socket was successfully created, false otherwise.
- // Called by server.
- bool StartAcceptingConnections(const std::string& service_name,
- AcceptedConnectionCallback callback)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns true, if object is currently running a Accept() loop.
- bool IsAcceptingConnections(const std::string& service_name)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Closes server socket corresponding to a service name. This automatically
- // terminates Accept() loop, if it were running.
- // Called by server.
- bool StopAcceptingConnections(const std::string& service_name)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns true if this object owns a valid platform implementation.
- bool IsMediumValid() const ABSL_LOCKS_EXCLUDED(mutex_) {
- MutexLock lock(&mutex_);
- return medium_.IsValid();
- }
-
- // Returns true if this object has a valid BluetoothAdapter reference.
- bool IsAdapterValid() const ABSL_LOCKS_EXCLUDED(mutex_) {
- MutexLock lock(&mutex_);
- return adapter_.IsValid();
- }
-
- // Establishes connection to BT service with internal retry for maximum
- // attempts of kConnectAttemptsLimit.
- // Blocks until connection is established, or server-side is terminated.
- // Returns socket instance. On success, BluetoothSocket.IsValid() return true.
- // Called by client.
- BluetoothSocket Connect(BluetoothDevice& bluetooth_device,
- const std::string& service_name,
- CancellationFlag* cancellation_flag)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- std::string GetMacAddress() const ABSL_LOCKS_EXCLUDED(mutex_);
-
- BluetoothDevice GetRemoteDevice(const std::string& mac_address)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- private:
- struct ScanInfo {
- bool valid = false;
- };
-
- static constexpr int kMaxConcurrentAcceptLoops = 5;
-
- static constexpr int kConnectAttemptsLimit = 3;
-
- // Constructs UUID object from arbitrary string, using MD5 hash, and then
- // converts UUID to a readable UUID string and returns it.
- static std::string GenerateUuidFromString(const std::string& data);
-
- // Same as IsAvailable(), but must be called with mutex_ held.
- bool IsAvailableLocked() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Same as IsAcceptingConnections(), but must be called with mutex_ held.
- bool IsAcceptingConnectionsLocked(const std::string& service_name)
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Returns true, if discoverability is enabled with TurnOnDiscoverability().
- bool IsDiscoverable() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Assignes a different name to BT adapter.
- // Returns true if successful. Stores original device name.
- bool ModifyDeviceName(const std::string& device_name)
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Changes current scan mode. This is an implementation of
- // Turn<On/Off>Discoveradility() method. Stores original scan mode.
- bool ModifyScanMode(ScanMode scan_mode) ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Restores original device name (the one before the very first call to
- // ModifyDeviceName()). Returns true if successful.
- bool RestoreScanMode() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Restores original device scan mode (the one before the very first call to
- // ModifyScanMode()). Returns true if successful.
- bool RestoreDeviceName() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Returns true if device is currently in discovery mode.
- bool IsDiscovering() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Establishes connection to BT service that was might be started on another
- // device with StartAcceptingConnections() using the same service_name.
- // Blocks until connection is established, or server-side is terminated.
- // Returns socket instance. On success, BluetoothSocket.IsValid() return true.
- // Called by client.
- BluetoothSocket AttemptToConnect(BluetoothDevice& bluetooth_device,
- const std::string& service_name,
- CancellationFlag* cancellation_flag);
-
- mutable Mutex mutex_;
- BluetoothRadio& radio_ ABSL_GUARDED_BY(mutex_);
- BluetoothAdapter& adapter_ ABSL_GUARDED_BY(mutex_){
- radio_.GetBluetoothAdapter()};
- BluetoothClassicMedium medium_ ABSL_GUARDED_BY(mutex_){adapter_};
-
- // A bundle of state required to do a Bluetooth Classic scan. When non-null,
- // we are currently performing a Bluetooth scan.
- ScanInfo scan_info_ ABSL_GUARDED_BY(mutex_);
-
- // The original scan mode (that controls visibility to scanners) of the device
- // before we modified it. Restored when we stop advertising.
- ScanMode original_scan_mode_ ABSL_GUARDED_BY(mutex_) = ScanMode::kUnknown;
-
- // The original Bluetooth device name, before we modified it. If non-empty, we
- // are currently Bluetooth discoverable. Restored when we stop advertising.
- std::string original_device_name_ ABSL_GUARDED_BY(mutex_);
-
- // A thread pool dedicated to running all the accept loops from
- // StartAcceptingConnections().
- MultiThreadExecutor accept_loops_runner_{kMaxConcurrentAcceptLoops};
-
- // A map of service Name -> ServerSocket. If map is non-empty, we
- // are currently listening for incoming connections.
- // BluetoothServerSocket instances are used from accept_loops_runner_,
- // and thus require pointer stability.
- absl::flat_hash_map<std::string, BluetoothServerSocket> server_sockets_
- ABSL_GUARDED_BY(mutex_);
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_MEDIUMS_BLUETOOTH_CLASSIC_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/bluetooth_classic_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/bluetooth_classic_test.cc
deleted file mode 100644
index d386bea51e0..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/bluetooth_classic_test.cc
+++ /dev/null
@@ -1,290 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/bluetooth_classic.h"
-
-#include <string>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/time/time.h"
-#include "core/internal/mediums/bluetooth_radio.h"
-#include "platform/base/medium_environment.h"
-#include "platform/public/bluetooth_classic.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/logging.h"
-#include "platform/public/system_clock.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-
-using FeatureFlags = FeatureFlags::Flags;
-
-constexpr FeatureFlags kTestCases[] = {
- FeatureFlags{
- .enable_cancellation_flag = true,
- },
- FeatureFlags{
- .enable_cancellation_flag = false,
- },
-};
-
-constexpr absl::Duration kWaitDuration = absl::Milliseconds(1000);
-
-class BluetoothClassicTest : public ::testing::TestWithParam<FeatureFlags> {
- protected:
- using DiscoveryCallback = BluetoothClassicMedium::DiscoveryCallback;
-
- BluetoothClassicTest() {
- env_.Start();
- env_.Reset();
- radio_a_ = std::make_unique<BluetoothRadio>();
- radio_b_ = std::make_unique<BluetoothRadio>();
- bt_a_ = std::make_unique<BluetoothClassic>(*radio_a_);
- bt_b_ = std::make_unique<BluetoothClassic>(*radio_b_);
- radio_a_->GetBluetoothAdapter().SetName("Device-A");
- radio_b_->GetBluetoothAdapter().SetName("Device-B");
- radio_a_->Enable();
- radio_b_->Enable();
- env_.Sync();
- }
-
- ~BluetoothClassicTest() override {
- env_.Sync(false);
- radio_a_->Disable();
- radio_b_->Disable();
- bt_a_.reset();
- bt_b_.reset();
- env_.Sync(false);
- radio_a_.reset();
- radio_b_.reset();
- env_.Reset();
- env_.Stop();
- }
-
- MediumEnvironment& env_{MediumEnvironment::Instance()};
-
- std::unique_ptr<BluetoothRadio> radio_a_;
- std::unique_ptr<BluetoothRadio> radio_b_;
- std::unique_ptr<BluetoothClassic> bt_a_;
- std::unique_ptr<BluetoothClassic> bt_b_;
-};
-
-TEST_P(BluetoothClassicTest, CanConnect) {
- FeatureFlags feature_flags = GetParam();
- env_.SetFeatureFlags(feature_flags);
-
- constexpr absl::string_view kDeviceName{"Simulated BT device #1"};
- constexpr absl::string_view kServiceName{"service name"};
-
- BluetoothRadio& radio_for_client = *radio_a_;
- BluetoothRadio& radio_for_server = *radio_b_;
- BluetoothClassic& bt_client = *bt_a_;
- BluetoothClassic& bt_server = *bt_b_;
-
- EXPECT_TRUE(radio_for_client.IsEnabled());
- EXPECT_TRUE(radio_for_server.IsEnabled());
-
- EXPECT_TRUE(bt_server.TurnOnDiscoverability(std::string(kDeviceName)));
- EXPECT_EQ(radio_for_server.GetBluetoothAdapter().GetName(),
- std::string(kDeviceName));
- CountDownLatch latch(1);
- BluetoothDevice discovered_device;
- EXPECT_TRUE(bt_client.StartDiscovery({
- .device_discovered_cb =
- [&latch, &discovered_device](BluetoothDevice& device) {
- discovered_device = device;
- NEARBY_LOG(INFO, "Discovered device=%p [impl=%p]", &device,
- &device.GetImpl());
- latch.CountDown();
- },
- }));
- EXPECT_TRUE(latch.Await(kWaitDuration).result());
- EXPECT_TRUE(bt_server.TurnOffDiscoverability());
- ASSERT_TRUE(discovered_device.IsValid());
- BluetoothSocket socket_for_server;
- CountDownLatch accept_latch(1);
- EXPECT_TRUE(bt_server.StartAcceptingConnections(
- std::string(kServiceName),
- {
- .accepted_cb =
- [&socket_for_server, &accept_latch](BluetoothSocket socket) {
- socket_for_server = std::move(socket);
- accept_latch.CountDown();
- },
- }));
- CancellationFlag flag;
- BluetoothSocket socket_for_client =
- bt_client.Connect(discovered_device, std::string(kServiceName), &flag);
- EXPECT_TRUE(accept_latch.Await(kWaitDuration).result());
- EXPECT_TRUE(bt_server.StopAcceptingConnections(std::string(kServiceName)));
- EXPECT_TRUE(socket_for_server.IsValid());
- EXPECT_TRUE(socket_for_client.IsValid());
- EXPECT_TRUE(socket_for_server.GetRemoteDevice().IsValid());
- EXPECT_TRUE(socket_for_client.GetRemoteDevice().IsValid());
-}
-
-TEST_P(BluetoothClassicTest, CanCancelConnect) {
- FeatureFlags feature_flags = GetParam();
- env_.SetFeatureFlags(feature_flags);
-
- constexpr absl::string_view kDeviceName{"Simulated BT device #1"};
- constexpr absl::string_view kServiceName{"service name"};
-
- BluetoothRadio& radio_for_client = *radio_a_;
- BluetoothRadio& radio_for_server = *radio_b_;
- BluetoothClassic& bt_client = *bt_a_;
- BluetoothClassic& bt_server = *bt_b_;
-
- EXPECT_TRUE(radio_for_client.IsEnabled());
- EXPECT_TRUE(radio_for_server.IsEnabled());
-
- EXPECT_TRUE(bt_server.TurnOnDiscoverability(std::string(kDeviceName)));
- EXPECT_EQ(radio_for_server.GetBluetoothAdapter().GetName(),
- std::string(kDeviceName));
- CountDownLatch latch(1);
- BluetoothDevice discovered_device;
- EXPECT_TRUE(bt_client.StartDiscovery({
- .device_discovered_cb =
- [&latch, &discovered_device](BluetoothDevice& device) {
- discovered_device = device;
- NEARBY_LOG(INFO, "Discovered device=%p [impl=%p]", &device,
- &device.GetImpl());
- latch.CountDown();
- },
- }));
- EXPECT_TRUE(latch.Await(kWaitDuration).result());
- EXPECT_TRUE(bt_server.TurnOffDiscoverability());
- ASSERT_TRUE(discovered_device.IsValid());
- BluetoothSocket socket_for_server;
- CountDownLatch accept_latch(1);
- EXPECT_TRUE(bt_server.StartAcceptingConnections(
- std::string(kServiceName),
- {
- .accepted_cb =
- [&socket_for_server, &accept_latch](BluetoothSocket socket) {
- socket_for_server = std::move(socket);
- accept_latch.CountDown();
- },
- }));
- CancellationFlag flag(true);
- BluetoothSocket socket_for_client =
- bt_client.Connect(discovered_device, std::string(kServiceName), &flag);
- // If FeatureFlag is disabled, Cancelled is false as no-op.
- if (!feature_flags.enable_cancellation_flag) {
- EXPECT_TRUE(accept_latch.Await(kWaitDuration).result());
- EXPECT_TRUE(bt_server.StopAcceptingConnections(std::string(kServiceName)));
- EXPECT_TRUE(socket_for_server.IsValid());
- EXPECT_TRUE(socket_for_client.IsValid());
- EXPECT_TRUE(socket_for_server.GetRemoteDevice().IsValid());
- EXPECT_TRUE(socket_for_client.GetRemoteDevice().IsValid());
- } else {
- EXPECT_FALSE(accept_latch.Await(kWaitDuration).result());
- EXPECT_TRUE(bt_server.StopAcceptingConnections(std::string(kServiceName)));
- EXPECT_FALSE(socket_for_server.IsValid());
- EXPECT_FALSE(socket_for_client.IsValid());
- }
-}
-
-INSTANTIATE_TEST_SUITE_P(ParametrisedBluetoothClassicTest, BluetoothClassicTest,
- ::testing::ValuesIn(kTestCases));
-
-TEST_F(BluetoothClassicTest, CanConstructValidObject) {
- EXPECT_TRUE(bt_a_->IsMediumValid());
- EXPECT_TRUE(bt_a_->IsAdapterValid());
- EXPECT_TRUE(bt_a_->IsAvailable());
- EXPECT_TRUE(bt_b_->IsMediumValid());
- EXPECT_TRUE(bt_b_->IsAdapterValid());
- EXPECT_TRUE(bt_b_->IsAvailable());
- EXPECT_NE(&radio_a_->GetBluetoothAdapter(), &radio_b_->GetBluetoothAdapter());
-}
-
-TEST_F(BluetoothClassicTest, CanStartAdvertising) {
- constexpr absl::string_view kDeviceName{"Simulated BT device #1"};
- EXPECT_TRUE(bt_a_->TurnOnDiscoverability(std::string(kDeviceName)));
- EXPECT_EQ(radio_a_->GetBluetoothAdapter().GetName(), kDeviceName);
-}
-
-TEST_F(BluetoothClassicTest, CanStopAdvertising) {
- constexpr absl::string_view kDeviceName{"Simulated BT device #1"};
- EXPECT_TRUE(bt_a_->TurnOnDiscoverability(std::string(kDeviceName)));
- EXPECT_EQ(radio_a_->GetBluetoothAdapter().GetName(), kDeviceName);
- EXPECT_TRUE(bt_a_->TurnOffDiscoverability());
-}
-
-TEST_F(BluetoothClassicTest, CanStartDiscovery) {
- constexpr absl::string_view kDeviceName{"Simulated BT device #1"};
- EXPECT_TRUE(bt_a_->TurnOnDiscoverability(std::string(kDeviceName)));
- EXPECT_EQ(radio_a_->GetBluetoothAdapter().GetName(), kDeviceName);
- CountDownLatch latch(1);
- EXPECT_TRUE(bt_b_->StartDiscovery({
- .device_discovered_cb =
- [&latch](BluetoothDevice& device) { latch.CountDown(); },
- }));
- EXPECT_TRUE(latch.Await(kWaitDuration).result());
- EXPECT_TRUE(bt_a_->TurnOffDiscoverability());
-}
-
-TEST_F(BluetoothClassicTest, CanStopDiscovery) {
- CountDownLatch latch(1);
- EXPECT_TRUE(bt_a_->StartDiscovery({
- .device_discovered_cb =
- [&latch](BluetoothDevice& device) { latch.CountDown(); },
- }));
- EXPECT_FALSE(latch.Await(kWaitDuration).result());
- EXPECT_TRUE(bt_a_->StopDiscovery());
-}
-
-TEST_F(BluetoothClassicTest, CanStartAcceptingConnections) {
- constexpr absl::string_view kDeviceName{"Simulated BT device #1"};
- constexpr absl::string_view kServiceName{"service name"};
-
- BluetoothRadio& radio_for_client = *radio_a_;
- BluetoothRadio& radio_for_server = *radio_b_;
- BluetoothClassic& bt_client = *bt_a_;
- BluetoothClassic& bt_server = *bt_b_;
-
- EXPECT_TRUE(radio_for_client.IsEnabled());
- EXPECT_TRUE(radio_for_server.IsEnabled());
-
- EXPECT_TRUE(bt_server.TurnOnDiscoverability(std::string(kDeviceName)));
- EXPECT_EQ(radio_for_server.GetBluetoothAdapter().GetName(), kDeviceName);
- CountDownLatch latch(1);
- BluetoothDevice discovered_device;
- EXPECT_TRUE(bt_client.StartDiscovery({
- .device_discovered_cb =
- [&latch, &discovered_device](BluetoothDevice& device) {
- discovered_device = device;
- NEARBY_LOG(INFO, "Discovered device=%p [impl=%p]", &device,
- &device.GetImpl());
- latch.CountDown();
- },
- }));
- EXPECT_TRUE(latch.Await(kWaitDuration).result());
- EXPECT_TRUE(bt_server.TurnOffDiscoverability());
- EXPECT_TRUE(discovered_device.IsValid());
- EXPECT_TRUE(
- bt_server.StartAcceptingConnections(std::string(kServiceName), {}));
- // Allow StartAcceptingConnections do something, before stopping it.
- // This is best effort, because no callbacks are invoked in this scenario.
- SystemClock::Sleep(kWaitDuration);
- EXPECT_TRUE(bt_server.StopAcceptingConnections(std::string(kServiceName)));
-}
-
-} // namespace
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/bluetooth_radio.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/bluetooth_radio.cc
deleted file mode 100644
index e0ec86149e4..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/bluetooth_radio.cc
+++ /dev/null
@@ -1,120 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/bluetooth_radio.h"
-
-#include "platform/base/exception.h"
-#include "platform/public/logging.h"
-#include "platform/public/system_clock.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-constexpr absl::Duration BluetoothRadio::kPauseBetweenToggle;
-
-BluetoothRadio::BluetoothRadio() {
- if (!IsAdapterValid()) {
- NEARBY_LOG(ERROR, "Bluetooth adapter is not valid: BT is not supported");
- }
-}
-
-BluetoothRadio::~BluetoothRadio() {
- // We never enabled Bluetooth, nothing to do.
- if (!ever_saved_state_.Get()) {
- NEARBY_LOG(INFO, "BT adapter was not used. Not touching HW.");
- return;
- }
-
- // Toggle Bluetooth regardless of our original state. Some devices/chips can
- // start to freak out after some time (e.g. b/37775337), and this helps to
- // ensure BT resets properly.
- NEARBY_LOG(INFO, "Toggle BT adapter state before releasing adapter.");
- Toggle();
-
- NEARBY_LOG(INFO, "Bring BT adapter to original state");
- if (!SetBluetoothState(originally_enabled_.Get())) {
- NEARBY_LOG(INFO, "Failed to restore BT adapter original state.");
- }
-}
-
-bool BluetoothRadio::Enable() {
- if (!SaveOriginalState()) {
- return false;
- }
-
- return SetBluetoothState(true);
-}
-
-bool BluetoothRadio::Disable() {
- if (!SaveOriginalState()) {
- return false;
- }
-
- return SetBluetoothState(false);
-}
-
-bool BluetoothRadio::IsEnabled() const {
- return IsAdapterValid() && IsInDesiredState(true);
-}
-
-bool BluetoothRadio::Toggle() {
- if (!SaveOriginalState()) {
- return false;
- }
-
- if (!SetBluetoothState(false)) {
- NEARBY_LOG(INFO, "BT Toggle: Failed to turn BT off.");
- return false;
- }
-
- if (SystemClock::Sleep(kPauseBetweenToggle).Raised(Exception::kInterrupted)) {
- NEARBY_LOG(INFO, "BT Toggle: interrupted before turing on.");
- return false;
- }
-
- if (!SetBluetoothState(true)) {
- NEARBY_LOG(INFO, "BT Toggle: Failed to turn BT on.");
- return false;
- }
-
- return true;
-}
-
-bool BluetoothRadio::SetBluetoothState(bool enable) {
- return bluetooth_adapter_.SetStatus(
- enable ? BluetoothAdapter::Status::kEnabled
- : BluetoothAdapter::Status::kDisabled);
-}
-
-bool BluetoothRadio::IsInDesiredState(bool should_be_enabled) const {
- return bluetooth_adapter_.IsEnabled() == should_be_enabled;
-}
-
-bool BluetoothRadio::SaveOriginalState() {
- if (!IsAdapterValid()) {
- return false;
- }
-
- // If we haven't saved the original state of the radio, save it.
- if (!ever_saved_state_.Set(true)) {
- originally_enabled_.Set(bluetooth_adapter_.IsEnabled());
- }
-
- return true;
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/bluetooth_radio.h b/chromium/third_party/nearby/src/cpp/core/internal/mediums/bluetooth_radio.h
deleted file mode 100644
index 59ee3f7d572..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/bluetooth_radio.h
+++ /dev/null
@@ -1,90 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_MEDIUMS_BLUETOOTH_RADIO_H_
-#define CORE_INTERNAL_MEDIUMS_BLUETOOTH_RADIO_H_
-
-#include <cstdint>
-
-#include "absl/time/clock.h"
-#include "platform/public/atomic_boolean.h"
-#include "platform/public/bluetooth_adapter.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Provides the operations that can be performed on the Bluetooth radio.
-class BluetoothRadio {
- public:
- BluetoothRadio();
- BluetoothRadio(BluetoothRadio&&) = default;
- BluetoothRadio& operator=(BluetoothRadio&&) = default;
-
- // Reverts the Bluetooth radio to its original state.
- ~BluetoothRadio();
-
- // Enables Bluetooth.
- //
- // This must be called before attempting to invoke any other methods of
- // this class.
- //
- // Returns true if enabled successfully.
- bool Enable();
-
- // Disables Bluetooth.
- //
- // Returns true if disabled successfully.
- bool Disable();
-
- // Returns true if the Bluetooth radio is currently enabled.
- bool IsEnabled() const;
-
- // Turn BT radio Off, delay for kPauseBetweenToggle and then turn it On.
- // This will block calling thread for at least kPauseBetweenToggle duration.
- bool Toggle();
-
- // Returns result of BluetoothAdapter::IsValid() for private adapter instance.
- bool IsAdapterValid() const { return bluetooth_adapter_.IsValid(); }
-
- BluetoothAdapter& GetBluetoothAdapter() { return bluetooth_adapter_; }
-
- private:
- static constexpr absl::Duration kPauseBetweenToggle = absl::Seconds(3);
-
- bool SetBluetoothState(bool enable);
- bool IsInDesiredState(bool should_be_enabled) const;
- // To be called in enable(), disable(), and toggle(). This will remember the
- // original state of the radio before any radio state has been modified.
- // Returns false if Bluetooth doesn't exist on the device and the state cannot
- // be obtained.
- bool SaveOriginalState();
-
- // BluetoothAdapter::IsValid() will return false if BT is not supported.
- BluetoothAdapter bluetooth_adapter_;
-
- // The Bluetooth radio's original state, before we modified it. True if
- // originally enabled, false if originally disabled.
- // We restore the radio to its original state in the destructor.
-
- AtomicBoolean originally_enabled_{false};
- // false if we never modified the radio state, true otherwise.
- AtomicBoolean ever_saved_state_{false};
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_MEDIUMS_BLUETOOTH_RADIO_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/bluetooth_radio_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/bluetooth_radio_test.cc
deleted file mode 100644
index 1a10383dd71..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/bluetooth_radio_test.cc
+++ /dev/null
@@ -1,59 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/bluetooth_radio.h"
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-
-TEST(BluetoothRadioTest, ConstructorDestructorWorks) {
- BluetoothRadio radio;
- EXPECT_TRUE(radio.IsAdapterValid());
-}
-
-TEST(BluetoothRadioTest, CanEnable) {
- BluetoothRadio radio;
- EXPECT_TRUE(radio.IsAdapterValid());
- EXPECT_FALSE(radio.IsEnabled());
- EXPECT_TRUE(radio.Enable());
- EXPECT_TRUE(radio.IsEnabled());
-}
-
-TEST(BluetoothRadioTest, CanDisable) {
- BluetoothRadio radio;
- EXPECT_TRUE(radio.IsAdapterValid());
- EXPECT_FALSE(radio.IsEnabled());
- EXPECT_TRUE(radio.Enable());
- EXPECT_TRUE(radio.IsEnabled());
- EXPECT_TRUE(radio.Disable());
- EXPECT_FALSE(radio.IsEnabled());
-}
-
-TEST(BluetoothRadioTest, CanToggle) {
- BluetoothRadio radio;
- EXPECT_TRUE(radio.IsAdapterValid());
- EXPECT_FALSE(radio.IsEnabled());
- EXPECT_TRUE(radio.Toggle());
- EXPECT_TRUE(radio.IsEnabled());
-}
-
-} // namespace
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/lost_entity_tracker.h b/chromium/third_party/nearby/src/cpp/core/internal/mediums/lost_entity_tracker.h
deleted file mode 100644
index b589155e7ac..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/lost_entity_tracker.h
+++ /dev/null
@@ -1,94 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_MEDIUMS_LOST_ENTITY_TRACKER_H_
-#define CORE_INTERNAL_MEDIUMS_LOST_ENTITY_TRACKER_H_
-
-#include "absl/container/flat_hash_set.h"
-#include "platform/public/mutex.h"
-#include "platform/public/mutex_lock.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-// Tracks "lost" entities based on a manual update/compute model. Used by
-// mediums that only report found devices. Lost entities are computed based off
-// of whether a specific entity was rediscovered since the last call to
-// ComputeLostEntities.
-//
-// Note: Entity must overload the < and == operators.
-template <typename Entity>
-class LostEntityTracker {
- public:
- using EntitySet = absl::flat_hash_set<Entity>;
-
- LostEntityTracker();
- ~LostEntityTracker();
-
- // Records the given entity as being recently found, whether or not this is
- // our first time discovering the entity.
- void RecordFoundEntity(const Entity& entity) ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Computes and returns the set of entities considered lost since the last
- // time this method was called.
- EntitySet ComputeLostEntities() ABSL_LOCKS_EXCLUDED(mutex_);
-
- private:
- Mutex mutex_;
- EntitySet current_entities_ ABSL_GUARDED_BY(mutex_);
- EntitySet previously_found_entities_ ABSL_GUARDED_BY(mutex_);
-};
-
-template <typename Entity>
-LostEntityTracker<Entity>::LostEntityTracker()
- : current_entities_{}, previously_found_entities_{} {}
-
-template <typename Entity>
-LostEntityTracker<Entity>::~LostEntityTracker() {
- previously_found_entities_.clear();
- current_entities_.clear();
-}
-
-template <typename Entity>
-void LostEntityTracker<Entity>::RecordFoundEntity(const Entity& entity) {
- MutexLock lock(&mutex_);
-
- current_entities_.insert(entity);
-}
-
-template <typename Entity>
-typename LostEntityTracker<Entity>::EntitySet
-LostEntityTracker<Entity>::ComputeLostEntities() {
- MutexLock lock(&mutex_);
-
- // The set of lost entities is the previously found set MINUS the currently
- // found set.
- for (const auto& item : current_entities_) {
- previously_found_entities_.erase(item);
- }
- auto lost_entities = std::move(previously_found_entities_);
- previously_found_entities_ = std::move(current_entities_);
- current_entities_ = {};
-
- return lost_entities;
-}
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_MEDIUMS_LOST_ENTITY_TRACKER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/lost_entity_tracker_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/lost_entity_tracker_test.cc
deleted file mode 100644
index 0c934e73f74..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/lost_entity_tracker_test.cc
+++ /dev/null
@@ -1,137 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/lost_entity_tracker.h"
-
-#include "gtest/gtest.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-namespace {
-
-struct TestEntity {
- int id;
-
- template <typename H>
- friend H AbslHashValue(H h, const TestEntity& test_entity) {
- return H::combine(std::move(h), test_entity.id);
- }
-
- bool operator==(const TestEntity& other) const { return id == other.id; }
- bool operator<(const TestEntity& other) const { return id < other.id; }
-};
-
-TEST(LostEntityTrackerTest, NoEntitiesLost) {
- LostEntityTracker<TestEntity> lost_entity_tracker;
- TestEntity entity_1{1};
- TestEntity entity_2{2};
- TestEntity entity_3{3};
-
- // Discover some entities.
- lost_entity_tracker.RecordFoundEntity(entity_1);
- lost_entity_tracker.RecordFoundEntity(entity_2);
- lost_entity_tracker.RecordFoundEntity(entity_3);
-
- // Make sure none are lost on the first round.
- ASSERT_TRUE(lost_entity_tracker.ComputeLostEntities().empty());
-
- // Rediscover the same entities.
- lost_entity_tracker.RecordFoundEntity(entity_1);
- lost_entity_tracker.RecordFoundEntity(entity_2);
- lost_entity_tracker.RecordFoundEntity(entity_3);
-
- // Make sure we still didn't lose any entities.
- EXPECT_TRUE(lost_entity_tracker.ComputeLostEntities().empty());
-}
-
-TEST(LostEntityTrackerTest, AllEntitiesLost) {
- LostEntityTracker<TestEntity> lost_entity_tracker;
- TestEntity entity_1{1};
- TestEntity entity_2{2};
- TestEntity entity_3{3};
-
- // Discover some entities.
- lost_entity_tracker.RecordFoundEntity(entity_1);
- lost_entity_tracker.RecordFoundEntity(entity_2);
- lost_entity_tracker.RecordFoundEntity(entity_3);
-
- // Make sure none are lost on the first round.
- EXPECT_TRUE(lost_entity_tracker.ComputeLostEntities().empty());
-
- // Go through a round without rediscovering any entities.
- typename LostEntityTracker<TestEntity>::EntitySet lost_entities =
- lost_entity_tracker.ComputeLostEntities();
- EXPECT_TRUE(lost_entities.find(entity_1) != lost_entities.end());
- EXPECT_TRUE(lost_entities.find(entity_2) != lost_entities.end());
- EXPECT_TRUE(lost_entities.find(entity_3) != lost_entities.end());
-}
-
-TEST(LostEntityTrackerTest, SomeEntitiesLost) {
- LostEntityTracker<TestEntity> lost_entity_tracker;
- TestEntity entity_1{1};
- TestEntity entity_2{2};
- TestEntity entity_3{3};
-
- // Discover some entities.
- lost_entity_tracker.RecordFoundEntity(entity_1);
- lost_entity_tracker.RecordFoundEntity(entity_2);
-
- // Make sure none are lost on the first round.
- EXPECT_TRUE(lost_entity_tracker.ComputeLostEntities().empty());
-
- // Go through the next round only rediscovering one of our entities and
- // discovering an additional entity as well. Then, verify that only one entity
- // was lost after the check.
- lost_entity_tracker.RecordFoundEntity(entity_1);
- lost_entity_tracker.RecordFoundEntity(entity_3);
- typename LostEntityTracker<TestEntity>::EntitySet lost_entities =
- lost_entity_tracker.ComputeLostEntities();
- EXPECT_TRUE(lost_entities.find(entity_1) == lost_entities.end());
- EXPECT_TRUE(lost_entities.find(entity_2) != lost_entities.end());
- EXPECT_TRUE(lost_entities.find(entity_3) == lost_entities.end());
-}
-
-TEST(LostEntityTrackerTest, SameEntityMultipleCopies) {
- LostEntityTracker<TestEntity> lost_entity_tracker;
- TestEntity entity_1{1};
- TestEntity entity_1_copy{1};
-
- // Discover an entity.
- lost_entity_tracker.RecordFoundEntity(entity_1);
-
- // Make sure none are lost on the first round.
- EXPECT_TRUE(lost_entity_tracker.ComputeLostEntities().empty());
-
- // Rediscover the same entity, but through a copy of it.
- lost_entity_tracker.RecordFoundEntity(entity_1_copy);
-
- // Make sure none are lost on the second round.
- EXPECT_TRUE(lost_entity_tracker.ComputeLostEntities().empty());
-
- // Go through a round without rediscovering any entities and verify that we
- // lost an entity equivalent to both copies of it.
- typename LostEntityTracker<TestEntity>::EntitySet lost_entities =
- lost_entity_tracker.ComputeLostEntities();
- EXPECT_EQ(lost_entities.size(), 1);
- EXPECT_TRUE(lost_entities.find(entity_1) != lost_entities.end());
- EXPECT_TRUE(lost_entities.find(entity_1_copy) != lost_entities.end());
-}
-
-} // namespace
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/mediums.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/mediums.cc
deleted file mode 100644
index 8b0b3100ecf..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/mediums.cc
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/mediums.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-BluetoothRadio& Mediums::GetBluetoothRadio() { return bluetooth_radio_; }
-
-BluetoothClassic& Mediums::GetBluetoothClassic() { return bluetooth_classic_; }
-
-Ble& Mediums::GetBle() { return ble_; }
-
-WifiLan& Mediums::GetWifiLan() { return wifi_lan_; }
-
-mediums::WebRtc& Mediums::GetWebRtc() { return webrtc_; }
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/mediums.h b/chromium/third_party/nearby/src/cpp/core/internal/mediums/mediums.h
deleted file mode 100644
index 4c6127eb957..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/mediums.h
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_MEDIUMS_MEDIUMS_H_
-#define CORE_INTERNAL_MEDIUMS_MEDIUMS_H_
-
-#include "core/internal/mediums/ble.h"
-#include "core/internal/mediums/bluetooth_classic.h"
-#include "core/internal/mediums/bluetooth_radio.h"
-#include "core/internal/mediums/webrtc.h"
-#include "core/internal/mediums/wifi_lan.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Facilitates convenient and reliable usage of various wireless mediums.
-class Mediums {
- public:
- Mediums() = default;
- ~Mediums() = default;
-
- // Returns a handle to the Bluetooth radio.
- BluetoothRadio& GetBluetoothRadio();
-
- // Returns a handle to the Bluetooth Classic medium.
- BluetoothClassic& GetBluetoothClassic();
-
- // Returns a handle to the Ble medium.
- Ble& GetBle();
-
- // Returns a handle to the Wifi-Lan medium.
- WifiLan& GetWifiLan();
-
- // Returns a handle to the WebRtc medium.
- mediums::WebRtc& GetWebRtc();
-
- private:
- // The order of declaration is critical for both construction and
- // destruction.
- //
- // 1) Construction: The individual mediums have a dependency on the
- // corresponding radio, so the radio must be initialized first.
- //
- // 2) Destruction: The individual mediums should be shut down before the
- // corresponding radio.
- BluetoothRadio bluetooth_radio_;
- BluetoothClassic bluetooth_classic_{bluetooth_radio_};
- Ble ble_{bluetooth_radio_};
- WifiLan wifi_lan_;
- mediums::WebRtc webrtc_;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_MEDIUMS_MEDIUMS_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/utils.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/utils.cc
deleted file mode 100644
index 11b581f7710..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/utils.cc
+++ /dev/null
@@ -1,94 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/utils.h"
-
-#include <memory>
-#include <string>
-
-#include "platform/base/prng.h"
-#include "platform/public/crypto.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-namespace {
-constexpr absl::string_view kUpgradeServiceIdPostfix = "_UPGRADE";
-}
-
-ByteArray Utils::GenerateRandomBytes(size_t length) {
- Prng rng;
- std::string data;
- data.reserve(length);
-
- // Adds 4 random bytes per iteration.
- while (length > 0) {
- std::uint32_t val = rng.NextUint32();
- for (int i = 0; i < 4; i++) {
- data += val & 0xFF;
- val >>= 8;
- length--;
-
- if (!length) break;
- }
- }
-
- return ByteArray(data);
-}
-
-ByteArray Utils::Sha256Hash(const ByteArray& source, size_t length) {
- return Utils::Sha256Hash(std::string(source), length);
-}
-
-ByteArray Utils::Sha256Hash(const std::string& source, size_t length) {
- ByteArray full_hash(length);
- full_hash.CopyAt(0, Crypto::Sha256(source));
- return full_hash;
-}
-
-std::string Utils::WrapUpgradeServiceId(const std::string& service_id) {
- if (service_id.empty()) {
- return {};
- }
- return service_id + std::string(kUpgradeServiceIdPostfix);
-}
-
-std::string Utils::UnwrapUpgradeServiceId(
- const std::string& upgrade_service_id) {
- auto pos = upgrade_service_id.find(std::string(kUpgradeServiceIdPostfix));
- if (pos != std::string::npos) {
- return std::string(upgrade_service_id, 0, pos);
- }
- return upgrade_service_id;
-}
-
-LocationHint Utils::BuildLocationHint(const std::string& location) {
- LocationHint location_hint;
- location_hint.set_format(LocationStandard::UNKNOWN);
-
- if (!location.empty()) {
- location_hint.set_location(location);
- if (location.at(0) == '+') {
- location_hint.set_format(LocationStandard::E164_CALLING);
- } else {
- location_hint.set_format(LocationStandard::ISO_3166_1_ALPHA_2);
- }
- }
- return location_hint;
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/utils.h b/chromium/third_party/nearby/src/cpp/core/internal/mediums/utils.h
deleted file mode 100644
index 4a26c4e82c6..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/utils.h
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_MEDIUMS_UTILS_H_
-#define CORE_INTERNAL_MEDIUMS_UTILS_H_
-
-#include <memory>
-#include <string>
-
-#include "platform/base/byte_array.h"
-#include "proto/connections/offline_wire_formats.pb.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-class Utils {
- public:
- static ByteArray GenerateRandomBytes(size_t length);
- static ByteArray Sha256Hash(const ByteArray& source, size_t length);
- static ByteArray Sha256Hash(const std::string& source, size_t length);
- static std::string WrapUpgradeServiceId(const std::string& service_id);
- static std::string UnwrapUpgradeServiceId(const std::string& service_id);
- static LocationHint BuildLocationHint(const std::string& location);
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_MEDIUMS_UTILS_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/uuid.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/uuid.cc
deleted file mode 100644
index e3c171598fd..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/uuid.cc
+++ /dev/null
@@ -1,87 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/uuid.h"
-
-#include <iomanip>
-#include <sstream>
-
-#include "platform/public/crypto.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-std::ostream& write_hex(std::ostream& os, absl::string_view data) {
- for (const auto b : data) {
- os << std::setfill('0') << std::setw(2) << std::hex
- << (static_cast<unsigned int>(b) & 0x0ff);
- }
- return os;
-}
-} // namespace
-
-Uuid::Uuid(absl::string_view data) : data_(Crypto::Md5(data)) {
- // Based on the Java counterpart at
- // http://androidxref.com/8.0.0_r4/xref/libcore/ojluni/src/main/java/java/util/UUID.java#162.
- data_[6] &= 0x0f; // Clear version.
- data_[6] |= 0x30; // Set to version 3.
- data_[8] &= 0x3f; // Clear variant.
- data_[8] |= 0x80; // Set to IETF variant.
-}
-
-Uuid::Uuid(std::uint64_t most_sig_bits, std::uint64_t least_sig_bits) {
- // Base on the Java counterpart at
- // http://androidxref.com/8.0.0_r4/xref/libcore/ojluni/src/main/java/java/util/UUID.java#104.
- data_.reserve(sizeof(most_sig_bits) + sizeof(least_sig_bits));
-
- data_[0] = static_cast<char>((most_sig_bits >> 56) & 0x0ff);
- data_[1] = static_cast<char>((most_sig_bits >> 48) & 0x0ff);
- data_[2] = static_cast<char>((most_sig_bits >> 40) & 0x0ff);
- data_[3] = static_cast<char>((most_sig_bits >> 32) & 0x0ff);
- data_[4] = static_cast<char>((most_sig_bits >> 24) & 0x0ff);
- data_[5] = static_cast<char>((most_sig_bits >> 16) & 0x0ff);
- data_[6] = static_cast<char>((most_sig_bits >> 8) & 0x0ff);
- data_[7] = static_cast<char>((most_sig_bits >> 0) & 0x0ff);
-
- data_[8] = static_cast<char>((least_sig_bits >> 56) & 0x0ff);
- data_[9] = static_cast<char>((least_sig_bits >> 48) & 0x0ff);
- data_[10] = static_cast<char>((least_sig_bits >> 40) & 0x0ff);
- data_[11] = static_cast<char>((least_sig_bits >> 32) & 0x0ff);
- data_[12] = static_cast<char>((least_sig_bits >> 24) & 0x0ff);
- data_[13] = static_cast<char>((least_sig_bits >> 16) & 0x0ff);
- data_[14] = static_cast<char>((least_sig_bits >> 8) & 0x0ff);
- data_[15] = static_cast<char>((least_sig_bits >> 0) & 0x0ff);
-}
-
-Uuid::operator std::string() const {
- // Based on the Java counterpart at
- // http://androidxref.com/8.0.0_r4/xref/libcore/ojluni/src/main/java/java/util/UUID.java#375.
- std::ostringstream md5_hex;
- write_hex(md5_hex, absl::string_view(&data_[0], 4));
- md5_hex << "-";
- write_hex(md5_hex, absl::string_view(&data_[4], 2));
- md5_hex << "-";
- write_hex(md5_hex, absl::string_view(&data_[6], 2));
- md5_hex << "-";
- write_hex(md5_hex, absl::string_view(&data_[8], 2));
- md5_hex << "-";
- write_hex(md5_hex, absl::string_view(&data_[10], 6));
-
- return md5_hex.str();
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/uuid_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/uuid_test.cc
deleted file mode 100644
index f5a8303265d..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/uuid_test.cc
+++ /dev/null
@@ -1,70 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/uuid.h"
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "platform/public/crypto.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-
-constexpr absl::string_view kString{"some string"};
-constexpr std::uint64_t kNum1 = 0x123456789abcdef0;
-constexpr std::uint64_t kNum2 = 0x21436587a9cbed0f;
-
-TEST(UuidTest, CreateFromStringWithMd5) {
- Uuid uuid(kString);
- std::string uuid_str(uuid);
- std::string uuid_data(uuid.data());
- std::string md5_data(Crypto::Md5(kString));
- NEARBY_LOG(INFO, "MD5-based UUID: '%s'", uuid_str.c_str());
- uuid_data[6] = 0;
- uuid_data[8] = 0;
- md5_data[6] = 0;
- md5_data[8] = 0;
- EXPECT_EQ(md5_data, uuid_data);
-}
-
-TEST(UuidTest, CreateFromBinary) {
- Uuid uuid(kNum1, kNum2);
- std::string uuid_data(uuid.data());
- std::string uuid_str(uuid);
- NEARBY_LOG(INFO, "UUID: '%s'", uuid_str.c_str());
- EXPECT_EQ(uuid_data[0], (kNum1 >> 56) & 0xFF);
- EXPECT_EQ(uuid_data[1], (kNum1 >> 48) & 0xFF);
- EXPECT_EQ(uuid_data[2], (kNum1 >> 40) & 0xFF);
- EXPECT_EQ(uuid_data[3], (kNum1 >> 32) & 0xFF);
- EXPECT_EQ(uuid_data[4], (kNum1 >> 24) & 0xFF);
- EXPECT_EQ(uuid_data[5], (kNum1 >> 16) & 0xFF);
- EXPECT_EQ(uuid_data[6], (kNum1 >> 8) & 0xFF);
- EXPECT_EQ(uuid_data[7], (kNum1 >> 0) & 0xFF);
- EXPECT_EQ(uuid_data[8], (kNum2 >> 56) & 0xFF);
- EXPECT_EQ(uuid_data[9], (kNum2 >> 48) & 0xFF);
- EXPECT_EQ(uuid_data[10], (kNum2 >> 40) & 0xFF);
- EXPECT_EQ(uuid_data[11], (kNum2 >> 32) & 0xFF);
- EXPECT_EQ(uuid_data[12], (kNum2 >> 24) & 0xFF);
- EXPECT_EQ(uuid_data[13], (kNum2 >> 16) & 0xFF);
- EXPECT_EQ(uuid_data[14], (kNum2 >> 8) & 0xFF);
- EXPECT_EQ(uuid_data[15], (kNum2 >> 0) & 0xFF);
-}
-
-} // namespace
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc.cc
deleted file mode 100644
index 1edcf63965a..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc.cc
+++ /dev/null
@@ -1,744 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/webrtc.h"
-
-#include <functional>
-#include <memory>
-
-#include "absl/functional/bind_front.h"
-#include "absl/strings/str_cat.h"
-#include "absl/time/time.h"
-#include "core/internal/mediums/webrtc/session_description_wrapper.h"
-#include "core/internal/mediums/webrtc/signaling_frames.h"
-#include "core/internal/mediums/webrtc_socket_wrapper.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/listeners.h"
-#include "platform/public/cancelable_alarm.h"
-#include "platform/public/future.h"
-#include "platform/public/logging.h"
-#include "platform/public/mutex_lock.h"
-#include "proto/mediums/web_rtc_signaling_frames.pb.h"
-#include "webrtc/api/jsep.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-namespace {
-
-// The maximum amount of time to wait to connect to a data channel via WebRTC.
-constexpr absl::Duration kDataChannelTimeout = absl::Seconds(10);
-
-// Delay between restarting signaling messenger to receive messages.
-constexpr absl::Duration kRestartReceiveMessagesDuration = absl::Seconds(60);
-
-} // namespace
-
-WebRtc::WebRtc() = default;
-
-WebRtc::~WebRtc() {
- // This ensures that all pending callbacks are run before we reset the medium
- // and we are not accepting new runnables.
- single_thread_executor_.Shutdown();
-
- // Stop accepting all connections
- absl::flat_hash_set<std::string> service_ids;
- for (auto& item : accepting_connections_info_) {
- service_ids.emplace(item.first);
- }
- for (const auto& service_id : service_ids) {
- StopAcceptingConnections(service_id);
- }
-}
-
-const std::string WebRtc::GetDefaultCountryCode() {
- return medium_.GetDefaultCountryCode();
-}
-
-bool WebRtc::IsAvailable() { return medium_.IsValid(); }
-
-bool WebRtc::IsAcceptingConnections(const std::string& service_id) {
- MutexLock lock(&mutex_);
- return IsAcceptingConnectionsLocked(service_id);
-}
-
-bool WebRtc::IsAcceptingConnectionsLocked(const std::string& service_id) {
- return accepting_connections_info_.contains(service_id);
-}
-
-bool WebRtc::StartAcceptingConnections(const std::string& service_id,
- const WebrtcPeerId& self_peer_id,
- const LocationHint& location_hint,
- AcceptedConnectionCallback callback) {
- MutexLock lock(&mutex_);
- if (!IsAvailable()) {
- NEARBY_LOG(WARNING,
- "Cannot start accepting WebRTC connections because WebRTC is "
- "not available.");
- return false;
- }
-
- if (IsAcceptingConnectionsLocked(service_id)) {
- NEARBY_LOG(WARNING,
- "Cannot start accepting WebRTC connections because service %s "
- "is already accepting WebRTC connections.",
- service_id.c_str());
- return false;
- }
-
- // We'll track our state here, so that we're separated from the other services
- // who may be also using WebRTC.
- AcceptingConnectionsInfo info = AcceptingConnectionsInfo();
- info.self_peer_id = self_peer_id;
- info.accepted_connection_callback = callback;
-
- // Create a new SignalingMessenger so that we can communicate w/ Tachyon.
- info.signaling_messenger =
- medium_.GetSignalingMessenger(self_peer_id.GetId(), location_hint);
- if (!info.signaling_messenger->IsValid()) {
- return false;
- }
-
- // This registers ourselves w/ Tachyon, creating a room from the PeerId.
- // This allows a remote device to message us over Tachyon.
- if (!info.signaling_messenger->StartReceivingMessages(
- absl::bind_front(&WebRtc::OnSignalingMessage, this, service_id),
- absl::bind_front(&WebRtc::OnSignalingComplete, this, service_id))) {
- info.signaling_messenger.reset();
- return false;
- }
-
- // We'll automatically disconnect from Tachyon after 60sec. When this alarm
- // fires, we'll recreate our room so we continue to receive messages.
- info.restart_tachyon_receive_messages_alarm = CancelableAlarm(
- "restart_receiving_messages_webrtc",
- std::bind(&WebRtc::ProcessRestartTachyonReceiveMessages, this,
- service_id),
- kRestartReceiveMessagesDuration, &single_thread_executor_);
-
- // Now that we're set up to receive messages, we'll save our state and return
- // a successful result.
- accepting_connections_info_.emplace(service_id, std::move(info));
- NEARBY_LOG(INFO,
- "Started listening for WebRTC connections as %s on service %s",
- self_peer_id.GetId().c_str(), service_id.c_str());
- return true;
-}
-
-void WebRtc::StopAcceptingConnections(const std::string& service_id) {
- MutexLock lock(&mutex_);
- if (!IsAcceptingConnectionsLocked(service_id)) {
- NEARBY_LOG(WARNING,
- "Cannot stop accepting WebRTC connections because service %s "
- "is not accepting WebRTC connections.",
- service_id.c_str());
- return;
- }
-
- // Grab our info from the map.
- auto& info = accepting_connections_info_.find(service_id)->second;
-
- // Stop receiving messages from Tachyon.
- info.signaling_messenger->StopReceivingMessages();
- info.signaling_messenger.reset();
-
- // Cancel the scheduled alarm.
- if (info.restart_tachyon_receive_messages_alarm.IsValid()) {
- info.restart_tachyon_receive_messages_alarm.Cancel();
- info.restart_tachyon_receive_messages_alarm = CancelableAlarm();
- }
-
- // If we had any in-progress connections that haven't materialized into full
- // DataChannels yet, it's time to shut them down since they can't reach us
- // anymore.
- absl::flat_hash_set<std::string> peer_ids;
- for (auto& item : connection_flows_) {
- peer_ids.emplace(item.first);
- }
- for (const auto& peer_id : peer_ids) {
- const auto& entry = connection_flows_.find(peer_id);
- // Skip outgoing connections in this step. Start/StopAcceptingConnections
- // only deals with incoming connections.
- if (requesting_connections_info_.contains(peer_id)) {
- continue;
- }
-
- // Skip fully connected connections in this step. If the connection was
- // formed while we were accepting connections, then it will stay alive until
- // it's explicitly closed.
- if (!entry->second->CloseIfNotConnected()) {
- continue;
- }
-
- connection_flows_.erase(peer_id);
- }
-
- // Clean up our state. We're now no longer listening for connections.
- accepting_connections_info_.erase(service_id);
- NEARBY_LOG(INFO, "Stopped listening for WebRTC connections for service %s",
- service_id.c_str());
-}
-
-WebRtcSocketWrapper WebRtc::Connect(const std::string& service_id,
- const WebrtcPeerId& remote_peer_id,
- const LocationHint& location_hint,
- CancellationFlag* cancellation_flag) {
- for (int attempts_count = 0; attempts_count < kConnectAttemptsLimit;
- attempts_count++) {
- auto wrapper_result = AttemptToConnect(service_id, remote_peer_id,
- location_hint, cancellation_flag);
- if (wrapper_result.IsValid()) {
- return wrapper_result;
- }
- }
- return WebRtcSocketWrapper();
-}
-
-WebRtcSocketWrapper WebRtc::AttemptToConnect(
- const std::string& service_id, const WebrtcPeerId& remote_peer_id,
- const LocationHint& location_hint, CancellationFlag* cancellation_flag) {
- ConnectionRequestInfo info = ConnectionRequestInfo();
- info.self_peer_id = WebrtcPeerId::FromRandom();
- Future<WebRtcSocketWrapper> socket_future = info.socket_future;
-
- {
- MutexLock lock(&mutex_);
- if (!IsAvailable()) {
- NEARBY_LOG(
- WARNING,
- "Cannot connect to WebRTC peer %s because WebRTC is not available.",
- remote_peer_id.GetId().c_str());
- return WebRtcSocketWrapper();
- }
-
- if (cancellation_flag->Cancelled()) {
- NEARBY_LOGS(INFO) << "Cannot connect with WebRtc due to cancel.";
- return WebRtcSocketWrapper();
- }
-
- // Create a new ConnectionFlow for this connection attempt.
- std::unique_ptr<ConnectionFlow> connection_flow =
- CreateConnectionFlow(service_id, remote_peer_id);
- if (!connection_flow) {
- NEARBY_LOG(
- INFO,
- "Cannot connect to WebRTC peer %s because we failed to create a "
- "ConnectionFlow.",
- remote_peer_id.GetId().c_str());
- return WebRtcSocketWrapper();
- }
-
- // Create a new SignalingMessenger so that we can communicate over Tachyon.
- info.signaling_messenger =
- medium_.GetSignalingMessenger(info.self_peer_id.GetId(), location_hint);
- if (!info.signaling_messenger->IsValid()) {
- NEARBY_LOG(
- INFO,
- "Cannot connect to WebRTC peer %s because we failed to create a "
- "SignalingMessenger.",
- remote_peer_id.GetId().c_str());
- return WebRtcSocketWrapper();
- }
-
- // This registers ourselves w/ Tachyon, creating a room from the PeerId.
- // This allows a remote device to message us over Tachyon.
- auto signaling_complete_callback = [socket_future](bool success) mutable {
- if (!success) {
- socket_future.SetException({Exception::kFailed});
- }
- };
- if (!info.signaling_messenger->StartReceivingMessages(
- absl::bind_front(&WebRtc::OnSignalingMessage, this, service_id),
- signaling_complete_callback)) {
- NEARBY_LOG(INFO,
- "Cannot connect to WebRTC peer %s because we failed to start "
- "receiving messages over Tachyon.",
- remote_peer_id.GetId().c_str());
- info.signaling_messenger.reset();
- return WebRtcSocketWrapper();
- }
-
- // Poke the remote device. This will cause them to send us an Offer.
- if (!info.signaling_messenger->SendMessage(
- remote_peer_id.GetId(),
- webrtc_frames::EncodeReadyForSignalingPoke(info.self_peer_id))) {
- NEARBY_LOG(INFO,
- "Cannot connect to WebRTC peer %s because we failed to poke "
- "the peer over Tachyon.",
- remote_peer_id.GetId().c_str());
- info.signaling_messenger.reset();
- return WebRtcSocketWrapper();
- }
-
- // Create a new ConnectionRequest entry. This map will be used later to look
- // up state as we negotiate the connection over Tachyon.
- requesting_connections_info_.emplace(remote_peer_id.GetId(),
- std::move(info));
- connection_flows_.emplace(remote_peer_id.GetId(),
- std::move(connection_flow));
- }
-
- // Wait for the connection to go through. Don't hold the mutex here so that
- // we're not blocking necessary operations.
- ExceptionOr<WebRtcSocketWrapper> socket_result =
- socket_future.Get(kDataChannelTimeout);
-
- {
- MutexLock lock(&mutex_);
-
- // Reclaim our info, since we had released ownership while talking to
- // Tachyon.
- auto& info =
- requesting_connections_info_.find(remote_peer_id.GetId())->second;
-
- // Verify that the connection went through.
- if (!socket_result.ok()) {
- NEARBY_LOG(INFO, "Failed to connect to WebRTC peer %s.",
- remote_peer_id.GetId().c_str());
- RemoveConnectionFlow(remote_peer_id);
- info.signaling_messenger.reset();
- requesting_connections_info_.erase(remote_peer_id.GetId());
- return WebRtcSocketWrapper();
- }
-
- // Clean up our ConnectionRequest.
- info.signaling_messenger.reset();
- requesting_connections_info_.erase(remote_peer_id.GetId());
-
- // Return the result.
- return socket_result.GetResult();
- }
-}
-
-void WebRtc::ProcessLocalIceCandidate(
- const std::string& service_id, const WebrtcPeerId& remote_peer_id,
- const ::location::nearby::mediums::IceCandidate ice_candidate) {
- MutexLock lock(&mutex_);
-
- // Check first if we have an outgoing request w/ this peer. As this request is
- // tied to a specific peer, it takes precedence.
- const auto& connection_request_entry =
- requesting_connections_info_.find(remote_peer_id.GetId());
- if (connection_request_entry != requesting_connections_info_.end()) {
- // Pass the ice candidate to the remote side.
- if (!connection_request_entry->second.signaling_messenger->SendMessage(
- remote_peer_id.GetId(),
- webrtc_frames::EncodeIceCandidates(
- connection_request_entry->second.self_peer_id,
- {ice_candidate}))) {
- NEARBY_LOG(INFO, "Failed to send ice candidate to %s.",
- remote_peer_id.GetId().c_str());
- }
-
- NEARBY_LOG(INFO, "Sent ice candidate to %s.",
- remote_peer_id.GetId().c_str());
- return;
- }
-
- // Check next if we're expecting incoming connection requests.
- const auto& accepting_connection_entry =
- accepting_connections_info_.find(service_id);
- if (accepting_connection_entry != accepting_connections_info_.end()) {
- // Pass the ice candidate to the remote side.
- // TODO(xlythe) Consider not blocking here, since this can eat into the
- // connection time
- if (!accepting_connection_entry->second.signaling_messenger->SendMessage(
- remote_peer_id.GetId(),
- webrtc_frames::EncodeIceCandidates(
- accepting_connection_entry->second.self_peer_id,
- {ice_candidate}))) {
- NEARBY_LOG(INFO, "Failed to send ice candidate to %s.",
- remote_peer_id.GetId().c_str());
- }
-
- NEARBY_LOG(INFO, "Sent ice candidate to %s.",
- remote_peer_id.GetId().c_str());
- return;
- }
-
- NEARBY_LOG(INFO,
- "Skipping restart listening for tachyon inbox messages since we "
- "are not accepting connections for service %s.",
- service_id.c_str());
-}
-
-void WebRtc::OnSignalingMessage(const std::string& service_id,
- const ByteArray& message) {
- OffloadFromThread("rtc-on-signaling-message", [this, service_id, message]() {
- ProcessTachyonInboxMessage(service_id, message);
- });
-}
-
-void WebRtc::OnSignalingComplete(const std::string& service_id, bool success) {
- NEARBY_LOG(INFO, "Signaling completed with status: %d.", success);
- if (success) {
- return;
- }
-
- OffloadFromThread("rtc-on-signaling-complete", [this, service_id]() {
- MutexLock lock(&mutex_);
- const auto& info_entry = accepting_connections_info_.find(service_id);
- if (info_entry == accepting_connections_info_.end()) {
- return;
- }
-
- if (info_entry->second.restart_accept_connections_count <
- kRestartAcceptConnectionsLimit) {
- ++info_entry->second.restart_accept_connections_count;
- } else {
- return;
- }
-
- RestartTachyonReceiveMessages(service_id);
- });
-}
-
-void WebRtc::ProcessTachyonInboxMessage(const std::string& service_id,
- const ByteArray& message) {
- MutexLock lock(&mutex_);
-
- // Attempt to parse the incoming message as a WebRtcSignalingFrame.
- location::nearby::mediums::WebRtcSignalingFrame frame;
- if (!frame.ParseFromString(std::string(message))) {
- NEARBY_LOG(WARNING, "Failed to parse signaling message.");
- return;
- }
-
- // Ensure that the frame is valid (no missing fields).
- if (!frame.has_sender_id()) {
- NEARBY_LOG(WARNING, "Invalid WebRTC frame: Sender ID is missing.");
- return;
- }
- WebrtcPeerId remote_peer_id = WebrtcPeerId(frame.sender_id().id());
-
- // Depending on the message type, we'll respond as appropriate.
- if (requesting_connections_info_.contains(remote_peer_id.GetId())) {
- // This is from a peer we have an outgoing connection request with, so we'll
- // only process the Answer path.
- if (frame.has_offer()) {
- ReceiveOffer(remote_peer_id,
- SessionDescriptionWrapper(
- webrtc_frames::DecodeOffer(frame).release()));
- SendAnswer(remote_peer_id);
- } else if (frame.has_ice_candidates()) {
- ReceiveIceCandidates(remote_peer_id,
- webrtc_frames::DecodeIceCandidates(frame));
- } else {
- NEARBY_LOG(INFO, "Received unknown WebRTC frame: ignoring.");
- }
- } else if (IsAcceptingConnectionsLocked(service_id)) {
- // We don't have an outgoing connection request with this peer, but we are
- // accepting incoming requests so we'll only process the Offer path.
- if (frame.has_ready_for_signaling_poke()) {
- SendOffer(service_id, remote_peer_id);
- } else if (frame.has_answer()) {
- ReceiveAnswer(remote_peer_id,
- SessionDescriptionWrapper(
- webrtc_frames::DecodeAnswer(frame).release()));
- } else if (frame.has_ice_candidates()) {
- ReceiveIceCandidates(remote_peer_id,
- webrtc_frames::DecodeIceCandidates(frame));
- } else {
- NEARBY_LOG(INFO, "Received unknown WebRTC frame: ignoring.");
- }
- } else {
- NEARBY_LOG(
- INFO,
- "Ignoring Tachyon message since we are not accepting connections.");
- }
-}
-
-void WebRtc::SendOffer(const std::string& service_id,
- const WebrtcPeerId& remote_peer_id) {
- std::unique_ptr<ConnectionFlow> connection_flow =
- CreateConnectionFlow(service_id, remote_peer_id);
- if (!connection_flow) {
- NEARBY_LOG(INFO,
- "Unable to send offer. Failed to create a ConnectionFlow.");
- return;
- }
-
- SessionDescriptionWrapper offer = connection_flow->CreateOffer();
- if (!offer.IsValid()) {
- NEARBY_LOG(INFO,
- "Unable to send offer. Failed to create our offer locally.");
- RemoveConnectionFlow(remote_peer_id);
- return;
- }
-
- const webrtc::SessionDescriptionInterface& sdp = offer.GetSdp();
- if (!connection_flow->SetLocalSessionDescription(offer)) {
- NEARBY_LOG(INFO,
- "Unable to send offer. Failed to register our offer locally.");
- RemoveConnectionFlow(remote_peer_id);
- return;
- }
-
- // Grab our info from the map.
- auto& info = accepting_connections_info_.find(service_id)->second;
-
- // Pass the offer to the remote side.
- if (!info.signaling_messenger->SendMessage(
- remote_peer_id.GetId(),
- webrtc_frames::EncodeOffer(info.self_peer_id, sdp))) {
- NEARBY_LOG(INFO,
- "Unable to send offer. Failed to write the offer to the remote "
- "peer %s.",
- remote_peer_id.GetId().c_str());
- RemoveConnectionFlow(remote_peer_id);
- return;
- }
-
- // Store the ConnectionFlow so that other methods can use it later.
- connection_flows_.emplace(remote_peer_id.GetId(), std::move(connection_flow));
- NEARBY_LOG(INFO, "Sent offer to %s.", remote_peer_id.GetId().c_str());
-}
-
-void WebRtc::ReceiveOffer(const WebrtcPeerId& remote_peer_id,
- SessionDescriptionWrapper offer) {
- const auto& entry = connection_flows_.find(remote_peer_id.GetId());
- if (entry == connection_flows_.end()) {
- NEARBY_LOG(INFO,
- "Unable to receive offer. Failed to create a ConnectionFlow.");
- return;
- }
-
- if (!entry->second->OnOfferReceived(offer)) {
- NEARBY_LOG(INFO, "Unable to receive offer. Failed to process the offer.");
- RemoveConnectionFlow(remote_peer_id);
- }
-}
-
-void WebRtc::SendAnswer(const WebrtcPeerId& remote_peer_id) {
- const auto& entry = connection_flows_.find(remote_peer_id.GetId());
- if (entry == connection_flows_.end()) {
- NEARBY_LOG(INFO,
- "Unable to send answer. Failed to create a ConnectionFlow.");
- return;
- }
-
- SessionDescriptionWrapper answer = entry->second->CreateAnswer();
- if (!answer.IsValid()) {
- NEARBY_LOG(INFO,
- "Unable to send answer. Failed to create our answer locally.");
- RemoveConnectionFlow(remote_peer_id);
- return;
- }
-
- const webrtc::SessionDescriptionInterface& sdp = answer.GetSdp();
- if (!entry->second->SetLocalSessionDescription(answer)) {
- NEARBY_LOG(INFO,
- "Unable to send answer. Failed to register our answer locally.");
- RemoveConnectionFlow(remote_peer_id);
- return;
- }
-
- // Grab our info from the map.
- const auto& connection_request_entry =
- requesting_connections_info_.find(remote_peer_id.GetId());
- if (connection_request_entry == requesting_connections_info_.end()) {
- NEARBY_LOG(INFO,
- "Unable to send answer. Failed to find an outgoing connection "
- "request.");
- RemoveConnectionFlow(remote_peer_id);
- return;
- }
-
- // Pass the answer to the remote side.
- if (!connection_request_entry->second.signaling_messenger->SendMessage(
- remote_peer_id.GetId(),
- webrtc_frames::EncodeAnswer(
- connection_request_entry->second.self_peer_id, sdp))) {
- NEARBY_LOG(
- INFO,
- "Unable to send answer. Failed to write the answer to the remote "
- "peer %s.",
- remote_peer_id.GetId().c_str());
- RemoveConnectionFlow(remote_peer_id);
- return;
- }
-
- NEARBY_LOG(INFO, "Sent answer to %s.", remote_peer_id.GetId().c_str());
-}
-
-void WebRtc::ReceiveAnswer(const WebrtcPeerId& remote_peer_id,
- SessionDescriptionWrapper answer) {
- const auto& entry = connection_flows_.find(remote_peer_id.GetId());
- if (entry == connection_flows_.end()) {
- NEARBY_LOG(INFO,
- "Unable to receive answer. Failed to create a ConnectionFlow.");
- return;
- }
-
- if (!entry->second->OnAnswerReceived(answer)) {
- NEARBY_LOG(INFO, "Unable to receive answer. Failed to process the answer.");
- RemoveConnectionFlow(remote_peer_id);
- }
-}
-
-void WebRtc::ReceiveIceCandidates(
- const WebrtcPeerId& remote_peer_id,
- std::vector<std::unique_ptr<webrtc::IceCandidateInterface>>
- ice_candidates) {
- const auto& entry = connection_flows_.find(remote_peer_id.GetId());
- if (entry == connection_flows_.end()) {
- NEARBY_LOG(
- INFO,
- "Unable to receive ice candidates. Failed to create a ConnectionFlow.");
- return;
- }
-
- entry->second->OnRemoteIceCandidatesReceived(std::move(ice_candidates));
-}
-
-void WebRtc::ProcessRestartTachyonReceiveMessages(
- const std::string& service_id) {
- MutexLock lock(&mutex_);
- RestartTachyonReceiveMessages(service_id);
-}
-
-void WebRtc::RestartTachyonReceiveMessages(const std::string& service_id) {
- if (!IsAcceptingConnectionsLocked(service_id)) {
- NEARBY_LOG(INFO,
- "Skipping restart listening for tachyon inbox messages since we "
- "are not accepting connections for service %s.",
- service_id.c_str());
- return;
- }
-
- // Grab our info from the map.
- auto& info = accepting_connections_info_.find(service_id)->second;
-
- // Ensure we've disconnected from Tachyon.
- info.signaling_messenger->StopReceivingMessages();
-
- // Attempt to re-register.
- if (!info.signaling_messenger->StartReceivingMessages(
- absl::bind_front(&WebRtc::OnSignalingMessage, this, service_id),
- absl::bind_front(&WebRtc::OnSignalingComplete, this, service_id))) {
- NEARBY_LOG(WARNING,
- "Failed to restart listening for tachyon inbox messages for "
- "service %s since we failed to reach Tachyon.",
- service_id.c_str());
- return;
- }
-
- NEARBY_LOG(INFO,
- "Successfully restarted listening for tachyon inbox messages on "
- "service %s.",
- service_id.c_str());
-}
-
-void WebRtc::ProcessDataChannelOpen(const std::string& service_id,
- const WebrtcPeerId& remote_peer_id,
- WebRtcSocketWrapper socket_wrapper) {
- MutexLock lock(&mutex_);
-
- // Notify the client of the newly formed socket.
- const auto& connection_request_entry =
- requesting_connections_info_.find(remote_peer_id.GetId());
- if (connection_request_entry != requesting_connections_info_.end()) {
- connection_request_entry->second.socket_future.Set(socket_wrapper);
- return;
- }
-
- const auto& accepting_connection_entry =
- accepting_connections_info_.find(service_id);
- if (accepting_connection_entry != accepting_connections_info_.end()) {
- accepting_connection_entry->second.accepted_connection_callback.accepted_cb(
- socket_wrapper);
- return;
- }
-
- // No one to handle the newly created DataChannel, so we'll just close it.
- socket_wrapper.Close();
- NEARBY_LOG(INFO,
- "Ignoring new DataChannel because we "
- "are not accepting connections for service %s.",
- service_id.c_str());
-}
-
-void WebRtc::ProcessDataChannelClosed(const WebrtcPeerId& remote_peer_id) {
- MutexLock lock(&mutex_);
- NEARBY_LOG(INFO,
- "Data channel has closed, removing connection flow for peer %s.",
- remote_peer_id.GetId().c_str());
-
- RemoveConnectionFlow(remote_peer_id);
-}
-
-std::unique_ptr<ConnectionFlow> WebRtc::CreateConnectionFlow(
- const std::string& service_id, const WebrtcPeerId& remote_peer_id) {
- RemoveConnectionFlow(remote_peer_id);
-
- return ConnectionFlow::Create(
- {.local_ice_candidate_found_cb =
- {[this, service_id, remote_peer_id](
- const webrtc::IceCandidateInterface* ice_candidate) {
- // Note: We need to encode the ice candidate here, before we jump
- // off the thread. Otherwise, it gets destroyed and we can't read
- // it later.
- ::location::nearby::mediums::IceCandidate encoded_ice_candidate =
- webrtc_frames::EncodeIceCandidate(*ice_candidate);
- OffloadFromThread(
- "rtc-ice-candidates",
- [this, service_id, remote_peer_id, encoded_ice_candidate]() {
- ProcessLocalIceCandidate(service_id, remote_peer_id,
- encoded_ice_candidate);
- });
- }}},
- {
- .data_channel_open_cb = {[this, service_id, remote_peer_id](
- WebRtcSocketWrapper socket_wrapper) {
- OffloadFromThread(
- "rtc-channel-created",
- [this, service_id, remote_peer_id, socket_wrapper]() {
- ProcessDataChannelOpen(service_id, remote_peer_id,
- socket_wrapper);
- });
- }},
- .data_channel_closed_cb = {[this, remote_peer_id]() {
- OffloadFromThread("rtc-channel-closed", [this, remote_peer_id]() {
- ProcessDataChannelClosed(remote_peer_id);
- });
- }},
- },
- medium_);
-}
-
-void WebRtc::RemoveConnectionFlow(const WebrtcPeerId& remote_peer_id) {
- if (!connection_flows_.erase(remote_peer_id.GetId())) {
- return;
- }
-
- // If we had an outgoing connection request w/ this peer, report the failure
- // to the future that's being waited on.
- const auto& connection_request_entry =
- requesting_connections_info_.find(remote_peer_id.GetId());
- if (connection_request_entry != requesting_connections_info_.end()) {
- connection_request_entry->second.socket_future.SetException(
- {Exception::kFailed});
- }
-}
-
-void WebRtc::OffloadFromThread(const std::string& name, Runnable runnable) {
- single_thread_executor_.Execute(name, std::move(runnable));
-}
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc.h b/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc.h
deleted file mode 100644
index b5fb959af11..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc.h
+++ /dev/null
@@ -1,265 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_MEDIUMS_WEBRTC_H_
-#define CORE_INTERNAL_MEDIUMS_WEBRTC_H_
-
-#include <cstddef>
-#include <functional>
-#include <memory>
-#include <string>
-
-#include "absl/container/flat_hash_map.h"
-#include "absl/container/flat_hash_set.h"
-#include "core/internal/mediums/webrtc/connection_flow.h"
-#include "core/internal/mediums/webrtc/data_channel_listener.h"
-#include "core/internal/mediums/webrtc/local_ice_candidate_listener.h"
-#include "core/internal/mediums/webrtc/webrtc_socket.h"
-#include "core/internal/mediums/webrtc_peer_id.h"
-#include "core/internal/mediums/webrtc_socket_wrapper.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/cancellation_flag.h"
-#include "platform/base/listeners.h"
-#include "platform/base/runnable.h"
-#include "platform/public/atomic_boolean.h"
-#include "platform/public/cancelable_alarm.h"
-#include "platform/public/future.h"
-#include "platform/public/mutex.h"
-#include "platform/public/scheduled_executor.h"
-#include "platform/public/single_thread_executor.h"
-#include "platform/public/webrtc.h"
-#include "proto/connections/offline_wire_formats.pb.h"
-#include "proto/mediums/web_rtc_signaling_frames.pb.h"
-#include "webrtc/api/jsep.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-// Callback that is invoked when a new connection is accepted.
-struct AcceptedConnectionCallback {
- std::function<void(WebRtcSocketWrapper socket)> accepted_cb =
- DefaultCallback<WebRtcSocketWrapper>();
-};
-
-// Entry point for connecting a data channel between two devices via WebRtc.
-class WebRtc {
- public:
- WebRtc();
- ~WebRtc();
-
- // Gets the default two-letter country code associated with current locale.
- // For example, en_US locale resolves to "US".
- const std::string GetDefaultCountryCode();
-
- // Returns if WebRtc is available as a medium for nearby to transport data.
- // Runs on @MainThread.
- bool IsAvailable();
-
- // Returns if the device is accepting connection with specific service id.
- // Runs on @MainThread.
- bool IsAcceptingConnections(const std::string& service_id)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Prepares the device to accept incoming WebRtc connections. Returns a
- // boolean value indicating if the device has started accepting connections.
- // Runs on @MainThread.
- bool StartAcceptingConnections(const std::string& service_id,
- const WebrtcPeerId& self_peer_id,
- const LocationHint& location_hint,
- AcceptedConnectionCallback callback)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Try to stop (accepting) the specific connection with provided service id.
- // Runs on @MainThread
- void StopAcceptingConnections(const std::string& service_id)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Initiates a WebRtc connection with peer device identified by |peer_id|
- // with internal retry for maximum attempts of kConnectAttemptsLimit.
- // Runs on @MainThread.
- WebRtcSocketWrapper Connect(const std::string& service_id,
- const WebrtcPeerId& peer_id,
- const LocationHint& location_hint,
- CancellationFlag* cancellation_flag)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- private:
- static constexpr int kConnectAttemptsLimit = 3;
- static constexpr int kRestartAcceptConnectionsLimit = 3;
-
- enum class Role {
- kNone = 0,
- kOfferer = 1,
- kAnswerer = 2,
- };
-
- struct AcceptingConnectionsInfo {
- // The self_peer_id is generated from the BT/WiFi advertisements and allows
- // the scanner to message us over Tachyon.
- WebrtcPeerId self_peer_id;
-
- // The registered callback. When there's an incoming connection, this
- // callback is notified.
- AcceptedConnectionCallback accepted_connection_callback;
-
- // Allows us to communicate with the Tachyon web server.
- std::unique_ptr<WebRtcSignalingMessenger> signaling_messenger;
-
- // Restarts the tachyon inbox receives messages streaming rpc if the
- // streaming rpc times out. The streaming rpc times out after 60s while
- // advertising. Non-null when listening for WebRTC connections as an
- // offerer.
- CancelableAlarm restart_tachyon_receive_messages_alarm;
-
- // Tracks the number of times we've restarted receiving messages after a
- // failure. We limit the number to prevent endless restarts if we are
- // repeatedly unable to communicate with Tachyon.
- int restart_accept_connections_count = 0;
- };
-
- struct ConnectionRequestInfo {
- // The self_peer_id is randomly generated and allows the advertiser to
- // message us over Tachyon.
- WebrtcPeerId self_peer_id;
-
- // Allows us to communicate with the Tachyon web server.
- std::unique_ptr<WebRtcSignalingMessenger> signaling_messenger;
-
- // The pending DataChannel future. Our client will be blocked on this while
- // they wait for us to set up the channel over Tachyon.
- Future<WebRtcSocketWrapper> socket_future;
- };
-
- // Attempt to initiates a WebRtc connection with peer device identified by
- // |peer_id|.
- // Runs on @MainThread.
- WebRtcSocketWrapper AttemptToConnect(const std::string& service_id,
- const WebrtcPeerId& peer_id,
- const LocationHint& location_hint,
- CancellationFlag* cancellation_flag)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns if the device is accepting connection with specific service id.
- // Runs on @MainThread.
- bool IsAcceptingConnectionsLocked(const std::string& service_id)
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Receives a message from the signaling messenger.
- void OnSignalingMessage(const std::string& service_id,
- const ByteArray& message);
-
- // Decides whether to restart receiving messages.
- void OnSignalingComplete(const std::string& service_id, bool success);
-
- // Runs on |single_thread_executor_|.
- void ProcessTachyonInboxMessage(const std::string& service_id,
- const ByteArray& message)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Runs on |single_thread_executor_|.
- void SendOffer(const std::string& service_id,
- const WebrtcPeerId& remote_peer_id)
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Runs on |single_thread_executor_|.
- void ReceiveOffer(const WebrtcPeerId& remote_peer_id,
- SessionDescriptionWrapper offer)
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Runs on |single_thread_executor_|.
- void SendAnswer(const WebrtcPeerId& remote_peer_id)
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Runs on |single_thread_executor_|.
- void ReceiveAnswer(const WebrtcPeerId& remote_peer_id,
- SessionDescriptionWrapper answer)
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Runs on |single_thread_executor_|.
- void ReceiveIceCandidates(
- const WebrtcPeerId& remote_peer_id,
- std::vector<std::unique_ptr<webrtc::IceCandidateInterface>>
- ice_candidates) ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Runs on |single_thread_executor_|.
- std::unique_ptr<ConnectionFlow> CreateConnectionFlow(
- const std::string& service_id, const WebrtcPeerId& remote_peer_id)
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Runs on |single_thread_executor_|.
- std::unique_ptr<ConnectionFlow> GetConnectionFlow(
- const WebrtcPeerId& remote_peer_id) ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Runs on |single_thread_executor_|.
- void RemoveConnectionFlow(const WebrtcPeerId& remote_peer_id)
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Runs on |single_thread_executor_|.
- void ProcessDataChannelOpen(const std::string& service_id,
- const WebrtcPeerId& remote_peer_id,
- WebRtcSocketWrapper socket_wrapper)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Runs on |single_thread_executor_|.
- void ProcessDataChannelClosed(const WebrtcPeerId& remote_peer_id)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Runs on |single_thread_executor_|.
- void ProcessLocalIceCandidate(
- const std::string& service_id, const WebrtcPeerId& remote_peer_id,
- const ::location::nearby::mediums::IceCandidate ice_candidate)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Runs on |single_thread_executor_|.
- void ProcessRestartTachyonReceiveMessages(const std::string& service_id)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Runs on |single_thread_executor_|.
- void RestartTachyonReceiveMessages(const std::string& service_id)
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- void OffloadFromThread(const std::string& name, Runnable runnable);
-
- Mutex mutex_;
-
- WebRtcMedium medium_;
-
- // The single thread we throw the potentially blocking work on to.
- ScheduledExecutor single_thread_executor_;
-
- // A map of ServiceID -> State for all services that are listening for
- // incoming connections.
- absl::flat_hash_map<std::string, AcceptingConnectionsInfo>
- accepting_connections_info_ ABSL_GUARDED_BY(mutex_);
-
- // A map of a remote PeerId -> State for pending connection requests. As
- // messages from Tachyon come in, this lets us look up the connection request
- // info to handle the interaction.
- absl::flat_hash_map<std::string, ConnectionRequestInfo>
- requesting_connections_info_ ABSL_GUARDED_BY(mutex_);
-
- // A map of a remote PeerId -> ConnectionFlow. For each connection, we create
- // a unique ConnectionFlow.
- absl::flat_hash_map<std::string, std::unique_ptr<ConnectionFlow>>
- connection_flows_ ABSL_GUARDED_BY(mutex_);
-};
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_MEDIUMS_WEBRTC_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/BUILD b/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/BUILD
deleted file mode 100644
index 9e13e8b8359..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/BUILD
+++ /dev/null
@@ -1,99 +0,0 @@
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# https://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-licenses(["notice"])
-
-cc_library(
- name = "webrtc",
- srcs = [
- "connection_flow.cc",
- "signaling_frames.cc",
- ],
- hdrs = [
- "connection_flow.h",
- "data_channel_listener.h",
- "local_ice_candidate_listener.h",
- "session_description_wrapper.h",
- "signaling_frames.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- copts = ["-DCORE_ADAPTER_DLL"],
- visibility = [
- "//core/internal:__subpackages__",
- ],
- deps = [
- ":data_types",
- "//absl/memory",
- "//absl/time",
- "//core:core_types",
- "//core/internal/mediums:utils",
- "//platform/base",
- "//platform/public:comm",
- "//platform/public:logging",
- "//platform/public:types",
- "//proto/mediums:web_rtc_signaling_frames_cc_proto",
- "//webrtc/api:libjingle_peerconnection_api",
- "//third_party/webrtc/files/stable/webrtc/pc:peerconnection",
- ],
-)
-
-cc_library(
- name = "data_types",
- srcs = [
- "webrtc_socket.cc",
- ],
- hdrs = [
- "webrtc_socket.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- copts = ["-DCORE_ADAPTER_DLL"],
- visibility = [
- "//core/internal:__subpackages__",
- ],
- deps = [
- "//core:core_types",
- "//platform/base",
- "//platform/public:types",
- "//webrtc/api:libjingle_peerconnection_api",
- ],
-)
-
-cc_test(
- name = "webrtc_test",
- timeout = "short",
- srcs = [
- "connection_flow_test.cc",
- "signaling_frames_test.cc",
- "webrtc_socket_test.cc",
- ],
- tags = [
- "notsan", # NOTE(b/139734036): known data race in usrsctplib.
- "requires-net:external",
- ],
- deps = [
- ":data_types",
- ":webrtc",
- "//net/proto2/compat/public:proto2",
- "//testing/base/public:gunit_main",
- "//absl/time",
- "//core/internal/mediums:utils",
- "//platform/base",
- "//platform/base:test_util",
- "//platform/impl/g3", # buildcleaner: keep
- "//platform/public:comm",
- "//platform/public:types",
- "//webrtc/api:libjingle_peerconnection_api",
- "//webrtc/api:rtc_error",
- "//webrtc/api:scoped_refptr",
- ],
-)
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/connection_flow.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/connection_flow.cc
deleted file mode 100644
index 2906645348f..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/connection_flow.cc
+++ /dev/null
@@ -1,556 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/webrtc/connection_flow.h"
-
-#include <iterator>
-#include <memory>
-
-#include "absl/memory/memory.h"
-#include "absl/time/time.h"
-#include "core/internal/mediums/webrtc/session_description_wrapper.h"
-#include "core/internal/mediums/webrtc/webrtc_socket.h"
-#include "core/internal/mediums/webrtc_socket_wrapper.h"
-#include "platform/public/logging.h"
-#include "platform/public/mutex_lock.h"
-#include "platform/public/webrtc.h"
-#include "webrtc/api/data_channel_interface.h"
-#include "webrtc/api/jsep.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-constexpr absl::Duration ConnectionFlow::kTimeout;
-constexpr absl::Duration ConnectionFlow::kPeerConnectionTimeout;
-
-// This is the same as the nearby data channel name.
-constexpr char kDataChannelName[] = "dataChannel";
-
-class CreateSessionDescriptionObserverImpl
- : public webrtc::CreateSessionDescriptionObserver {
- public:
- CreateSessionDescriptionObserverImpl(
- ConnectionFlow* connection_flow,
- Future<SessionDescriptionWrapper> settable_future,
- ConnectionFlow::State expected_entry_state,
- ConnectionFlow::State exit_state)
- : connection_flow_{connection_flow},
- settable_future_{settable_future},
- expected_entry_state_{expected_entry_state},
- exit_state_{exit_state} {}
-
- // webrtc::CreateSessionDescriptionObserver
- void OnSuccess(webrtc::SessionDescriptionInterface* desc) override {
- if (connection_flow_->TransitionState(expected_entry_state_, exit_state_)) {
- settable_future_.Set(SessionDescriptionWrapper{desc});
- } else {
- settable_future_.SetException({Exception::kFailed});
- }
- }
-
- void OnFailure(webrtc::RTCError error) override {
- NEARBY_LOG(ERROR, "Error when creating session description: %s",
- error.message());
- settable_future_.SetException({Exception::kFailed});
- }
-
- private:
- ConnectionFlow* connection_flow_;
- Future<SessionDescriptionWrapper> settable_future_;
- ConnectionFlow::State expected_entry_state_;
- ConnectionFlow::State exit_state_;
-};
-
-class SetDescriptionObserverBase {
- public:
- ExceptionOr<bool> GetResult(absl::Duration timeout) {
- return settable_future_.Get(timeout);
- }
-
- protected:
- void OnSetDescriptionComplete(webrtc::RTCError error) {
- // On success, |error.ok()| is true.
- if (error.ok()) {
- settable_future_.Set(true);
- return;
- }
- settable_future_.SetException({Exception::kFailed});
- }
-
- private:
- Future<bool> settable_future_;
-};
-
-class SetLocalDescriptionObserver
- : public webrtc::SetLocalDescriptionObserverInterface,
- public SetDescriptionObserverBase {
- public:
- void OnSetLocalDescriptionComplete(webrtc::RTCError error) override {
- OnSetDescriptionComplete(error);
- }
-};
-
-class SetRemoteDescriptionObserver
- : public webrtc::SetRemoteDescriptionObserverInterface,
- public SetDescriptionObserverBase {
- public:
- void OnSetRemoteDescriptionComplete(webrtc::RTCError error) override {
- OnSetDescriptionComplete(error);
- }
-};
-
-using PeerConnectionState =
- webrtc::PeerConnectionInterface::PeerConnectionState;
-
-std::unique_ptr<ConnectionFlow> ConnectionFlow::Create(
- LocalIceCandidateListener local_ice_candidate_listener,
- DataChannelListener data_channel_listener, WebRtcMedium& webrtc_medium) {
- auto connection_flow = absl::WrapUnique(
- new ConnectionFlow(std::move(local_ice_candidate_listener),
- std::move(data_channel_listener)));
- if (connection_flow->InitPeerConnection(webrtc_medium)) {
- return connection_flow;
- }
-
- return nullptr;
-}
-
-ConnectionFlow::ConnectionFlow(
- LocalIceCandidateListener local_ice_candidate_listener,
- DataChannelListener data_channel_listener)
- : data_channel_listener_(std::move(data_channel_listener)),
- local_ice_candidate_listener_(std::move(local_ice_candidate_listener)) {}
-
-ConnectionFlow::~ConnectionFlow() {
- NEARBY_LOG(INFO, "~ConnectionFlow");
- RunOnSignalingThread([this] { CloseOnSignalingThread(); });
- shutdown_latch_.Await();
- NEARBY_LOG(INFO, "~ConnectionFlow done");
-}
-
-SessionDescriptionWrapper ConnectionFlow::CreateOffer() {
- CHECK(!IsRunningOnSignalingThread());
- Future<SessionDescriptionWrapper> success_future;
- if (!RunOnSignalingThread([this, success_future] {
- CreateOfferOnSignalingThread(success_future);
- })) {
- NEARBY_LOG(ERROR, "Failed to create offer");
- return SessionDescriptionWrapper();
- }
- ExceptionOr<SessionDescriptionWrapper> result = success_future.Get(kTimeout);
- if (result.ok()) {
- return std::move(result.result());
- }
- NEARBY_LOG(ERROR, "Failed to create offer: %d", result.exception());
- return SessionDescriptionWrapper();
-}
-
-void ConnectionFlow::CreateOfferOnSignalingThread(
- Future<SessionDescriptionWrapper> success_future) {
- if (!TransitionState(State::kInitialized, State::kCreatingOffer)) {
- success_future.SetException({Exception::kFailed});
- return;
- }
- webrtc::DataChannelInit data_channel_init;
- data_channel_init.reliable = true;
- auto pc = GetPeerConnection();
- CreateSocketFromDataChannel(
- pc->CreateDataChannel(kDataChannelName, &data_channel_init));
-
- webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options;
- rtc::scoped_refptr<CreateSessionDescriptionObserverImpl> observer =
- new rtc::RefCountedObject<CreateSessionDescriptionObserverImpl>(
- this, success_future, State::kCreatingOffer,
- State::kWaitingForAnswer);
- pc->CreateOffer(observer, options);
-}
-
-SessionDescriptionWrapper ConnectionFlow::CreateAnswer() {
- CHECK(!IsRunningOnSignalingThread());
- Future<SessionDescriptionWrapper> success_future;
- if (!RunOnSignalingThread([this, success_future] {
- CreateAnswerOnSignalingThread(success_future);
- })) {
- NEARBY_LOG(ERROR, "Failed to create answer");
- return SessionDescriptionWrapper();
- }
- ExceptionOr<SessionDescriptionWrapper> result = success_future.Get(kTimeout);
- if (result.ok()) {
- return std::move(result.result());
- }
- NEARBY_LOG(ERROR, "Failed to create answer: %d", result.exception());
- return SessionDescriptionWrapper();
-}
-
-void ConnectionFlow::CreateAnswerOnSignalingThread(
- Future<SessionDescriptionWrapper> success_future) {
- if (!TransitionState(State::kReceivedOffer, State::kCreatingAnswer)) {
- success_future.SetException({Exception::kFailed});
- return;
- }
- webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options;
- rtc::scoped_refptr<CreateSessionDescriptionObserverImpl> observer =
- new rtc::RefCountedObject<CreateSessionDescriptionObserverImpl>(
- this, success_future, State::kCreatingAnswer,
- State::kWaitingToConnect);
- auto pc = GetPeerConnection();
- pc->CreateAnswer(observer, options);
-}
-
-bool ConnectionFlow::SetLocalSessionDescription(SessionDescriptionWrapper sdp) {
- CHECK(!IsRunningOnSignalingThread());
- if (!sdp.IsValid()) return false;
-
- rtc::scoped_refptr<SetLocalDescriptionObserver> observer =
- new rtc::RefCountedObject<SetLocalDescriptionObserver>();
-
- if (!RunOnSignalingThread([this, observer, sdp = std::move(sdp)]() mutable {
- if (state_ == State::kEnded) {
- observer->OnSetLocalDescriptionComplete(
- webrtc::RTCError(webrtc::RTCErrorType::INVALID_STATE));
- return;
- }
- auto pc = GetPeerConnection();
-
- pc->SetLocalDescription(
- std::unique_ptr<webrtc::SessionDescriptionInterface>(sdp.Release()),
- observer);
- })) {
- return false;
- }
-
- ExceptionOr<bool> result = observer->GetResult(kTimeout);
- bool success = result.ok() && result.result();
- if (!success) {
- NEARBY_LOG(ERROR, "Failed to set local session description: %d",
- result.exception());
- }
- return success;
-}
-
-bool ConnectionFlow::SetRemoteSessionDescription(SessionDescriptionWrapper sdp,
- State expected_entry_state,
- State exit_state) {
- if (!sdp.IsValid()) return false;
-
- rtc::scoped_refptr<SetRemoteDescriptionObserver> observer =
- new rtc::RefCountedObject<SetRemoteDescriptionObserver>();
-
- if (!RunOnSignalingThread([this, observer, sdp = std::move(sdp),
- expected_entry_state, exit_state]() mutable {
- if (!TransitionState(expected_entry_state, exit_state)) {
- observer->OnSetRemoteDescriptionComplete(
- webrtc::RTCError(webrtc::RTCErrorType::INVALID_STATE));
- return;
- }
- auto pc = GetPeerConnection();
-
- pc->SetRemoteDescription(
- std::unique_ptr<webrtc::SessionDescriptionInterface>(sdp.Release()),
- observer);
- })) {
- return false;
- }
-
- ExceptionOr<bool> result = observer->GetResult(kTimeout);
- bool success = result.ok() && result.result();
- if (!success) {
- NEARBY_LOG(ERROR, "Failed to set remote description: %d",
- result.exception());
- }
- return success;
-}
-
-bool ConnectionFlow::OnOfferReceived(SessionDescriptionWrapper offer) {
- CHECK(!IsRunningOnSignalingThread());
- return SetRemoteSessionDescription(std::move(offer), State::kInitialized,
- State::kReceivedOffer);
-}
-
-bool ConnectionFlow::OnAnswerReceived(SessionDescriptionWrapper answer) {
- CHECK(!IsRunningOnSignalingThread());
- return SetRemoteSessionDescription(
- std::move(answer), State::kWaitingForAnswer, State::kWaitingToConnect);
-}
-
-bool ConnectionFlow::OnRemoteIceCandidatesReceived(
- std::vector<std::unique_ptr<webrtc::IceCandidateInterface>>
- ice_candidates) {
- CHECK(!IsRunningOnSignalingThread());
- // We can't call RunOnSignalingThread because C++ wants to copy ice_candidates
- // if we try. unique_ptr is not CopyConstructible and compilation fails.
- auto pc = GetPeerConnection();
-
- if (!pc) {
- return false;
- }
- pc->signaling_thread()->PostTask(
- RTC_FROM_HERE, [this, can_run_tasks = std::weak_ptr<void>(can_run_tasks_),
- candidates = std::move(ice_candidates)]() mutable {
- // don't run the task if the weak_ptr is no longer valid.
- if (!can_run_tasks.lock()) {
- return;
- }
- AddIceCandidatesOnSignalingThread(std::move(candidates));
- });
- return true;
-}
-
-void ConnectionFlow::AddIceCandidatesOnSignalingThread(
- std::vector<std::unique_ptr<webrtc::IceCandidateInterface>>
- ice_candidates) {
- CHECK(IsRunningOnSignalingThread());
- if (state_ == State::kEnded) {
- NEARBY_LOG(WARNING,
- "You cannot add ice candidates to a disconnected session.");
- return;
- }
- if (state_ != State::kWaitingToConnect && state_ != State::kConnected) {
- cached_remote_ice_candidates_.insert(
- cached_remote_ice_candidates_.end(),
- std::make_move_iterator(ice_candidates.begin()),
- std::make_move_iterator(ice_candidates.end()));
- return;
- }
- auto pc = GetPeerConnection();
- for (auto&& ice_candidate : ice_candidates) {
- if (!pc->AddIceCandidate(ice_candidate.get())) {
- NEARBY_LOG(WARNING, "Unable to add remote ice candidate.");
- }
- }
-}
-
-bool ConnectionFlow::CloseIfNotConnected() {
- CHECK(!IsRunningOnSignalingThread());
- Future<bool> closed;
- if (RunOnSignalingThread([this, closed]() mutable {
- if (state_ == State::kConnected) {
- closed.Set(false);
- } else {
- CloseOnSignalingThread();
- closed.Set(true);
- }
- })) {
- auto result = closed.Get();
- return result.ok() && result.result();
- }
- return true;
-}
-
-bool ConnectionFlow::InitPeerConnection(WebRtcMedium& webrtc_medium) {
- Future<bool> success_future;
- // CreatePeerConnection callback may be invoked after ConnectionFlow lifetime
- // has ended, in case of a timeout. Future is captured by value, and is safe
- // to access, but it is not safe to access ConnectionFlow member variables
- // unless the Future::Set() returns true.
- webrtc_medium.CreatePeerConnection(
- this,
- [this, success_future](rtc::scoped_refptr<webrtc::PeerConnectionInterface>
- peer_connection) mutable {
- if (!peer_connection) {
- success_future.Set(false);
- return;
- }
-
- // If this fails, means we have already assigned something to
- // success_future; it is either:
- // 1) this is the 2nd call of this callback (and this is a bug), or
- // 2) Get(timeout) has set the future value as exception already.
- if (success_future.IsSet()) return;
- MutexLock lock(&mutex_);
- peer_connection_ = peer_connection;
- signaling_thread_for_dcheck_only_ =
- peer_connection_->signaling_thread();
- success_future.Set(true);
- });
-
- ExceptionOr<bool> result = success_future.Get(kPeerConnectionTimeout);
- bool success = result.ok() && result.result();
- if (!success) {
- shutdown_latch_.CountDown();
- NEARBY_LOG(ERROR, "Failed to create peer connection: %d",
- result.exception());
- }
- return success;
-}
-
-void ConnectionFlow::OnSignalingStable() {
- if (state_ != State::kWaitingToConnect && state_ != State::kConnected) return;
- auto pc = GetPeerConnection();
- for (auto&& ice_candidate : cached_remote_ice_candidates_) {
- if (!pc->AddIceCandidate(ice_candidate.get())) {
- NEARBY_LOG(WARNING, "Unable to add remote ice candidate.");
- }
- }
- cached_remote_ice_candidates_.clear();
-}
-
-void ConnectionFlow::CreateSocketFromDataChannel(
- rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel) {
- NEARBY_LOG(INFO, "Creating data channel socket");
- auto socket =
- std::make_unique<WebRtcSocket>("WebRtcSocket", std::move(data_channel));
- socket->SetSocketListener({
- .socket_ready_cb = {[this](WebRtcSocket* socket) {
- CHECK(IsRunningOnSignalingThread());
- if (!TransitionState(State::kWaitingToConnect, State::kConnected)) {
- NEARBY_LOG(ERROR,
- "Data channel socket is open but connection flow was not "
- "in the required state");
- socket->Close();
- return;
- }
- // Pass socket wrapper by copy on purpose
- data_channel_listener_.data_channel_open_cb(socket_wrapper_);
- }},
- .socket_closed_cb = [callback =
- data_channel_listener_.data_channel_closed_cb](
- WebRtcSocket*) { callback(); },
- });
- socket_wrapper_ = WebRtcSocketWrapper(std::move(socket));
-}
-
-void ConnectionFlow::OnIceCandidate(
- const webrtc::IceCandidateInterface* candidate) {
- CHECK(IsRunningOnSignalingThread());
- local_ice_candidate_listener_.local_ice_candidate_found_cb(candidate);
-}
-
-void ConnectionFlow::OnSignalingChange(
- webrtc::PeerConnectionInterface::SignalingState new_state) {
- NEARBY_LOG(INFO, "OnSignalingChange: %d", new_state);
- CHECK(IsRunningOnSignalingThread());
- if (new_state == webrtc::PeerConnectionInterface::SignalingState::kStable) {
- OnSignalingStable();
- }
-}
-
-void ConnectionFlow::OnDataChannel(
- rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel) {
- NEARBY_LOG(INFO, "OnDataChannel");
- CHECK(IsRunningOnSignalingThread());
- CreateSocketFromDataChannel(std::move(data_channel));
-}
-
-void ConnectionFlow::OnIceGatheringChange(
- webrtc::PeerConnectionInterface::IceGatheringState new_state) {
- NEARBY_LOG(INFO, "OnIceGatheringChange: %d", new_state);
- CHECK(IsRunningOnSignalingThread());
-}
-
-void ConnectionFlow::OnConnectionChange(
- webrtc::PeerConnectionInterface::PeerConnectionState new_state) {
- NEARBY_LOG(INFO, "OnConnectionChange: %d", new_state);
- CHECK(IsRunningOnSignalingThread());
- if (new_state == PeerConnectionState::kClosed ||
- new_state == PeerConnectionState::kFailed ||
- new_state == PeerConnectionState::kDisconnected) {
- NEARBY_LOG(INFO, "Closing due to peer connection state change: %d",
- new_state);
- CloseOnSignalingThread();
- }
-}
-
-void ConnectionFlow::OnRenegotiationNeeded() {
- NEARBY_LOG(INFO, "OnRenegotiationNeeded");
- CHECK(IsRunningOnSignalingThread());
-}
-
-bool ConnectionFlow::TransitionState(State current_state, State new_state) {
- CHECK(IsRunningOnSignalingThread());
- if (current_state != state_) {
- NEARBY_LOG(
- WARNING,
- "Invalid state transition to %d: current state is %d but expected %d.",
- new_state, state_, current_state);
- return false;
- }
- NEARBY_LOG(INFO, "Transition: %d -> %d", state_, new_state);
- state_ = new_state;
- return true;
-}
-
-bool ConnectionFlow::CloseOnSignalingThread() {
- if (state_ == State::kEnded) {
- return false;
- }
- state_ = State::kEnded;
- // This prevents other tasks from queuing on the signaling thread for this
- // object.
- auto pc = GetAndResetPeerConnection();
-
- NEARBY_LOG(INFO, "Closing WebRTC peer connection.");
- // NOTE: Closing the peer conection will close the data channel and thus the
- // socket implicitly.
- if (pc) pc->Close();
- NEARBY_LOG(INFO, "Closed WebRTC peer connection.");
- // Prevent any already queued tasks from running on the signaling thread
- can_run_tasks_.reset();
- // If anyone was waiting for shutdown to be done let them know.
- shutdown_latch_.CountDown();
- return true;
-}
-
-bool ConnectionFlow::RunOnSignalingThread(Runnable&& runnable) {
- CHECK(!IsRunningOnSignalingThread());
- auto pc = GetPeerConnection();
- if (!pc) {
- NEARBY_LOG(WARNING,
- "Peer connection not available. Cannot schedule tasks.");
- return false;
- }
- // We are off signaling thread, so we can't use peer connection's methods
- // but we can access the signaling thread handle.
- pc->signaling_thread()->PostTask(
- RTC_FROM_HERE, [can_run_tasks = std::weak_ptr<void>(can_run_tasks_),
- task = std::move(runnable)] {
- // don't run the task if the weak_ptr is no longer valid.
- // shared_ptr |can_run_tasks_| is destroyed on the same thread
- // (signaling thread). This guarantees that if the weak_ptr is valid
- // when this task starts, it will stay valid until the task ends.
- if (!can_run_tasks.lock()) {
- NEARBY_LOG(INFO, "Peer connection already closed. Cannot run tasks.");
- return;
- }
- task();
- });
- return true;
-}
-
-bool ConnectionFlow::IsRunningOnSignalingThread() {
- return signaling_thread_for_dcheck_only_ != nullptr &&
- signaling_thread_for_dcheck_only_ == rtc::Thread::Current();
-}
-
-rtc::scoped_refptr<webrtc::PeerConnectionInterface>
-ConnectionFlow::GetPeerConnection() {
- // We must use a mutex to ensure that peer connection is
- // fully initialized.
- // We increase the peer_connection_'s refcount to keep it
- // alive while we use it.
- MutexLock lock(&mutex_);
- return peer_connection_;
-}
-
-rtc::scoped_refptr<webrtc::PeerConnectionInterface>
-ConnectionFlow::GetAndResetPeerConnection() {
- MutexLock lock(&mutex_);
- return std::move(peer_connection_);
-}
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/connection_flow.h b/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/connection_flow.h
deleted file mode 100644
index 474a1829bda..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/connection_flow.h
+++ /dev/null
@@ -1,233 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_MEDIUMS_WEBRTC_CONNECTION_FLOW_H_
-#define CORE_INTERNAL_MEDIUMS_WEBRTC_CONNECTION_FLOW_H_
-
-#include <memory>
-
-#include "core/internal/mediums/webrtc/data_channel_listener.h"
-#include "core/internal/mediums/webrtc/local_ice_candidate_listener.h"
-#include "core/internal/mediums/webrtc/session_description_wrapper.h"
-#include "core/internal/mediums/webrtc_socket_wrapper.h"
-#include "platform/base/runnable.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/single_thread_executor.h"
-#include "platform/public/webrtc.h"
-#include "webrtc/api/data_channel_interface.h"
-#include "webrtc/api/peer_connection_interface.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-/**
- * Flow for an offerer:
- *
- * <ul>
- * <li>INITIALIZED: After construction.
- * <li>CREATING_OFFER: After CreateOffer(). Local ice candidate collection
- * begins.
- * <li>WAITING_FOR_ANSWER: Until the remote peer sends their answer.
- * <li>WAITING_TO_CONNECT: Until the data channel actually connects. Remote
- * ice candidates should be added with OnRemoteIceCandidatesReceived as they are
- * gathered.
- * <li>CONNECTED: We successfully connected to the remote data
- * channel.
- * <li>ENDED: The final state that can occur from any of the previous
- * states if we disconnect at any point in the flow.
- * </ul>
- *
- * <p>Flow for an answerer:
- *
- * <ul>
- * <li>INITIALIZED: After construction.
- * <li>RECEIVED_OFFER: After onOfferReceived().
- * <li>CREATING_ANSWER: After CreateAnswer(). Local ice candidate collection
- * begins.
- * <li>WAITING_TO_CONNECT: Until the data channel actually connects.
- * Remote ice candidates should be added with OnRemoteIceCandidatesReceived as
- * they are gathered.
- * <li>CONNECTED: We successfully connected to the remote
- * data channel.
- * <li>ENDED: The final state that can occur from any of the
- * previous states if we disconnect at any point in the flow.
- * </ul>
- */
-class ConnectionFlow : public webrtc::PeerConnectionObserver {
- public:
- enum class State {
- kInitialized,
- kCreatingOffer,
- kWaitingForAnswer,
- kReceivedOffer,
- kCreatingAnswer,
- kWaitingToConnect,
- kConnected,
- kEnded,
- };
-
- // This method blocks on the creation of the peer connection object.
- // Can be called on any thread but never called on signaling thread.
- static std::unique_ptr<ConnectionFlow> Create(
- LocalIceCandidateListener local_ice_candidate_listener,
- DataChannelListener data_channel_listener, WebRtcMedium& webrtc_medium);
- ~ConnectionFlow() override;
-
- // Create the offer that will be sent to the remote. Mirrors the behaviour of
- // PeerConnectionInterface::CreateOffer.
- // Can be called on any thread but never called on signaling thread.
- SessionDescriptionWrapper CreateOffer() ABSL_LOCKS_EXCLUDED(mutex_);
- // Create the answer that will be sent to the remote. Mirrors the behaviour of
- // PeerConnectionInterface::CreateAnswer.
- // Can be called on any thread but never called on signaling thread.
- SessionDescriptionWrapper CreateAnswer() ABSL_LOCKS_EXCLUDED(mutex_);
- // Set the local session description. |sdp| was created via CreateOffer()
- // or CreateAnswer().
- // Can be called on any thread but never called on signaling thread.
- bool SetLocalSessionDescription(SessionDescriptionWrapper sdp)
- ABSL_LOCKS_EXCLUDED(mutex_);
- // Invoked when an offer was received from a remote; this will set the remote
- // session description on the peer connection. Returns true if the offer was
- // successfully set as remote session description.
- // Can be called on any thread but never called on signaling thread.
- bool OnOfferReceived(SessionDescriptionWrapper offer)
- ABSL_LOCKS_EXCLUDED(mutex_);
- // Invoked when an answer was received from a remote; this will set the remote
- // session description on the peer connection. Returns true if the offer was
- // successfully set as remote session description.
- // Can be called on any thread but never called on signaling thread.
- bool OnAnswerReceived(SessionDescriptionWrapper answer)
- ABSL_LOCKS_EXCLUDED(mutex_);
- // Invoked when an ice candidate was received from a remote; this will add the
- // ice candidate to the peer connection if ready or cache it otherwise.
- // Can be called on any thread but never called on signaling thread.
- bool OnRemoteIceCandidatesReceived(
- std::vector<std::unique_ptr<webrtc::IceCandidateInterface>>
- ice_candidates) ABSL_LOCKS_EXCLUDED(mutex_);
- // Close the peer connection and data channel if not connected.
- // Can be called on any thread but never called on signaling thread.
- bool CloseIfNotConnected() ABSL_LOCKS_EXCLUDED(mutex_);
-
- // webrtc::PeerConnectionObserver:
- // All methods called only on signaling thread.
- void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override;
- void OnSignalingChange(
- webrtc::PeerConnectionInterface::SignalingState new_state) override;
- void OnDataChannel(
- rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel) override;
- void OnIceGatheringChange(
- webrtc::PeerConnectionInterface::IceGatheringState new_state) override;
- void OnConnectionChange(
- webrtc::PeerConnectionInterface::PeerConnectionState new_state) override;
- void OnRenegotiationNeeded() override;
-
- // Public because it's used in tests too.
- rtc::scoped_refptr<webrtc::PeerConnectionInterface> GetPeerConnection();
-
- private:
- ConnectionFlow(LocalIceCandidateListener local_ice_candidate_listener,
- DataChannelListener data_channel_listener);
-
- // Resets peer connection reference. Returns old value.
- rtc::scoped_refptr<webrtc::PeerConnectionInterface>
- GetAndResetPeerConnection();
- void CreateOfferOnSignalingThread(
- Future<SessionDescriptionWrapper> success_future);
- void CreateAnswerOnSignalingThread(
- Future<SessionDescriptionWrapper> success_future);
- void AddIceCandidatesOnSignalingThread(
- std::vector<std::unique_ptr<webrtc::IceCandidateInterface>>
- ice_candidates);
- // Invoked when the peer connection indicates that signaling is stable.
- void OnSignalingStable() ABSL_LOCKS_EXCLUDED(mutex_);
-
- void CreateSocketFromDataChannel(
- rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel);
-
- // TODO(bfranz): Consider whether this needs to be configurable per platform
- static constexpr absl::Duration kTimeout = absl::Milliseconds(250);
- static constexpr absl::Duration kPeerConnectionTimeout =
- absl::Milliseconds(2500);
-
- bool InitPeerConnection(WebRtcMedium& webrtc_medium);
-
- bool TransitionState(State current_state, State new_state);
-
- bool SetRemoteSessionDescription(SessionDescriptionWrapper sdp,
- State expected_entry_state,
- State exit_state);
-
- bool CloseOnSignalingThread() ABSL_LOCKS_EXCLUDED(mutex_);
-
- bool RunOnSignalingThread(Runnable&& runnable);
- bool IsRunningOnSignalingThread();
-
- Mutex mutex_;
- // Used to prevent the destructor from returning while the signaling thread is
- // still running CloseOnSignalingThread()
- CountDownLatch shutdown_latch_{1};
-
- // State is used on signaling thread only.
- State state_ = State::kInitialized;
- // Used to communicate data channel events back to the caller of Create()
- DataChannelListener data_channel_listener_;
-
- LocalIceCandidateListener local_ice_candidate_listener_;
- // Peer connection can be used only on signaling thread. The only exception
- // is accessing the signaling thread handle. Tasks posted on the
- // signaling thread may outlive both |peer_connection_| and |this| objects.
- // A mutex is required to access peer connection reference because peer
- // connection object and the reference can be initialized on different
- // threads - the reference could be initialized before peer connection's
- // constructor has finished.
- // |peer_connection_| is actually implemented by PeerConnectionProxy, which
- // runs the real PeerConnection's methods on the correct thread (signaling or
- // worker). If a proxy method is called on the correct thread, then the real
- // method is called directly. Otherwise, a task is posted on the correct
- // thread and the current thread is blocked until that task finishes. We
- // choose to explicitly use |peer_connection_| on the signaling thread,
- // because it allows us to do state management on the signaling thread too,
- // simplifies locking, and we don't have to block the current thread for every
- // peer connection call.
- rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_
- ABSL_GUARDED_BY(mutex_);
-
- // Used to hold a reference to the WebRtcSocket while the data channel is
- // connecting.
- WebRtcSocketWrapper socket_wrapper_;
-
- std::vector<std::unique_ptr<webrtc::IceCandidateInterface>>
- cached_remote_ice_candidates_;
- // This pointer is only for DCHECK() assertions.
- // It allows us to check if we are running on signaling thread even
- // after destroying |peer_connection_|.
- const void* signaling_thread_for_dcheck_only_ = nullptr;
- // This shared_ptr is reset on the signaling thread when ConnectionFlow is
- // closed. This prevents us from running tasks on the signaling thread when
- // peer connection is closed. The value stored in |can_run_tasks_| is not
- // used. We are using std::shared_ptr instead of rtc::WeakPtrFactory because
- // the former is thread-safe.
- std::shared_ptr<void> can_run_tasks_ = std::make_shared<int>();
-
- friend class CreateSessionDescriptionObserverImpl;
-};
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_MEDIUMS_WEBRTC_CONNECTION_FLOW_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/connection_flow_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/connection_flow_test.cc
deleted file mode 100644
index dfc98d71f6e..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/connection_flow_test.cc
+++ /dev/null
@@ -1,407 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/webrtc/connection_flow.h"
-
-#include <memory>
-#include <vector>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/time/time.h"
-#include "core/internal/mediums/webrtc/session_description_wrapper.h"
-#include "core/internal/mediums/webrtc_socket_wrapper.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/medium_environment.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/webrtc.h"
-#include "webrtc/api/data_channel_interface.h"
-#include "webrtc/api/jsep.h"
-#include "webrtc/api/rtc_error.h"
-#include "webrtc/api/scoped_refptr.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-namespace {
-
-class ConnectionFlowTest : public ::testing::Test {
- protected:
- ConnectionFlowTest() {
- MediumEnvironment::Instance().Stop();
- MediumEnvironment::Instance().Start({.webrtc_enabled = true});
- }
-};
-
-std::unique_ptr<webrtc::IceCandidateInterface> CopyCandidate(
- const webrtc::IceCandidateInterface* candidate) {
- return webrtc::CreateIceCandidate(candidate->sdp_mid(),
- candidate->sdp_mline_index(),
- candidate->candidate());
-}
-
-// TODO(bfranz) - Add test that deterministically sends answerer_ice_candidates
-// before answer is sent.
-TEST_F(ConnectionFlowTest, SuccessfulOfferAnswerFlow) {
- WebRtcMedium webrtc_medium_offerer, webrtc_medium_answerer;
-
- Future<ByteArray> message_received_future;
-
- Future<WebRtcSocketWrapper> offerer_socket_future, answerer_socket_future;
-
- std::unique_ptr<ConnectionFlow> offerer, answerer;
-
- // Send Ice Candidates immediately when you retrieve them
- offerer = ConnectionFlow::Create(
- {.local_ice_candidate_found_cb =
- [&answerer](const webrtc::IceCandidateInterface* candidate) {
- std::vector<std::unique_ptr<webrtc::IceCandidateInterface>> vec;
- vec.push_back(CopyCandidate(candidate));
- // The callback might be alive while the objects in test are
- // destroyed.
- if (answerer)
- answerer->OnRemoteIceCandidatesReceived(std::move(vec));
- }},
- {.data_channel_open_cb =
- [&offerer_socket_future](WebRtcSocketWrapper socket) {
- offerer_socket_future.Set(std::move(socket));
- }},
- webrtc_medium_offerer);
- ASSERT_NE(offerer, nullptr);
- answerer = ConnectionFlow::Create(
- {.local_ice_candidate_found_cb =
- [&offerer](const webrtc::IceCandidateInterface* candidate) {
- std::vector<std::unique_ptr<webrtc::IceCandidateInterface>> vec;
- vec.push_back(CopyCandidate(candidate));
- // The callback might be alive while the objects in test are
- // destroyed.
- if (offerer)
- offerer->OnRemoteIceCandidatesReceived(std::move(vec));
- }},
- {.data_channel_open_cb =
- [&answerer_socket_future](WebRtcSocketWrapper socket) {
- answerer_socket_future.Set(std::move(socket));
- }},
- webrtc_medium_answerer);
- ASSERT_NE(answerer, nullptr);
-
- // Create and send offer
- SessionDescriptionWrapper offer = offerer->CreateOffer();
- ASSERT_TRUE(offer.IsValid());
- EXPECT_EQ(offer.GetType(), webrtc::SdpType::kOffer);
- EXPECT_TRUE(answerer->OnOfferReceived(offer));
- EXPECT_TRUE(offerer->SetLocalSessionDescription(std::move(offer)));
-
- // Create and send answer
- SessionDescriptionWrapper answer = answerer->CreateAnswer();
- ASSERT_TRUE(answer.IsValid());
- EXPECT_EQ(answer.GetType(), webrtc::SdpType::kAnswer);
- EXPECT_TRUE(offerer->OnAnswerReceived(answer));
- EXPECT_TRUE(answerer->SetLocalSessionDescription(std::move(answer)));
-
- // Retrieve Data Channels
- ExceptionOr<WebRtcSocketWrapper> offerer_socket =
- offerer_socket_future.Get(absl::Seconds(1));
- EXPECT_TRUE(offerer_socket.ok());
- ExceptionOr<WebRtcSocketWrapper> answerer_socket =
- answerer_socket_future.Get(absl::Seconds(1));
- EXPECT_TRUE(answerer_socket.ok());
-
- // Send message on data channel
- const char message[] = "Test";
- offerer_socket.result().GetImpl().GetOutputStream().Write(
- ByteArray(message, 4));
- ExceptionOr<ByteArray> received_message =
- answerer_socket.result().GetImpl().GetInputStream().Read(4);
- EXPECT_TRUE(received_message.ok());
- EXPECT_EQ(received_message.result(), ByteArray{message});
-}
-
-TEST_F(ConnectionFlowTest, CreateAnswerBeforeOfferReceived) {
- WebRtcMedium webrtc_medium;
-
- std::unique_ptr<ConnectionFlow> answerer = ConnectionFlow::Create(
- LocalIceCandidateListener(), DataChannelListener(), webrtc_medium);
- ASSERT_NE(answerer, nullptr);
-
- SessionDescriptionWrapper answer = answerer->CreateAnswer();
- EXPECT_FALSE(answer.IsValid());
-}
-
-TEST_F(ConnectionFlowTest, SetAnswerBeforeOffer) {
- WebRtcMedium webrtc_medium_offerer, webrtc_medium_answerer;
-
- std::unique_ptr<ConnectionFlow> offerer =
- ConnectionFlow::Create(LocalIceCandidateListener(), DataChannelListener(),
- webrtc_medium_offerer);
- ASSERT_NE(offerer, nullptr);
- std::unique_ptr<ConnectionFlow> answerer =
- ConnectionFlow::Create(LocalIceCandidateListener(), DataChannelListener(),
- webrtc_medium_answerer);
- ASSERT_NE(answerer, nullptr);
-
- SessionDescriptionWrapper offer = offerer->CreateOffer();
- ASSERT_TRUE(offer.IsValid());
- EXPECT_EQ(offer.GetType(), webrtc::SdpType::kOffer);
- // Did not set offer as local session description
- EXPECT_TRUE(answerer->OnOfferReceived(offer));
-
- SessionDescriptionWrapper answer = answerer->CreateAnswer();
- ASSERT_TRUE(answer.IsValid());
- EXPECT_EQ(answer.GetType(), webrtc::SdpType::kAnswer);
- EXPECT_FALSE(offerer->OnAnswerReceived(answer));
-}
-
-TEST_F(ConnectionFlowTest, CannotCreateOfferAfterClose) {
- WebRtcMedium webrtc_medium;
-
- std::unique_ptr<ConnectionFlow> offerer = ConnectionFlow::Create(
- LocalIceCandidateListener(), DataChannelListener(), webrtc_medium);
- ASSERT_NE(offerer, nullptr);
-
- EXPECT_TRUE(offerer->CloseIfNotConnected());
-
- EXPECT_FALSE(offerer->CreateOffer().IsValid());
-}
-
-TEST_F(ConnectionFlowTest, CannotSetSessionDescriptionAfterClose) {
- WebRtcMedium webrtc_medium;
-
- std::unique_ptr<ConnectionFlow> offerer = ConnectionFlow::Create(
- LocalIceCandidateListener(), DataChannelListener(), webrtc_medium);
- ASSERT_NE(offerer, nullptr);
-
- SessionDescriptionWrapper offer = offerer->CreateOffer();
- ASSERT_TRUE(offer.IsValid());
- EXPECT_EQ(offer.GetType(), webrtc::SdpType::kOffer);
-
- EXPECT_TRUE(offerer->CloseIfNotConnected());
-
- EXPECT_FALSE(offerer->SetLocalSessionDescription(offer));
-}
-
-TEST_F(ConnectionFlowTest, CannotReceiveOfferAfterClose) {
- WebRtcMedium webrtc_medium_offerer, webrtc_medium_answerer;
-
- std::unique_ptr<ConnectionFlow> offerer =
- ConnectionFlow::Create(LocalIceCandidateListener(), DataChannelListener(),
- webrtc_medium_offerer);
- ASSERT_NE(offerer, nullptr);
- std::unique_ptr<ConnectionFlow> answerer =
- ConnectionFlow::Create(LocalIceCandidateListener(), DataChannelListener(),
- webrtc_medium_answerer);
- ASSERT_NE(answerer, nullptr);
-
- EXPECT_TRUE(answerer->CloseIfNotConnected());
-
- SessionDescriptionWrapper offer = offerer->CreateOffer();
- ASSERT_TRUE(offer.IsValid());
- EXPECT_EQ(offer.GetType(), webrtc::SdpType::kOffer);
-
- EXPECT_FALSE(answerer->OnOfferReceived(offer));
-}
-
-TEST_F(ConnectionFlowTest, NullPeerConnection) {
- MediumEnvironment::Instance().SetUseValidPeerConnection(
- /*use_valid_peer_connection=*/false);
-
- WebRtcMedium medium;
- std::unique_ptr<ConnectionFlow> answerer = ConnectionFlow::Create(
- LocalIceCandidateListener(), DataChannelListener(), medium);
- EXPECT_EQ(answerer, nullptr);
-}
-
-TEST_F(ConnectionFlowTest, PeerConnectionTimeout) {
- MediumEnvironment::Instance().SetUseValidPeerConnection(
- /*use_valid_peer_connection=*/true);
- WebRtcMedium medium1;
- std::unique_ptr<ConnectionFlow> flow1 = ConnectionFlow::Create(
- LocalIceCandidateListener(), DataChannelListener(), medium1);
- EXPECT_NE(flow1, nullptr);
-
- // Attempt to trigger the 2.5s peer connection timeout.
- MediumEnvironment::Instance().SetPeerConnectionLatency(absl::Seconds(5));
- WebRtcMedium medium2;
- std::unique_ptr<ConnectionFlow> flow2 = ConnectionFlow::Create(
- LocalIceCandidateListener(), DataChannelListener(), medium2);
- EXPECT_EQ(flow2, nullptr);
-}
-
-TEST_F(ConnectionFlowTest, TerminateAnswerer) {
- WebRtcMedium webrtc_medium_offerer, webrtc_medium_answerer;
-
- Future<ByteArray> message_received_future;
-
- Future<WebRtcSocketWrapper> offerer_socket_future, answerer_socket_future;
-
- std::unique_ptr<ConnectionFlow> offerer, answerer;
-
- // Send Ice Candidates immediately when you retrieve them
- offerer = ConnectionFlow::Create(
- {.local_ice_candidate_found_cb =
- [&answerer](const webrtc::IceCandidateInterface* candidate) {
- std::vector<std::unique_ptr<webrtc::IceCandidateInterface>> vec;
- vec.push_back(CopyCandidate(candidate));
- // The callback might be alive while the objects in test are
- // destroyed.
- if (answerer)
- answerer->OnRemoteIceCandidatesReceived(std::move(vec));
- }},
- {.data_channel_open_cb =
- [&offerer_socket_future](WebRtcSocketWrapper socket) {
- offerer_socket_future.Set(std::move(socket));
- }},
- webrtc_medium_offerer);
- ASSERT_NE(offerer, nullptr);
- answerer = ConnectionFlow::Create(
- {.local_ice_candidate_found_cb =
- [&offerer](const webrtc::IceCandidateInterface* candidate) {
- std::vector<std::unique_ptr<webrtc::IceCandidateInterface>> vec;
- vec.push_back(CopyCandidate(candidate));
- // The callback might be alive while the objects in test are
- // destroyed.
- if (offerer)
- offerer->OnRemoteIceCandidatesReceived(std::move(vec));
- }},
- {.data_channel_open_cb =
- [&answerer_socket_future](WebRtcSocketWrapper wrapper) {
- answerer_socket_future.Set(std::move(wrapper));
- }},
- webrtc_medium_answerer);
- ASSERT_NE(answerer, nullptr);
-
- // Create and send offer
- SessionDescriptionWrapper offer = offerer->CreateOffer();
- ASSERT_TRUE(offer.IsValid());
- EXPECT_EQ(offer.GetType(), webrtc::SdpType::kOffer);
- EXPECT_TRUE(answerer->OnOfferReceived(offer));
- EXPECT_TRUE(offerer->SetLocalSessionDescription(std::move(offer)));
-
- // Create and send answer
- SessionDescriptionWrapper answer = answerer->CreateAnswer();
- ASSERT_TRUE(answer.IsValid());
- EXPECT_EQ(answer.GetType(), webrtc::SdpType::kAnswer);
- EXPECT_TRUE(offerer->OnAnswerReceived(answer));
- EXPECT_TRUE(answerer->SetLocalSessionDescription(std::move(answer)));
-
- // Retrieve Data Channels
- ExceptionOr<WebRtcSocketWrapper> offerer_socket =
- offerer_socket_future.Get(absl::Seconds(1));
- EXPECT_TRUE(offerer_socket.ok());
- ExceptionOr<WebRtcSocketWrapper> answerer_socket =
- answerer_socket_future.Get(absl::Seconds(1));
- EXPECT_TRUE(offerer_socket.ok());
-
- CountDownLatch latch(1);
- auto pc = answerer->GetPeerConnection();
- pc->signaling_thread()->PostTask(RTC_FROM_HERE, [pc, latch]() mutable {
- pc->Close();
- latch.CountDown();
- });
- latch.Await();
-
- // Send message on data channel
- std::string message = "Test";
- offerer_socket.result().GetOutputStream().Write(ByteArray{message});
- ExceptionOr<ByteArray> received_message =
- answerer_socket.result().GetInputStream().Read(4);
- EXPECT_FALSE(received_message.ok());
-}
-
-TEST_F(ConnectionFlowTest, TerminateOfferer) {
- WebRtcMedium webrtc_medium_offerer, webrtc_medium_answerer;
-
- Future<ByteArray> message_received_future;
-
- Future<WebRtcSocketWrapper> offerer_socket_future, answerer_socket_future;
-
- std::unique_ptr<ConnectionFlow> offerer, answerer;
-
- // Send Ice Candidates immediately when you retrieve them
- offerer = ConnectionFlow::Create(
- {.local_ice_candidate_found_cb =
- [&answerer](const webrtc::IceCandidateInterface* candidate) {
- std::vector<std::unique_ptr<webrtc::IceCandidateInterface>> vec;
- vec.push_back(CopyCandidate(candidate));
- // The callback might be alive while the objects in test are
- // destroyed.
- if (answerer)
- answerer->OnRemoteIceCandidatesReceived(std::move(vec));
- }},
- {.data_channel_open_cb =
- [&offerer_socket_future](WebRtcSocketWrapper socket) {
- offerer_socket_future.Set(std::move(socket));
- }},
- webrtc_medium_offerer);
- ASSERT_NE(offerer, nullptr);
- answerer = ConnectionFlow::Create(
- {.local_ice_candidate_found_cb =
- [&offerer](const webrtc::IceCandidateInterface* candidate) {
- std::vector<std::unique_ptr<webrtc::IceCandidateInterface>> vec;
- vec.push_back(CopyCandidate(candidate));
- // The callback might be alive while the objects in test are
- // destroyed.
- if (offerer)
- offerer->OnRemoteIceCandidatesReceived(std::move(vec));
- }},
- {.data_channel_open_cb =
- [&answerer_socket_future](WebRtcSocketWrapper wrapper) {
- answerer_socket_future.Set(std::move(wrapper));
- }},
- webrtc_medium_answerer);
- ASSERT_NE(answerer, nullptr);
-
- // Create and send offer
- SessionDescriptionWrapper offer = offerer->CreateOffer();
- ASSERT_TRUE(offer.IsValid());
- EXPECT_EQ(offer.GetType(), webrtc::SdpType::kOffer);
- EXPECT_TRUE(answerer->OnOfferReceived(offer));
- EXPECT_TRUE(offerer->SetLocalSessionDescription(std::move(offer)));
-
- // Create and send answer
- SessionDescriptionWrapper answer = answerer->CreateAnswer();
- ASSERT_TRUE(answer.IsValid());
- EXPECT_EQ(answer.GetType(), webrtc::SdpType::kAnswer);
- EXPECT_TRUE(offerer->OnAnswerReceived(answer));
- EXPECT_TRUE(answerer->SetLocalSessionDescription(std::move(answer)));
-
- // Retrieve Data Channels
- ExceptionOr<WebRtcSocketWrapper> offerer_socket =
- offerer_socket_future.Get(absl::Seconds(1));
- EXPECT_TRUE(offerer_socket.ok());
- ExceptionOr<WebRtcSocketWrapper> answerer_socket =
- answerer_socket_future.Get(absl::Seconds(1));
- EXPECT_TRUE(offerer_socket.ok());
-
- CountDownLatch latch(1);
- auto pc = offerer->GetPeerConnection();
- pc->signaling_thread()->PostTask(RTC_FROM_HERE, [pc, latch]() mutable {
- pc->Close();
- latch.CountDown();
- });
- latch.Await();
-
- // Send message on data channel
- std::string message = "Test";
- offerer_socket.result().GetOutputStream().Write(ByteArray{message});
- ExceptionOr<ByteArray> received_message =
- answerer_socket.result().GetInputStream().Read(4);
- EXPECT_FALSE(received_message.ok());
-}
-} // namespace
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/data_channel_listener.h b/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/data_channel_listener.h
deleted file mode 100644
index 13e6bb5a02e..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/data_channel_listener.h
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_MEDIUMS_WEBRTC_DATA_CHANNEL_LISTENER_H_
-#define CORE_INTERNAL_MEDIUMS_WEBRTC_DATA_CHANNEL_LISTENER_H_
-
-#include "core/internal/mediums/webrtc_socket_wrapper.h"
-#include "core/listeners.h"
-#include "platform/base/byte_array.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-// Callbacks from the data channel.
-struct DataChannelListener {
- // Called when the data channel is open and the socket wraper is ready to
- // read and write.
- std::function<void(WebRtcSocketWrapper)> data_channel_open_cb =
- DefaultCallback<WebRtcSocketWrapper>();
-
- // Called when the data channel is closed.
- std::function<void()> data_channel_closed_cb = DefaultCallback<>();
-};
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_MEDIUMS_WEBRTC_DATA_CHANNEL_LISTENER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/local_ice_candidate_listener.h b/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/local_ice_candidate_listener.h
deleted file mode 100644
index 24085193e39..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/local_ice_candidate_listener.h
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_MEDIUMS_WEBRTC_LOCAL_ICE_CANDIDATE_LISTENER_H_
-#define CORE_INTERNAL_MEDIUMS_WEBRTC_LOCAL_ICE_CANDIDATE_LISTENER_H_
-
-#include "core/listeners.h"
-#include "webrtc/api/peer_connection_interface.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-// Callbacks from local ice candidate collection.
-struct LocalIceCandidateListener {
- // Called when a new local ice candidate has been found.
- std::function<void(const webrtc::IceCandidateInterface*)>
- local_ice_candidate_found_cb = location::nearby::DefaultCallback<
- const webrtc::IceCandidateInterface*>();
-};
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_MEDIUMS_WEBRTC_LOCAL_ICE_CANDIDATE_LISTENER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/signaling_frames.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/signaling_frames.cc
deleted file mode 100644
index 033c2fac17f..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/signaling_frames.cc
+++ /dev/null
@@ -1,134 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/webrtc/signaling_frames.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-namespace webrtc_frames {
-using WebRtcSignalingFrame = location::nearby::mediums::WebRtcSignalingFrame;
-
-namespace {
-
-ByteArray FrameToByteArray(const WebRtcSignalingFrame& signaling_frame) {
- std::string message;
- signaling_frame.SerializeToString(&message);
- return ByteArray(message.c_str(), message.size());
-}
-
-void SetSenderId(const WebrtcPeerId& sender_id, WebRtcSignalingFrame& frame) {
- frame.mutable_sender_id()->set_id(sender_id.GetId());
-}
-
-std::unique_ptr<webrtc::IceCandidateInterface> DecodeIceCandidate(
- location::nearby::mediums::IceCandidate ice_candidate_proto) {
- webrtc::SdpParseError error;
- return std::unique_ptr<webrtc::IceCandidateInterface>(
- webrtc::CreateIceCandidate(ice_candidate_proto.sdp_mid(),
- ice_candidate_proto.sdp_m_line_index(),
- ice_candidate_proto.sdp(), &error));
-}
-
-} // namespace
-
-ByteArray EncodeReadyForSignalingPoke(const WebrtcPeerId& sender_id) {
- WebRtcSignalingFrame signaling_frame;
- signaling_frame.set_type(WebRtcSignalingFrame::READY_FOR_SIGNALING_POKE_TYPE);
- SetSenderId(sender_id, signaling_frame);
- signaling_frame.set_allocated_ready_for_signaling_poke(
- new location::nearby::mediums::ReadyForSignalingPoke());
- return FrameToByteArray(std::move(signaling_frame));
-}
-
-ByteArray EncodeOffer(const WebrtcPeerId& sender_id,
- const webrtc::SessionDescriptionInterface& offer) {
- WebRtcSignalingFrame signaling_frame;
- signaling_frame.set_type(WebRtcSignalingFrame::OFFER_TYPE);
- SetSenderId(sender_id, signaling_frame);
- std::string offer_str;
- offer.ToString(&offer_str);
- signaling_frame.mutable_offer()
- ->mutable_session_description()
- ->set_description(offer_str);
- return FrameToByteArray(std::move(signaling_frame));
-}
-
-ByteArray EncodeAnswer(const WebrtcPeerId& sender_id,
- const webrtc::SessionDescriptionInterface& answer) {
- WebRtcSignalingFrame signaling_frame;
- signaling_frame.set_type(WebRtcSignalingFrame::ANSWER_TYPE);
- SetSenderId(sender_id, signaling_frame);
- std::string answer_str;
- answer.ToString(&answer_str);
- signaling_frame.mutable_answer()
- ->mutable_session_description()
- ->set_description(answer_str);
- return FrameToByteArray(std::move(signaling_frame));
-}
-
-ByteArray EncodeIceCandidates(
- const WebrtcPeerId& sender_id,
- const std::vector<location::nearby::mediums::IceCandidate>&
- ice_candidates) {
- WebRtcSignalingFrame signaling_frame;
- signaling_frame.set_type(WebRtcSignalingFrame::ICE_CANDIDATES_TYPE);
- SetSenderId(sender_id, signaling_frame);
- for (const auto& ice_candidate : ice_candidates) {
- *signaling_frame.mutable_ice_candidates()->add_ice_candidates() =
- ice_candidate;
- }
- return FrameToByteArray(std::move(signaling_frame));
-}
-
-std::unique_ptr<webrtc::SessionDescriptionInterface> DecodeOffer(
- const WebRtcSignalingFrame& frame) {
- return webrtc::CreateSessionDescription(
- webrtc::SdpType::kOffer,
- frame.offer().session_description().description());
-}
-
-std::unique_ptr<webrtc::SessionDescriptionInterface> DecodeAnswer(
- const WebRtcSignalingFrame& frame) {
- return webrtc::CreateSessionDescription(
- webrtc::SdpType::kAnswer,
- frame.answer().session_description().description());
-}
-
-std::vector<std::unique_ptr<webrtc::IceCandidateInterface>> DecodeIceCandidates(
- const WebRtcSignalingFrame& frame) {
- std::vector<std::unique_ptr<webrtc::IceCandidateInterface>> ice_candidates;
- for (const auto& candidate : frame.ice_candidates().ice_candidates()) {
- ice_candidates.push_back(DecodeIceCandidate(candidate));
- }
- return ice_candidates;
-}
-
-location::nearby::mediums::IceCandidate EncodeIceCandidate(
- const webrtc::IceCandidateInterface& ice_candidate) {
- std::string sdp;
- ice_candidate.ToString(&sdp);
- location::nearby::mediums::IceCandidate ice_candidate_proto;
- ice_candidate_proto.set_sdp(sdp);
- ice_candidate_proto.set_sdp_mid(ice_candidate.sdp_mid());
- ice_candidate_proto.set_sdp_m_line_index(ice_candidate.sdp_mline_index());
- return ice_candidate_proto;
-}
-
-} // namespace webrtc_frames
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/signaling_frames.h b/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/signaling_frames.h
deleted file mode 100644
index 8be6a97b325..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/signaling_frames.h
+++ /dev/null
@@ -1,58 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_MEDIUMS_WEBRTC_SIGNALING_FRAMES_H_
-#define CORE_INTERNAL_MEDIUMS_WEBRTC_SIGNALING_FRAMES_H_
-
-#include <vector>
-
-#include "core/internal/mediums/webrtc_peer_id.h"
-#include "platform/base/byte_array.h"
-#include "proto/mediums/web_rtc_signaling_frames.pb.h"
-#include "webrtc/api/peer_connection_interface.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-namespace webrtc_frames {
-
-ByteArray EncodeReadyForSignalingPoke(const WebrtcPeerId& sender_id);
-
-ByteArray EncodeOffer(const WebrtcPeerId& sender_id,
- const webrtc::SessionDescriptionInterface& offer);
-ByteArray EncodeAnswer(const WebrtcPeerId& sender_id,
- const webrtc::SessionDescriptionInterface& answer);
-
-ByteArray EncodeIceCandidates(
- const WebrtcPeerId& sender_id,
- const std::vector<location::nearby::mediums::IceCandidate>& ice_candidates);
-location::nearby::mediums::IceCandidate EncodeIceCandidate(
- const webrtc::IceCandidateInterface& ice_candidate);
-
-std::unique_ptr<webrtc::SessionDescriptionInterface> DecodeOffer(
- const location::nearby::mediums::WebRtcSignalingFrame& frame);
-std::unique_ptr<webrtc::SessionDescriptionInterface> DecodeAnswer(
- const location::nearby::mediums::WebRtcSignalingFrame& frame);
-
-std::vector<std::unique_ptr<webrtc::IceCandidateInterface>> DecodeIceCandidates(
- const location::nearby::mediums::WebRtcSignalingFrame& frame);
-
-} // namespace webrtc_frames
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_MEDIUMS_WEBRTC_SIGNALING_FRAMES_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/signaling_frames_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/signaling_frames_test.cc
deleted file mode 100644
index 4105c7b78f3..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/signaling_frames_test.cc
+++ /dev/null
@@ -1,196 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/webrtc/signaling_frames.h"
-
-#include <memory>
-
-#include "google/protobuf/text_format.h"
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "core/internal/mediums/webrtc_peer_id.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-namespace webrtc_frames {
-
-namespace {
-
-const char kSampleSdp[] =
- "v=0\r\no=- 7859371131 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 "
- "0\r\na=msid-semantic: WMS\r\n";
-
-const char kIceCandidateSdp1[] =
- "a=candidate:1 1 UDP 2130706431 10.0.1.1 8998 typ host";
-const char kIceCandidateSdp2[] =
- "a=candidate:2 1 UDP 1694498815 192.0.2.3 45664 typ srflx raddr";
-
-const char kIceSdpMid[] = "data";
-const int kIceSdpMLineIndex = 0;
-
-const char kOfferProto[] = R"(
- sender_id { id: "abc" }
- type: OFFER_TYPE
- offer {
- session_description {
- description: "v=0\r\no=- 7859371131 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=msid-semantic: WMS\r\n"
- }
- }
- )";
-
-const char kAnswerProto[] = R"(
- sender_id { id: "abc" }
- type: ANSWER_TYPE
- answer {
- session_description {
- description: "v=0\r\no=- 7859371131 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=msid-semantic: WMS\r\n"
- }
- }
- )";
-
-const char kIceCandidatesProto[] = R"(
- sender_id { id: "abc" }
- type: ICE_CANDIDATES_TYPE
- ice_candidates {
- ice_candidates {
- sdp: "candidate:1 1 udp 2130706431 10.0.1.1 8998 typ host generation 0"
- sdp_mid: "data"
- sdp_m_line_index: 0
- }
- ice_candidates {
- sdp: "candidate:2 1 udp 1694498815 192.0.2.3 45664 typ srflx generation 0"
- sdp_mid: "data"
- sdp_m_line_index: 0
- }
- }
- )";
-} // namespace
-
-TEST(SignalingFramesTest, SignalingPoke) {
- WebrtcPeerId sender_id("abc");
- ByteArray encoded_poke = EncodeReadyForSignalingPoke(sender_id);
-
- location::nearby::mediums::WebRtcSignalingFrame frame;
- frame.ParseFromString(std::string(encoded_poke.data(), encoded_poke.size()));
-
- EXPECT_THAT(frame, testing::EqualsProto(R"pb(
- sender_id { id: "abc" }
- type: READY_FOR_SIGNALING_POKE_TYPE
- ready_for_signaling_poke {}
- )pb"));
-}
-
-TEST(SignalingFramesTest, EncodeValidOffer) {
- WebrtcPeerId sender_id("abc");
- std::unique_ptr<webrtc::SessionDescriptionInterface> offer =
- webrtc::CreateSessionDescription(webrtc::SdpType::kOffer, kSampleSdp);
- ByteArray encoded_offer = EncodeOffer(sender_id, *offer);
-
- location::nearby::mediums::WebRtcSignalingFrame frame;
- frame.ParseFromString(
- std::string(encoded_offer.data(), encoded_offer.size()));
-
- EXPECT_THAT(frame, testing::EqualsProto(kOfferProto));
-}
-
-TEST(SignaingFramesTest, DecodeValidOffer) {
- location::nearby::mediums::WebRtcSignalingFrame frame;
- proto2::TextFormat::ParseFromString(kOfferProto, &frame);
- std::unique_ptr<webrtc::SessionDescriptionInterface> decoded_offer =
- DecodeOffer(frame);
-
- EXPECT_EQ(webrtc::SdpType::kOffer, decoded_offer->GetType());
- std::string description;
- decoded_offer->ToString(&description);
- EXPECT_EQ(kSampleSdp, description);
-}
-
-TEST(SignalingFramesTest, EncodeValidAnswer) {
- WebrtcPeerId sender_id("abc");
- std::unique_ptr<webrtc::SessionDescriptionInterface> answer(
- webrtc::CreateSessionDescription(webrtc::SdpType::kAnswer, kSampleSdp));
- ByteArray encoded_answer = EncodeAnswer(sender_id, *answer);
-
- location::nearby::mediums::WebRtcSignalingFrame frame;
- frame.ParseFromString(
- std::string(encoded_answer.data(), encoded_answer.size()));
-
- EXPECT_THAT(frame, testing::EqualsProto(kAnswerProto));
-}
-
-TEST(SignalingFramesTest, DecodeValidAnswer) {
- location::nearby::mediums::WebRtcSignalingFrame frame;
- proto2::TextFormat::ParseFromString(kAnswerProto, &frame);
- std::unique_ptr<webrtc::SessionDescriptionInterface> decoded_answer =
- DecodeAnswer(frame);
-
- EXPECT_EQ(webrtc::SdpType::kAnswer, decoded_answer->GetType());
- std::string description;
- decoded_answer->ToString(&description);
- EXPECT_EQ(kSampleSdp, description);
-}
-
-TEST(SignalingFramesTest, EncodeValidIceCandidates) {
- WebrtcPeerId sender_id("abc");
- webrtc::SdpParseError error;
-
- std::vector<std::unique_ptr<webrtc::IceCandidateInterface>> ice_candidates;
- ice_candidates.emplace_back(webrtc::CreateIceCandidate(
- kIceSdpMid, kIceSdpMLineIndex, kIceCandidateSdp1, &error));
- ice_candidates.emplace_back(webrtc::CreateIceCandidate(
- kIceSdpMid, kIceSdpMLineIndex, kIceCandidateSdp2, &error));
- std::vector<location::nearby::mediums::IceCandidate> encoded_candidates_vec;
- for (const auto& ice_candidate : ice_candidates) {
- encoded_candidates_vec.push_back(EncodeIceCandidate(*ice_candidate));
- }
- ByteArray encoded_candidates =
- EncodeIceCandidates(sender_id, encoded_candidates_vec);
-
- location::nearby::mediums::WebRtcSignalingFrame frame;
- frame.ParseFromString(
- std::string(encoded_candidates.data(), encoded_candidates.size()));
-
- EXPECT_THAT(frame, testing::EqualsProto(kIceCandidatesProto));
-}
-
-TEST(SignalingFramesTest, DecodeValidIceCandidates) {
- webrtc::SdpParseError error;
- std::vector<std::unique_ptr<webrtc::IceCandidateInterface>> ice_candidates;
- ice_candidates.emplace_back(webrtc::CreateIceCandidate(
- kIceSdpMid, kIceSdpMLineIndex, kIceCandidateSdp1, &error));
- ice_candidates.emplace_back(webrtc::CreateIceCandidate(
- kIceSdpMid, kIceSdpMLineIndex, kIceCandidateSdp2, &error));
-
- location::nearby::mediums::WebRtcSignalingFrame frame;
- proto2::TextFormat::ParseFromString(kIceCandidatesProto, &frame);
- std::vector<std::unique_ptr<webrtc::IceCandidateInterface>>
- decoded_candidates = DecodeIceCandidates(frame);
-
- ASSERT_EQ(2u, decoded_candidates.size());
- for (int i = 0; i < static_cast<int>(decoded_candidates.size()); i++) {
- EXPECT_TRUE(ice_candidates[i]->candidate().IsEquivalent(
- decoded_candidates[i]->candidate()));
- EXPECT_EQ(ice_candidates[i]->sdp_mid(), decoded_candidates[i]->sdp_mid());
- EXPECT_EQ(ice_candidates[i]->sdp_mline_index(),
- decoded_candidates[i]->sdp_mline_index());
- }
-}
-
-} // namespace webrtc_frames
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/webrtc_socket.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/webrtc_socket.cc
deleted file mode 100644
index 0e4f34babab..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/webrtc_socket.cc
+++ /dev/null
@@ -1,190 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/webrtc/webrtc_socket.h"
-
-#include "platform/public/logging.h"
-#include "platform/public/mutex_lock.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-// OutputStreamImpl
-Exception WebRtcSocket::OutputStreamImpl::Write(const ByteArray& data) {
- if (data.size() > kMaxDataSize) {
- NEARBY_LOG(WARNING, "Sending data larger than 1MB");
- return {Exception::kIo};
- }
-
- socket_->BlockUntilSufficientSpaceInBuffer(data.size());
-
- if (socket_->IsClosed()) {
- NEARBY_LOG(WARNING, "Tried sending message while socket is closed");
- return {Exception::kIo};
- }
-
- if (!socket_->SendMessage(data)) {
- NEARBY_LOG(INFO, "Unable to write data to socket.");
- return {Exception::kIo};
- }
- return {Exception::kSuccess};
-}
-
-Exception WebRtcSocket::OutputStreamImpl::Flush() {
- // Java implementation is empty.
- return {Exception::kSuccess};
-}
-
-Exception WebRtcSocket::OutputStreamImpl::Close() {
- socket_->Close();
- return {Exception::kSuccess};
-}
-
-// WebRtcSocket
-WebRtcSocket::WebRtcSocket(
- const std::string& name,
- rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel)
- : name_(name), data_channel_(std::move(data_channel)) {
- NEARBY_LOGS(INFO) << "WebRtcSocket::WebRtcSocket(" << name_
- << ") this: " << this;
- data_channel_->RegisterObserver(this);
-}
-
-WebRtcSocket::~WebRtcSocket() {
- NEARBY_LOGS(INFO) << "WebRtcSocket::~WebRtcSocket(" << name_
- << ") this: " << this;
- Close();
- NEARBY_LOGS(INFO) << "WebRtcSocket::~WebRtcSocket(" << name_
- << ") this: " << this << " done";
-}
-
-InputStream& WebRtcSocket::GetInputStream() { return pipe_.GetInputStream(); }
-
-OutputStream& WebRtcSocket::GetOutputStream() { return output_stream_; }
-
-void WebRtcSocket::Close() {
- NEARBY_LOGS(INFO) << "WebRtcSocket::Close(" << name_ << ") this: " << this;
- if (closed_.Set(true)) return;
-
- ClosePipe();
- // NOTE: This call blocks and triggers a state change on the siginaling thread
- // to 'closing' but does not block until 'closed' is sent so the data channel
- // is not fully closed when this call is done.
- data_channel_->Close();
- NEARBY_LOGS(INFO) << "WebRtcSocket::Close(" << name_ << ") this: " << this
- << " done";
-}
-
-void WebRtcSocket::OnStateChange() {
- // Running on the signaling thread right now.
- NEARBY_LOGS(ERROR)
- << "WebRtcSocket::OnStateChange() webrtc data channel state: "
- << webrtc::DataChannelInterface::DataStateString(data_channel_->state());
- switch (data_channel_->state()) {
- case webrtc::DataChannelInterface::DataState::kConnecting:
- break;
- case webrtc::DataChannelInterface::DataState::kOpen:
- // We implicitly depend on the |socket_listener_| to offload from
- // the signaling thread so it does not get blocked.
- socket_listener_.socket_ready_cb(this);
- break;
- case webrtc::DataChannelInterface::DataState::kClosing:
- break;
- case webrtc::DataChannelInterface::DataState::kClosed:
- NEARBY_LOG(
- ERROR,
- "WebRtcSocket::OnStateChange() unregistering data channel observer.");
- data_channel_->UnregisterObserver();
- // This will trigger a destruction of the owning connection flow
- // We implicitly depend on the |socket_listener_| to offload from
- // the signaling thread so it does not get blocked.
- socket_listener_.socket_closed_cb(this);
-
- if (!closed_.Set(true)) {
- OffloadFromSignalingThread([this] { ClosePipe(); });
- }
- break;
- }
-}
-void WebRtcSocket::OnMessage(const webrtc::DataBuffer& buffer) {
- // This is a data channel callback on the signaling thread, lets off load so
- // we don't block signaling.
- OffloadFromSignalingThread(
- [this, buffer = ByteArray(buffer.data.data<char>(), buffer.size())] {
- if (!pipe_.GetOutputStream().Write(buffer).Ok()) {
- Close();
- return;
- }
-
- if (!pipe_.GetOutputStream().Flush().Ok()) {
- Close();
- }
- });
-}
-
-void WebRtcSocket::OnBufferedAmountChange(uint64_t sent_data_size) {
- // This is a data channel callback on the signaling thread, lets off load so
- // we don't block signaling.
- OffloadFromSignalingThread([this] { WakeUpWriter(); });
-}
-
-bool WebRtcSocket::SendMessage(const ByteArray& data) {
- return data_channel_->Send(
- webrtc::DataBuffer(std::string(data.data(), data.size())));
-}
-
-bool WebRtcSocket::IsClosed() { return closed_.Get(); }
-
-void WebRtcSocket::ClosePipe() {
- NEARBY_LOGS(INFO) << "WebRtcSocket::ClosePipe(" << name_
- << ") this: " << this;
- // This is thread-safe to close these sockets even if a read or write is in
- // process on another thread, Close will wait for the exclusive mutex before
- // setting state.
- pipe_.GetInputStream().Close();
- pipe_.GetOutputStream().Close();
- WakeUpWriter();
- NEARBY_LOGS(INFO) << "WebRtcSocket::ClosePipe(" << name_ << ") this: " << this
- << " done";
-}
-
-// Must not be called on signalling thread.
-void WebRtcSocket::WakeUpWriter() {
- MutexLock lock(&backpressure_mutex_);
- buffer_variable_.Notify();
-}
-
-void WebRtcSocket::SetSocketListener(SocketListener&& listener) {
- socket_listener_ = std::move(listener);
-}
-
-void WebRtcSocket::BlockUntilSufficientSpaceInBuffer(int length) {
- MutexLock lock(&backpressure_mutex_);
- while (!IsClosed() &&
- (data_channel_->buffered_amount() + length > kMaxDataSize)) {
- // TODO(himanshujaju): Add wait with timeout.
- buffer_variable_.Wait();
- }
-}
-
-void WebRtcSocket::OffloadFromSignalingThread(Runnable runnable) {
- single_thread_executor_.Execute(std::move(runnable));
-}
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/webrtc_socket.h b/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/webrtc_socket.h
deleted file mode 100644
index a65f2d5d9ed..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/webrtc_socket.h
+++ /dev/null
@@ -1,123 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_MEDIUMS_WEBRTC_WEBRTC_SOCKET_H_
-#define CORE_INTERNAL_MEDIUMS_WEBRTC_WEBRTC_SOCKET_H_
-
-#include <memory>
-
-#include "core/listeners.h"
-#include "platform/base/input_stream.h"
-#include "platform/base/output_stream.h"
-#include "platform/base/socket.h"
-#include "platform/public/atomic_boolean.h"
-#include "platform/public/condition_variable.h"
-#include "platform/public/mutex.h"
-#include "platform/public/pipe.h"
-#include "platform/public/single_thread_executor.h"
-#include "webrtc/api/data_channel_interface.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-// Maximum data size: 1 MB
-constexpr int kMaxDataSize = 1 * 1024 * 1024;
-
-// Defines the Socket implementation specific to WebRTC, which uses the WebRTC
-// data channel to send and receive messages.
-//
-// Messages are buffered here to prevent the data channel from overflowing,
-// which could lead to data loss.
-class WebRtcSocket : public Socket, public webrtc::DataChannelObserver {
- public:
- WebRtcSocket(const std::string& name,
- rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel);
- ~WebRtcSocket() override;
-
- WebRtcSocket(const WebRtcSocket& other) = delete;
- WebRtcSocket& operator=(const WebRtcSocket& other) = delete;
-
- // Overrides for location::nearby::Socket:
- InputStream& GetInputStream() override;
- OutputStream& GetOutputStream() override;
- void Close() override;
-
- // webrtc::DataChannelObserver:
- void OnStateChange() override;
- void OnMessage(const webrtc::DataBuffer& buffer) override;
- void OnBufferedAmountChange(uint64_t sent_data_size) override;
-
- // Listener class the gets called when the socket is ready or closed
- struct SocketListener {
- std::function<void(WebRtcSocket*)> socket_ready_cb =
- DefaultCallback<WebRtcSocket*>();
- std::function<void(WebRtcSocket*)> socket_closed_cb =
- DefaultCallback<WebRtcSocket*>();
- };
-
- void SetSocketListener(SocketListener&& listener);
-
- private:
- class OutputStreamImpl : public OutputStream {
- public:
- explicit OutputStreamImpl(WebRtcSocket* const socket) : socket_(socket) {}
- ~OutputStreamImpl() override = default;
-
- OutputStreamImpl(const OutputStreamImpl& other) = delete;
- OutputStreamImpl& operator=(const OutputStreamImpl& other) = delete;
-
- // OutputStream:
- Exception Write(const ByteArray& data) override;
- Exception Flush() override;
- Exception Close() override;
-
- private:
- // |this| OutputStreamImpl is owned by |socket_|.
- WebRtcSocket* const socket_;
- };
-
- void WakeUpWriter();
- bool IsClosed();
- void ClosePipe();
- bool SendMessage(const ByteArray& data);
- void BlockUntilSufficientSpaceInBuffer(int length);
- void OffloadFromSignalingThread(Runnable runnable);
-
- std::string name_;
- rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel_;
-
- Pipe pipe_;
-
- OutputStreamImpl output_stream_{this};
-
- AtomicBoolean closed_{false};
-
- SocketListener socket_listener_;
-
- mutable Mutex backpressure_mutex_;
- ConditionVariable buffer_variable_{&backpressure_mutex_};
-
- // This should be destroyed first to ensure any remaining tasks flushed on
- // shutdown get run while the other members are still alive.
- SingleThreadExecutor single_thread_executor_;
-};
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_MEDIUMS_WEBRTC_WEBRTC_SOCKET_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/webrtc_socket_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/webrtc_socket_test.cc
deleted file mode 100644
index 135a63345db..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc/webrtc_socket_test.cc
+++ /dev/null
@@ -1,234 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/webrtc/webrtc_socket.h"
-
-#include <memory>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "platform/base/byte_array.h"
-#include "webrtc/api/data_channel_interface.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-namespace {
-
-// using TestPlatform = platform::ImplementationPlatform;
-
-const char kSocketName[] = "TestSocket";
-
-class MockDataChannel
- : public rtc::RefCountedObject<webrtc::DataChannelInterface> {
- public:
- MOCK_METHOD(void, RegisterObserver, (webrtc::DataChannelObserver*));
- MOCK_METHOD(void, UnregisterObserver, ());
-
- MOCK_METHOD(std::string, label, (), (const));
-
- MOCK_METHOD(bool, reliable, (), (const));
- MOCK_METHOD(int, id, (), (const));
- MOCK_METHOD(DataState, state, (), (const));
- MOCK_METHOD(uint32_t, messages_sent, (), (const));
- MOCK_METHOD(uint64_t, bytes_sent, (), (const));
- MOCK_METHOD(uint32_t, messages_received, (), (const));
- MOCK_METHOD(uint64_t, bytes_received, (), (const));
-
- MOCK_METHOD(uint64_t, buffered_amount, (), (const));
-
- MOCK_METHOD(void, Close, ());
-
- MOCK_METHOD(bool, Send, (const webrtc::DataBuffer&));
-};
-
-} // namespace
-
-TEST(WebRtcSocketTest, ReadFromSocket) {
- const char* message = "message";
- rtc::scoped_refptr<MockDataChannel> mock_data_channel = new MockDataChannel();
- WebRtcSocket webrtc_socket(kSocketName, mock_data_channel);
-
- webrtc_socket.OnMessage(webrtc::DataBuffer{message});
- ExceptionOr<ByteArray> result = webrtc_socket.GetInputStream().Read(7);
- EXPECT_TRUE(result.ok());
- EXPECT_EQ(result.result(), ByteArray{message});
-}
-
-TEST(WebRtcSocketTest, ReadMultipleMessages) {
- rtc::scoped_refptr<MockDataChannel> mock_data_channel = new MockDataChannel();
- WebRtcSocket webrtc_socket(kSocketName, mock_data_channel);
-
- webrtc_socket.OnMessage(webrtc::DataBuffer{"Me"});
- webrtc_socket.OnMessage(webrtc::DataBuffer{"ssa"});
- webrtc_socket.OnMessage(webrtc::DataBuffer{"ge"});
-
- ExceptionOr<ByteArray> result;
-
- // This behaviour is different from the Java code
- result = webrtc_socket.GetInputStream().Read(7);
- EXPECT_TRUE(result.ok());
- EXPECT_EQ(result.result(), ByteArray{"Me"});
-
- result = webrtc_socket.GetInputStream().Read(7);
- EXPECT_TRUE(result.ok());
- EXPECT_EQ(result.result(), ByteArray{"ssa"});
-
- result = webrtc_socket.GetInputStream().Read(7);
- EXPECT_TRUE(result.ok());
- EXPECT_EQ(result.result(), ByteArray{"ge"});
-}
-
-TEST(WebRtcSocketTest, WriteToSocket) {
- const ByteArray kMessage{"Message"};
- rtc::scoped_refptr<MockDataChannel> mock_data_channel = new MockDataChannel();
- WebRtcSocket webrtc_socket(kSocketName, mock_data_channel);
-
- EXPECT_CALL(*mock_data_channel, Send(testing::_))
- .WillRepeatedly(testing::Return(true));
- EXPECT_TRUE(webrtc_socket.GetOutputStream().Write(kMessage).Ok());
-}
-
-TEST(WebRtcSocketTest, SendDataBiggerThanMax) {
- const ByteArray kMessage{kMaxDataSize + 1};
- rtc::scoped_refptr<MockDataChannel> mock_data_channel = new MockDataChannel();
- WebRtcSocket webrtc_socket(kSocketName, mock_data_channel);
-
- EXPECT_CALL(*mock_data_channel, Send(testing::_)).Times(0);
- EXPECT_EQ(webrtc_socket.GetOutputStream().Write(kMessage),
- Exception{Exception::kIo});
-}
-
-TEST(WebRtcSocketTest, WriteToDataChannelFails) {
- ByteArray kMessage{"Message"};
- rtc::scoped_refptr<MockDataChannel> mock_data_channel = new MockDataChannel();
- WebRtcSocket webrtc_socket(kSocketName, mock_data_channel);
-
- ON_CALL(*mock_data_channel, Send(testing::_))
- .WillByDefault(testing::Return(false));
- EXPECT_EQ(webrtc_socket.GetOutputStream().Write(kMessage),
- Exception{Exception::kIo});
-}
-
-TEST(WebRtcSocketTest, Close) {
- rtc::scoped_refptr<MockDataChannel> mock_data_channel = new MockDataChannel();
- WebRtcSocket webrtc_socket(kSocketName, mock_data_channel);
-
- EXPECT_CALL(*mock_data_channel, Close());
-
- int socket_closed_cb_called = 0;
-
- webrtc_socket.SetSocketListener(
- {.socket_closed_cb = [&](WebRtcSocket* socket) {
- socket_closed_cb_called++;
- }});
- webrtc_socket.Close();
-
- // We have to fake the close event to get the callback to run.
- ON_CALL(*mock_data_channel, state())
- .WillByDefault(
- testing::Return(webrtc::DataChannelInterface::DataState::kClosed));
-
- webrtc_socket.OnStateChange();
-
- EXPECT_EQ(socket_closed_cb_called, 1);
-}
-
-TEST(WebRtcSocketTest, WriteOnClosedChannel) {
- ByteArray kMessage{"Message"};
- rtc::scoped_refptr<MockDataChannel> mock_data_channel = new MockDataChannel();
- WebRtcSocket webrtc_socket(kSocketName, mock_data_channel);
- webrtc_socket.Close();
-
- EXPECT_CALL(*mock_data_channel, Send(testing::_)).Times(0);
- EXPECT_EQ(webrtc_socket.GetOutputStream().Write(kMessage),
- Exception{Exception::kIo});
-}
-
-TEST(WebRtcSocketTest, ReadFromClosedChannel) {
- ByteArray kMessage{"Message"};
- rtc::scoped_refptr<MockDataChannel> mock_data_channel = new MockDataChannel();
- WebRtcSocket webrtc_socket(kSocketName, mock_data_channel);
- ON_CALL(*mock_data_channel, Send(testing::_))
- .WillByDefault(testing::Return(true));
-
- webrtc_socket.GetOutputStream().Write(kMessage);
- webrtc_socket.Close();
-
- EXPECT_EQ(webrtc_socket.GetInputStream().Read(7).exception(), Exception::kIo);
-}
-
-TEST(WebRtcSocketTest, DataChannelCloseEventCleansUp) {
- rtc::scoped_refptr<MockDataChannel> mock_data_channel = new MockDataChannel();
- WebRtcSocket webrtc_socket(kSocketName, mock_data_channel);
-
- ON_CALL(*mock_data_channel, state())
- .WillByDefault(
- testing::Return(webrtc::DataChannelInterface::DataState::kClosed));
-
- webrtc_socket.OnStateChange();
-
- EXPECT_EQ(webrtc_socket.GetInputStream().Read(7).exception(), Exception::kIo);
-
- // Calling Close again should be safe even if the channel is already shut
- // down.
- webrtc_socket.Close();
-}
-
-TEST(WebRtcSocketTest, OpenStateTriggersCallback) {
- rtc::scoped_refptr<MockDataChannel> mock_data_channel = new MockDataChannel();
- WebRtcSocket webrtc_socket(kSocketName, mock_data_channel);
-
- int socket_ready_cb_called = 0;
-
- webrtc_socket.SetSocketListener(
- {.socket_ready_cb = [&](WebRtcSocket* socket) {
- socket_ready_cb_called++;
- }});
-
- ON_CALL(*mock_data_channel, state())
- .WillByDefault(
- testing::Return(webrtc::DataChannelInterface::DataState::kOpen));
-
- webrtc_socket.OnStateChange();
-
- EXPECT_EQ(socket_ready_cb_called, 1);
-}
-
-TEST(WebRtcSocketTest, CloseStateTriggersCallback) {
- rtc::scoped_refptr<MockDataChannel> mock_data_channel = new MockDataChannel();
- WebRtcSocket webrtc_socket(kSocketName, mock_data_channel);
-
- int socket_closed_cb_called = 0;
-
- webrtc_socket.SetSocketListener(
- {.socket_closed_cb = [&](WebRtcSocket* socket) {
- socket_closed_cb_called++;
- }});
-
- ON_CALL(*mock_data_channel, state())
- .WillByDefault(
- testing::Return(webrtc::DataChannelInterface::DataState::kClosed));
-
- webrtc_socket.OnStateChange();
-
- EXPECT_EQ(socket_closed_cb_called, 1);
-}
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc_peer_id.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc_peer_id.cc
deleted file mode 100644
index 9360357c2e2..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc_peer_id.cc
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/webrtc_peer_id.h"
-
-#include <sstream>
-
-#include "absl/strings/ascii.h"
-#include "absl/strings/escaping.h"
-#include "core/internal/mediums/utils.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-namespace {
-constexpr int kPeerIdLength = 64;
-
-std::string BytesToStringUppercase(const ByteArray& bytes) {
- std::string hex_string(
- absl::BytesToHexString(std::string(bytes.data(), bytes.size())));
- absl::AsciiStrToUpper(&hex_string);
- return hex_string;
-}
-} // namespace
-
-WebrtcPeerId WebrtcPeerId::FromRandom() {
- return FromSeed(Utils::GenerateRandomBytes(kPeerIdLength));
-}
-
-WebrtcPeerId WebrtcPeerId::FromSeed(const ByteArray& seed) {
- ByteArray full_hash(Utils::Sha256Hash(seed, kPeerIdLength));
- ByteArray hashed_seed(full_hash.data(), kPeerIdLength / 2);
- return WebrtcPeerId(BytesToStringUppercase(hashed_seed));
-}
-
-bool WebrtcPeerId::IsValid() const { return !id_.empty(); }
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc_peer_id.h b/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc_peer_id.h
deleted file mode 100644
index d2331b5a0d9..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc_peer_id.h
+++ /dev/null
@@ -1,52 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_MEDIUMS_WEBRTC_PEER_ID_H_
-#define CORE_INTERNAL_MEDIUMS_WEBRTC_PEER_ID_H_
-
-#include <memory>
-#include <string>
-
-#include "platform/base/byte_array.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-// WebrtcPeerId is used as an identifier to exchange SDP messages to establish
-// WebRTC p2p connection. An empty WebrtcPeerId is considered to be invalid.
-class WebrtcPeerId {
- public:
- WebrtcPeerId() = default;
- explicit WebrtcPeerId(const std::string& id) : id_(id) {}
- ~WebrtcPeerId() = default;
-
- static WebrtcPeerId FromRandom();
- static WebrtcPeerId FromSeed(const ByteArray& seed);
-
- bool IsValid() const;
-
- const std::string& GetId() const { return id_; }
-
- private:
- std::string id_;
-};
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_MEDIUMS_WEBRTC_PEER_ID_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc_peer_id_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc_peer_id_test.cc
deleted file mode 100644
index 612d213c023..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc_peer_id_test.cc
+++ /dev/null
@@ -1,56 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/webrtc_peer_id.h"
-
-#include <memory>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "platform/base/byte_array.h"
-#include "platform/public/crypto.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-TEST(WebrtcPeerIdTest, GenerateRandomPeerId) {
- WebrtcPeerId peer_id = WebrtcPeerId::FromRandom();
- EXPECT_EQ(64, peer_id.GetId().size());
-}
-
-TEST(WebrtcPeerIdTest, GenerateFromSeed) {
- // Values calculated by running actual SHA-256 hash on |seed|.
- std::string seed = "seed";
- std::string expected_peer_id =
- "19B25856E1C150CA834CFFC8B59B23ADBD0EC0389E58EB22B3B64768098D002B";
-
- ByteArray seed_bytes(seed);
- WebrtcPeerId peer_id = WebrtcPeerId::FromSeed(seed_bytes);
-
- EXPECT_EQ(64, peer_id.GetId().size());
- EXPECT_EQ(expected_peer_id, peer_id.GetId());
-}
-
-TEST(WebrtcPeerIdTest, GetId) {
- const std::string id = "this_is_a_test";
- WebrtcPeerId peer_id(id);
- EXPECT_EQ(id, peer_id.GetId());
-}
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc_socket_wrapper.h b/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc_socket_wrapper.h
deleted file mode 100644
index bc4671136b5..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc_socket_wrapper.h
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_MEDIUMS_WEBRTC_SOCKET_WRAPPER_H_
-#define CORE_INTERNAL_MEDIUMS_WEBRTC_SOCKET_WRAPPER_H_
-
-#include <memory>
-
-#include "core/internal/mediums/webrtc/webrtc_socket.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-class WebRtcSocketWrapper final {
- public:
- WebRtcSocketWrapper() = default;
- WebRtcSocketWrapper(const WebRtcSocketWrapper&) = default;
- WebRtcSocketWrapper& operator=(const WebRtcSocketWrapper&) = default;
- explicit WebRtcSocketWrapper(std::unique_ptr<WebRtcSocket> socket)
- : impl_(socket.release()) {}
- ~WebRtcSocketWrapper() = default;
-
- InputStream& GetInputStream() { return impl_->GetInputStream(); }
-
- OutputStream& GetOutputStream() { return impl_->GetOutputStream(); }
-
- void Close() { return impl_->Close(); }
-
- bool IsValid() const { return impl_ != nullptr; }
-
- WebRtcSocket& GetImpl() { return *impl_; }
-
- private:
- std::shared_ptr<WebRtcSocket> impl_;
-};
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_MEDIUMS_WEBRTC_WEBRTC_SOCKET_WRAPPER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc_test.cc
deleted file mode 100644
index 863e6ef7310..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/webrtc_test.cc
+++ /dev/null
@@ -1,405 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/webrtc.h"
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "core/internal/mediums/webrtc_socket_wrapper.h"
-#include "platform/base/listeners.h"
-#include "platform/base/medium_environment.h"
-#include "platform/public/mutex_lock.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace mediums {
-
-namespace {
-
-using FeatureFlags = FeatureFlags::Flags;
-
-constexpr FeatureFlags kTestCases[] = {
- FeatureFlags{
- .enable_cancellation_flag = true,
- },
- FeatureFlags{
- .enable_cancellation_flag = false,
- },
-};
-
-class WebRtcTest : public ::testing::TestWithParam<FeatureFlags> {
- protected:
- using MockAcceptedCallback =
- testing::MockFunction<void(WebRtcSocketWrapper socket)>;
-
- WebRtcTest() { env_.Stop(); }
-
- MediumEnvironment& env_{MediumEnvironment::Instance()};
-};
-
-// Tests the flow when the two devices exchange SDP messages and connect to each
-// other but the signaling channel is closed before sending the data.
-TEST_P(WebRtcTest, ConnectBothDevices_ShutdownSignaling_SendData) {
- env_.Start({.webrtc_enabled = true});
- FeatureFlags feature_flags = GetParam();
- env_.SetFeatureFlags(feature_flags);
- WebRtc receiver, sender;
- WebRtcSocketWrapper receiver_socket, sender_socket;
- const WebrtcPeerId self_id("self_id");
- const std::string service_id("NearbySharing");
- LocationHint location_hint;
- Future<bool> connected;
- ByteArray message("message xyz");
-
- receiver.StartAcceptingConnections(
- service_id, self_id, location_hint,
- {[&receiver_socket, connected](WebRtcSocketWrapper wrapper) mutable {
- receiver_socket = wrapper;
- connected.Set(receiver_socket.IsValid());
- }});
-
- CancellationFlag flag;
- sender_socket = sender.Connect(service_id, self_id, location_hint, &flag);
- EXPECT_TRUE(sender_socket.IsValid());
-
- ExceptionOr<bool> devices_connected = connected.Get();
- ASSERT_TRUE(devices_connected.ok());
- EXPECT_TRUE(devices_connected.result());
-
- // Only shuts down signaling channel.
- receiver.StopAcceptingConnections(service_id);
-
- sender_socket.GetOutputStream().Write(message);
- ExceptionOr<ByteArray> received_msg =
- receiver_socket.GetInputStream().Read(/*size=*/32);
- ASSERT_TRUE(received_msg.ok());
- EXPECT_EQ(message, received_msg.result());
- env_.Stop();
-}
-
-TEST_P(WebRtcTest, CanCancelConnect) {
- env_.Start({.webrtc_enabled = true});
- FeatureFlags feature_flags = GetParam();
- env_.SetFeatureFlags(feature_flags);
- WebRtc receiver, sender;
- WebRtcSocketWrapper receiver_socket, sender_socket;
- const WebrtcPeerId self_id("self_id");
- const std::string service_id("NearbySharing");
- LocationHint location_hint;
- Future<bool> connected;
- ByteArray message("message");
-
- receiver.StartAcceptingConnections(
- service_id, self_id, location_hint,
- {[&receiver_socket, connected](WebRtcSocketWrapper wrapper) mutable {
- receiver_socket = wrapper;
- connected.Set(receiver_socket.IsValid());
- }});
-
- CancellationFlag flag(true);
- sender_socket = sender.Connect(service_id, self_id, location_hint, &flag);
- // If FeatureFlag is disabled, Cancelled is false as no-op.
- if (!feature_flags.enable_cancellation_flag) {
- EXPECT_TRUE(sender_socket.IsValid());
-
- ExceptionOr<bool> devices_connected = connected.Get();
- ASSERT_TRUE(devices_connected.ok());
- EXPECT_TRUE(devices_connected.result());
-
- sender_socket.GetOutputStream().Write(message);
- ExceptionOr<ByteArray> received_msg =
- receiver_socket.GetInputStream().Read(/*size=*/32);
- ASSERT_TRUE(received_msg.ok());
- EXPECT_EQ(message, received_msg.result());
-
- receiver_socket.Close();
- } else {
- EXPECT_FALSE(sender_socket.IsValid());
- }
- env_.Stop();
-}
-
-INSTANTIATE_TEST_SUITE_P(ParametrisedWebRtcTest, WebRtcTest,
- ::testing::ValuesIn(kTestCases));
-
-// Basic test to check that device is accepting connections when initialized.
-TEST_F(WebRtcTest, NotAcceptingConnections) {
- env_.Start({.webrtc_enabled = true});
- WebRtc webrtc;
- ASSERT_TRUE(webrtc.IsAvailable());
- EXPECT_FALSE(webrtc.IsAcceptingConnections(std::string{}));
- env_.Stop();
-}
-
-// Tests the flow when the device tries to accept connections twice. In this
-// case, only the first call is successful and subsequent calls fail.
-TEST_F(WebRtcTest, StartAcceptingConnectionTwice) {
- env_.Start({.webrtc_enabled = true});
- testing::StrictMock<MockAcceptedCallback> mock_accepted_callback_;
- WebRtc webrtc;
- WebrtcPeerId self_id("peer_id");
- const std::string service_id("NearbySharing");
- LocationHint location_hint{};
-
- ASSERT_TRUE(webrtc.IsAvailable());
- ASSERT_TRUE(webrtc.StartAcceptingConnections(
- service_id, self_id, location_hint,
- {mock_accepted_callback_.AsStdFunction()}));
- EXPECT_FALSE(webrtc.StartAcceptingConnections(
- service_id, self_id, location_hint,
- {mock_accepted_callback_.AsStdFunction()}));
- EXPECT_TRUE(webrtc.IsAcceptingConnections(service_id));
- EXPECT_FALSE(webrtc.IsAcceptingConnections(std::string{}));
- env_.Stop();
-}
-
-// Tests the flow when the device tries to connect but there is no peer
-// accepting connections at the given peer ID.
-TEST_F(WebRtcTest, Connect_NoPeer) {
- env_.Start({.webrtc_enabled = true});
- WebRtc webrtc;
- WebrtcPeerId peer_id("peer_id");
- const std::string service_id("NearbySharing");
- LocationHint location_hint;
-
- ASSERT_TRUE(webrtc.IsAvailable());
- CancellationFlag flag;
- WebRtcSocketWrapper wrapper_1 =
- webrtc.Connect(service_id, peer_id, location_hint, &flag);
- EXPECT_FALSE(wrapper_1.IsValid());
-
- EXPECT_TRUE(webrtc.StartAcceptingConnections(
- service_id, peer_id, location_hint, AcceptedConnectionCallback()));
- env_.Stop();
-}
-
-// Tests the flow when the device calls Connect() after calling
-// StartAcceptingConnections() without StopAcceptingConnections().
-TEST_F(WebRtcTest, StartAcceptingConnection_ThenConnect) {
- env_.Start({.webrtc_enabled = true});
- testing::StrictMock<MockAcceptedCallback> mock_accepted_callback_;
- WebRtc webrtc;
- WebrtcPeerId self_id("peer_id");
- const std::string service_id("NearbySharing");
- LocationHint location_hint;
-
- ASSERT_TRUE(webrtc.IsAvailable());
- ASSERT_TRUE(webrtc.StartAcceptingConnections(
- service_id, self_id, location_hint,
- {mock_accepted_callback_.AsStdFunction()}));
- CancellationFlag flag;
- WebRtcSocketWrapper wrapper = webrtc.Connect(
- service_id, WebrtcPeerId("random_peer_id"), location_hint, &flag);
- EXPECT_TRUE(webrtc.IsAcceptingConnections(service_id));
- EXPECT_FALSE(wrapper.IsValid());
- EXPECT_FALSE(webrtc.StartAcceptingConnections(
- service_id, self_id, location_hint,
- {mock_accepted_callback_.AsStdFunction()}));
- env_.Stop();
-}
-
-// Tests the flow when the device calls StartAcceptingConnections but the medium
-// is closed before a peer device can connect to it.
-TEST_F(WebRtcTest, StartAndStopAcceptingConnections) {
- env_.Start({.webrtc_enabled = true});
- testing::StrictMock<MockAcceptedCallback> mock_accepted_callback_;
- WebRtc webrtc;
- WebrtcPeerId self_id("peer_id");
- const std::string service_id("NearbySharing");
- LocationHint location_hint;
-
- ASSERT_TRUE(webrtc.IsAvailable());
- ASSERT_TRUE(webrtc.StartAcceptingConnections(
- service_id, self_id, location_hint,
- {mock_accepted_callback_.AsStdFunction()}));
- EXPECT_TRUE(webrtc.IsAcceptingConnections(service_id));
- webrtc.StopAcceptingConnections(service_id);
- EXPECT_FALSE(webrtc.IsAcceptingConnections(service_id));
- env_.Stop();
-}
-
-// Tests the flow when the device tries to connect to two different peers
-// without disconnecting in between.
-TEST_F(WebRtcTest, ConnectTwice) {
- env_.Start({.webrtc_enabled = true});
- WebRtc receiver, sender, device_c;
- WebRtcSocketWrapper receiver_socket, sender_socket;
- const WebrtcPeerId self_id("self_id"), other_id("other_id");
- const std::string service_id("NearbySharing");
- LocationHint location_hint;
- Future<bool> connected;
- ByteArray message("message xyz");
-
- receiver.StartAcceptingConnections(
- service_id, self_id, location_hint,
- {[&receiver_socket, connected](WebRtcSocketWrapper wrapper) mutable {
- receiver_socket = wrapper;
- connected.Set(receiver_socket.IsValid());
- }});
-
- device_c.StartAcceptingConnections(service_id, other_id, location_hint,
- {[](WebRtcSocketWrapper wrapper) {}});
-
- CancellationFlag flag;
- sender_socket = sender.Connect(service_id, self_id, location_hint, &flag);
- EXPECT_TRUE(sender_socket.IsValid());
-
- ExceptionOr<bool> devices_connected = connected.Get();
- ASSERT_TRUE(devices_connected.ok());
- EXPECT_TRUE(devices_connected.result());
-
- WebRtcSocketWrapper socket =
- sender.Connect(service_id, other_id, location_hint, &flag);
- EXPECT_TRUE(socket.IsValid());
- socket.Close();
-
- EXPECT_TRUE(receiver_socket.IsValid());
- EXPECT_TRUE(sender_socket.IsValid());
-
- sender_socket.GetOutputStream().Write(message);
- ExceptionOr<ByteArray> received_msg =
- receiver_socket.GetInputStream().Read(/*size=*/32);
- ASSERT_TRUE(received_msg.ok());
- EXPECT_EQ(message, received_msg.result());
-
- receiver_socket.Close();
- env_.Stop();
-}
-
-// Tests the flow when the two devices exchange SDP messages and connect to each
-// other but disconnect before being able to send/receive the actual data.
-TEST_F(WebRtcTest, ConnectBothDevicesAndAbort) {
- env_.Start({.webrtc_enabled = true});
- WebRtc receiver, sender;
- WebRtcSocketWrapper receiver_socket, sender_socket;
- const WebrtcPeerId self_id("self_id");
- const std::string service_id("NearbySharing");
- LocationHint location_hint;
- Future<bool> connected;
- ByteArray message("message xyz");
-
- receiver.StartAcceptingConnections(
- service_id, self_id, location_hint,
- {[&receiver_socket, connected](WebRtcSocketWrapper wrapper) mutable {
- receiver_socket = wrapper;
- connected.Set(receiver_socket.IsValid());
- }});
-
- CancellationFlag flag;
- sender_socket = sender.Connect(service_id, self_id, location_hint, &flag);
- EXPECT_TRUE(sender_socket.IsValid());
-
- ExceptionOr<bool> devices_connected = connected.Get();
- ASSERT_TRUE(devices_connected.ok());
- EXPECT_TRUE(devices_connected.result());
-
- receiver_socket.Close();
- env_.Stop();
-}
-
-// Tests the flow when the two devices exchange SDP messages and connect to each
-// other and the actual data is exchanged successfully between the devices.
-TEST_F(WebRtcTest, ConnectBothDevicesAndSendData) {
- env_.Start({.webrtc_enabled = true});
- WebRtc receiver, sender;
- WebRtcSocketWrapper receiver_socket, sender_socket;
- const WebrtcPeerId self_id("self_id");
- const std::string service_id("NearbySharing");
- LocationHint location_hint;
- Future<bool> connected;
- ByteArray message("message");
-
- receiver.StartAcceptingConnections(
- service_id, self_id, location_hint,
- {[&receiver_socket, connected](WebRtcSocketWrapper wrapper) mutable {
- receiver_socket = wrapper;
- connected.Set(receiver_socket.IsValid());
- }});
-
- CancellationFlag flag;
- sender_socket = sender.Connect(service_id, self_id, location_hint, &flag);
- EXPECT_TRUE(sender_socket.IsValid());
-
- ExceptionOr<bool> devices_connected = connected.Get();
- ASSERT_TRUE(devices_connected.ok());
- EXPECT_TRUE(devices_connected.result());
-
- sender_socket.GetOutputStream().Write(message);
- ExceptionOr<ByteArray> received_msg =
- receiver_socket.GetInputStream().Read(/*size=*/32);
- ASSERT_TRUE(received_msg.ok());
- EXPECT_EQ(message, received_msg.result());
-
- receiver_socket.Close();
- env_.Stop();
-}
-
-TEST_F(WebRtcTest, Connect_NullPeerConnection) {
- env_.Start({.webrtc_enabled = true});
- testing::StrictMock<MockAcceptedCallback> mock_accepted_callback_;
- env_.SetUseValidPeerConnection(
- /*use_valid_peer_connection=*/false);
-
- WebRtc webrtc;
- const std::string service_id("NearbySharing");
- WebrtcPeerId self_id("peer_id");
- LocationHint location_hint;
-
- ASSERT_TRUE(webrtc.IsAvailable());
- CancellationFlag flag;
- WebRtcSocketWrapper wrapper = webrtc.Connect(
- service_id, WebrtcPeerId("random_peer_id"), location_hint, &flag);
- EXPECT_FALSE(wrapper.IsValid());
- env_.Stop();
-}
-
-// Tests the flow when the device calls StartAcceptingConnections and the
-// receive messages stream fails.
-TEST_F(WebRtcTest, ContinueAcceptingConnectionsOnComplete) {
- env_.Start({.webrtc_enabled = true});
- testing::StrictMock<MockAcceptedCallback> mock_accepted_callback_;
- WebRtc webrtc;
- WebrtcPeerId self_id("peer_id");
- const std::string service_id("NearbySharing");
- LocationHint location_hint;
-
- ASSERT_TRUE(webrtc.IsAvailable());
- ASSERT_TRUE(webrtc.StartAcceptingConnections(
- service_id, self_id, location_hint,
- {mock_accepted_callback_.AsStdFunction()}));
- EXPECT_TRUE(webrtc.IsAcceptingConnections(service_id));
-
- // Simulate a failure in receiving messages stream, WebRtc should restart
- // accepting connections.
- env_.SendWebRtcSignalingComplete(self_id.GetId(),
- /*success=*/false);
- EXPECT_TRUE(webrtc.IsAcceptingConnections(service_id));
-
- // And a "success" message should not cause accepting connections to stop.
- env_.SendWebRtcSignalingComplete(self_id.GetId(),
- /*success=*/true);
- EXPECT_TRUE(webrtc.IsAcceptingConnections(service_id));
-
- webrtc.StopAcceptingConnections(service_id);
- EXPECT_FALSE(webrtc.IsAcceptingConnections(service_id));
- env_.Stop();
-}
-
-} // namespace
-
-} // namespace mediums
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/wifi_lan.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/wifi_lan.cc
deleted file mode 100644
index 9e24c5fe2e3..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/wifi_lan.cc
+++ /dev/null
@@ -1,409 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/wifi_lan.h"
-
-#include <memory>
-#include <string>
-#include <utility>
-
-#include "absl/strings/str_format.h"
-#include "core/internal/mediums/utils.h"
-#include "platform/public/logging.h"
-#include "platform/public/mutex_lock.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-WifiLan::~WifiLan() {
- // Destructor is not taking locks, but methods it is calling are.
- while (!discovering_info_.service_ids.empty()) {
- StopDiscovery(*discovering_info_.service_ids.begin());
- }
- while (!server_sockets_.empty()) {
- StopAcceptingConnections(server_sockets_.begin()->first);
- }
- while (!advertising_info_.nsd_service_infos.empty()) {
- StopAdvertising(advertising_info_.nsd_service_infos.begin()->first);
- }
-
- // All the AcceptLoopRunnable objects in here should already have gotten an
- // opportunity to shut themselves down cleanly in the calls to
- // StopAcceptingConnections() above.
- accept_loops_runner_.Shutdown();
-}
-
-bool WifiLan::IsAvailable() const {
- MutexLock lock(&mutex_);
-
- return IsAvailableLocked();
-}
-
-bool WifiLan::IsAvailableLocked() const { return medium_.IsValid(); }
-
-bool WifiLan::StartAdvertising(const std::string& service_id,
- NsdServiceInfo& nsd_service_info) {
- MutexLock lock(&mutex_);
-
- if (!IsAvailableLocked()) {
- NEARBY_LOGS(INFO)
- << "Can't turn on WifiLan advertising. WifiLan is not available.";
- return false;
- }
-
- if (!nsd_service_info.IsValid()) {
- NEARBY_LOGS(INFO)
- << "Refusing to turn on WifiLan advertising. nsd_service_info is not "
- "valid.";
- return false;
- }
-
- if (IsAdvertisingLocked(service_id)) {
- NEARBY_LOGS(INFO)
- << "Failed to WifiLan advertise because we're already advertising.";
- return false;
- }
-
- if (!IsAcceptingConnectionsLocked(service_id)) {
- NEARBY_LOGS(INFO)
- << "Failed to turn on WifiLan advertising with nsd_service_info="
- << &nsd_service_info
- << ", service_name=" << nsd_service_info.GetServiceName()
- << ", service_id=" << service_id
- << ". Should accept connections before advertising.";
- return false;
- }
-
- nsd_service_info.SetServiceType(GenerateServiceType(service_id));
- const auto& it = server_sockets_.find(service_id);
- if (it != server_sockets_.end()) {
- nsd_service_info.SetIPAddress(it->second.GetIPAddress());
- nsd_service_info.SetPort(it->second.GetPort());
- }
- if (!medium_.StartAdvertising(nsd_service_info)) {
- NEARBY_LOGS(INFO)
- << "Failed to turn on WifiLan advertising with nsd_service_info="
- << &nsd_service_info
- << ", service_name=" << nsd_service_info.GetServiceName()
- << ", service_id=" << service_id;
- return false;
- }
-
- NEARBY_LOGS(INFO) << "Turned on WifiLan advertising with nsd_service_info="
- << &nsd_service_info
- << ", service_name=" << nsd_service_info.GetServiceName()
- << ", service_id=" << service_id;
- advertising_info_.Add(service_id, std::move(nsd_service_info));
- return true;
-}
-
-bool WifiLan::StopAdvertising(const std::string& service_id) {
- MutexLock lock(&mutex_);
-
- if (!IsAdvertisingLocked(service_id)) {
- NEARBY_LOGS(INFO)
- << "Can't turn off WifiLan advertising; it is already off";
- return false;
- }
-
- NEARBY_LOGS(INFO) << "Turned off WifiLan advertising with service_id="
- << service_id;
- bool ret =
- medium_.StopAdvertising(*advertising_info_.GetServiceInfo(service_id));
- // Reset our bundle of advertising state to mark that we're no longer
- // advertising for specific service_id.
- advertising_info_.Remove(service_id);
- return ret;
-}
-
-bool WifiLan::IsAdvertising(const std::string& service_id) {
- MutexLock lock(&mutex_);
-
- return IsAdvertisingLocked(service_id);
-}
-
-bool WifiLan::IsAdvertisingLocked(const std::string& service_id) {
- return advertising_info_.Existed(service_id);
-}
-
-bool WifiLan::StartDiscovery(const std::string& service_id,
- DiscoveredServiceCallback callback) {
- MutexLock lock(&mutex_);
-
- if (service_id.empty()) {
- NEARBY_LOGS(INFO)
- << "Refusing to start WifiLan discovering with empty service_id.";
- return false;
- }
-
- if (!IsAvailableLocked()) {
- NEARBY_LOGS(INFO)
- << "Can't discover WifiLan services because WifiLan isn't available.";
- return false;
- }
-
- if (IsDiscoveringLocked(service_id)) {
- NEARBY_LOGS(INFO)
- << "Refusing to start discovery of WifiLan services because another "
- "discovery is already in-progress.";
- return false;
- }
-
- std::string service_type = GenerateServiceType(service_id);
- bool ret = medium_.StartDiscovery(service_id, service_type, callback);
- if (!ret) {
- NEARBY_LOGS(INFO) << "Failed to start discovery of WifiLan services.";
- return false;
- }
-
- NEARBY_LOGS(INFO) << "Turned on WifiLan discovering with service_id="
- << service_id;
- // Mark the fact that we're currently performing a WifiLan discovering.
- discovering_info_.Add(service_id);
- return true;
-}
-
-bool WifiLan::StopDiscovery(const std::string& service_id) {
- MutexLock lock(&mutex_);
-
- if (!IsDiscoveringLocked(service_id)) {
- NEARBY_LOGS(INFO)
- << "Can't turn off WifiLan discovering because we never started "
- "discovering.";
- return false;
- }
-
- std::string service_type = GenerateServiceType(service_id);
- NEARBY_LOGS(INFO) << "Turned off WifiLan discovering with service_id="
- << service_id << ", service_type=" << service_type;
- bool ret = medium_.StopDiscovery(service_type);
- discovering_info_.Remove(service_id);
- return ret;
-}
-
-bool WifiLan::IsDiscovering(const std::string& service_id) {
- MutexLock lock(&mutex_);
- return IsDiscoveringLocked(service_id);
-}
-
-bool WifiLan::IsDiscoveringLocked(const std::string& service_id) {
- return discovering_info_.Existed(service_id);
-}
-
-bool WifiLan::StartAcceptingConnections(const std::string& service_id,
- AcceptedConnectionCallback callback) {
- MutexLock lock(&mutex_);
-
- if (service_id.empty()) {
- NEARBY_LOGS(INFO) << "Refusing to start accepting WifiLan connections; "
- "service_id is empty.";
- return false;
- }
-
- if (!IsAvailableLocked()) {
- NEARBY_LOGS(INFO)
- << "Can't start accepting WifiLan connections [service_id="
- << service_id << "]; WifiLan not available.";
- return false;
- }
-
- if (IsAcceptingConnectionsLocked(service_id)) {
- NEARBY_LOGS(INFO)
- << "Refusing to start accepting WifiLan connections [service="
- << service_id
- << "]; WifiLan server is already in-progress with the same name.";
- return false;
- }
-
- // We can generate an exact port here on server socket; now we just assign 0
- // to let platform medium decide it.
- int port = 0;
- WifiLanServerSocket server_socket = medium_.ListenForService(port);
- if (!server_socket.IsValid()) {
- NEARBY_LOGS(INFO)
- << "Failed to start accepting WifiLan connections for service_id="
- << service_id;
- return false;
- }
-
- // Mark the fact that there's an in-progress WifiLan server accepting
- // connections.
- auto owned_server_socket =
- server_sockets_.insert({service_id, std::move(server_socket)})
- .first->second;
-
- // Start the accept loop on a dedicated thread - this stays alive and
- // listening for new incoming connections until StopAcceptingConnections() is
- // invoked.
- accept_loops_runner_.Execute(
- "wifi-lan-accept",
- [callback = std::move(callback),
- server_socket = std::move(owned_server_socket)]() mutable {
- while (true) {
- WifiLanSocket client_socket = server_socket.Accept();
- if (!client_socket.IsValid()) {
- server_socket.Close();
- break;
- }
- callback.accepted_cb(std::move(client_socket));
- }
- });
-
- return true;
-}
-
-bool WifiLan::StopAcceptingConnections(const std::string& service_id) {
- MutexLock lock(&mutex_);
-
- if (service_id.empty()) {
- NEARBY_LOGS(INFO) << "Unable to stop accepting WifiLan connections because "
- "the service_id is empty.";
- return false;
- }
-
- const auto& it = server_sockets_.find(service_id);
- if (it == server_sockets_.end()) {
- NEARBY_LOGS(INFO) << "Can't stop accepting WifiLan connections for "
- << service_id << " because it was never started.";
- return false;
- }
-
- // Closing the WifiLanServerSocket will kick off the suicide of the thread
- // in accept_loops_thread_pool_ that blocks on WifiLanServerSocket.accept().
- // That may take some time to complete, but there's no particular reason to
- // wait around for it.
- auto item = server_sockets_.extract(it);
-
- // Store a handle to the WifiLanServerSocket, so we can use it after
- // removing the entry from server_sockets_; making it scoped
- // is a bonus that takes care of deallocation before we leave this method.
- WifiLanServerSocket& listening_socket = item.mapped();
-
- // Regardless of whether or not we fail to close the existing
- // WifiLanServerSocket, remove it from server_sockets_ so that it
- // frees up this service for another round.
-
- // Finally, close the WifiLanServerSocket.
- if (!listening_socket.Close().Ok()) {
- NEARBY_LOGS(INFO) << "Failed to close WifiLan server socket for service_id="
- << service_id;
- return false;
- }
-
- return true;
-}
-
-bool WifiLan::IsAcceptingConnections(const std::string& service_id) {
- MutexLock lock(&mutex_);
- return IsAcceptingConnectionsLocked(service_id);
-}
-
-bool WifiLan::IsAcceptingConnectionsLocked(const std::string& service_id) {
- return server_sockets_.find(service_id) != server_sockets_.end();
-}
-
-WifiLanSocket WifiLan::Connect(const std::string& service_id,
- const NsdServiceInfo& service_info,
- CancellationFlag* cancellation_flag) {
- MutexLock lock(&mutex_);
- // Socket to return. To allow for NRVO to work, it has to be a single object.
- WifiLanSocket socket;
-
- if (service_id.empty()) {
- NEARBY_LOGS(INFO) << "Refusing to create client WifiLan socket because "
- "service_id is empty.";
- return socket;
- }
-
- if (!IsAvailableLocked()) {
- NEARBY_LOGS(INFO) << "Can't create client WifiLan socket [service_id="
- << service_id << "]; WifiLan isn't available.";
- return socket;
- }
-
- if (cancellation_flag->Cancelled()) {
- NEARBY_LOGS(INFO) << "Can't create client WifiLan socket due to cancel.";
- return socket;
- }
-
- socket = medium_.ConnectToService(service_info, cancellation_flag);
- if (!socket.IsValid()) {
- NEARBY_LOGS(INFO) << "Failed to Connect via WifiLan [service_id="
- << service_id << "]";
- }
-
- return socket;
-}
-
-WifiLanSocket WifiLan::Connect(const std::string& service_id,
- const std::string& ip_address, int port,
- CancellationFlag* cancellation_flag) {
- MutexLock lock(&mutex_);
- // Socket to return. To allow for NRVO to work, it has to be a single object.
- WifiLanSocket socket;
-
- if (service_id.empty()) {
- NEARBY_LOGS(INFO) << "Refusing to create client WifiLan socket because "
- "service_id is empty.";
- return socket;
- }
-
- if (!IsAvailableLocked()) {
- NEARBY_LOGS(INFO) << "Can't create client WifiLan socket [service_id="
- << service_id << "]; WifiLan isn't available.";
- return socket;
- }
-
- if (cancellation_flag->Cancelled()) {
- NEARBY_LOGS(INFO) << "Can't create client WifiLan socket due to cancel.";
- return socket;
- }
-
- socket = medium_.ConnectToService(ip_address, port, cancellation_flag);
- if (!socket.IsValid()) {
- NEARBY_LOGS(INFO) << "Failed to Connect via WifiLan [service_id="
- << service_id << "]";
- }
-
- return socket;
-}
-
-std::pair<std::string, int> WifiLan::GetCredentials(
- const std::string& service_id) {
- MutexLock lock(&mutex_);
- const auto& it = server_sockets_.find(service_id);
- if (it == server_sockets_.end()) {
- return std::pair<std::string, int>();
- }
- return std::pair<std::string, int>(it->second.GetIPAddress(),
- it->second.GetPort());
-}
-
-std::string WifiLan::GenerateServiceType(const std::string& service_id) {
- std::string service_id_hash_string;
-
- const ByteArray service_id_hash = Utils::Sha256Hash(
- service_id, NsdServiceInfo::kTypeFromServiceIdHashLength);
- for (auto byte : std::string(service_id_hash)) {
- absl::StrAppend(&service_id_hash_string, absl::StrFormat("%02X", byte));
- }
-
- return absl::StrFormat(NsdServiceInfo::kNsdTypeFormat,
- service_id_hash_string);
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/wifi_lan.h b/chromium/third_party/nearby/src/cpp/core/internal/mediums/wifi_lan.h
deleted file mode 100644
index dc5300f7d1f..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/wifi_lan.h
+++ /dev/null
@@ -1,194 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_MEDIUMS_WIFI_LAN_H_
-#define CORE_INTERNAL_MEDIUMS_WIFI_LAN_H_
-
-#include <cstdint>
-#include <string>
-
-#include "absl/container/flat_hash_map.h"
-#include "absl/container/flat_hash_set.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/cancellation_flag.h"
-#include "platform/base/nsd_service_info.h"
-#include "platform/public/multi_thread_executor.h"
-#include "platform/public/mutex.h"
-#include "platform/public/wifi_lan.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-class WifiLan {
- public:
- using DiscoveredServiceCallback = WifiLanMedium::DiscoveredServiceCallback;
-
- // Callback that is invoked when a new connection is accepted.
- struct AcceptedConnectionCallback {
- std::function<void(WifiLanSocket socket)> accepted_cb =
- DefaultCallback<WifiLanSocket>();
- };
-
- WifiLan() = default;
- ~WifiLan();
-
- // Returns true, if WifiLan communications are supported by a platform.
- bool IsAvailable() const ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Sets custom service info name, endpoint info name in NsdServiceInfo and
- // then enables WifiLan advertising.
- // Returns true, if NsdServiceInfo is successfully set, and false otherwise.
- bool StartAdvertising(const std::string& service_id,
- NsdServiceInfo& nsd_service_info)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Disables WifiLan advertising.
- // Returns false if no successful call StartAdvertising() was previously
- // made, otherwise returns true.
- bool StopAdvertising(const std::string& service_id)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- bool IsAdvertising(const std::string& service_id) ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Enables WifiLan discovery. Will report any discoverable services
- // through a callback.
- // Returns true, if discovery was enabled, false otherwise.
- bool StartDiscovery(const std::string& service_id,
- DiscoveredServiceCallback callback)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Disables WifiLan discovery.
- bool StopDiscovery(const std::string& service_id) ABSL_LOCKS_EXCLUDED(mutex_);
-
- bool IsDiscovering(const std::string& service_id) ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Starts a worker thread, creates a WifiLan socket, associates it with a
- // service id.
- bool StartAcceptingConnections(const std::string& service_id,
- AcceptedConnectionCallback callback)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Closes socket corresponding to a service id.
- bool StopAcceptingConnections(const std::string& service_id)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- bool IsAcceptingConnections(const std::string& service_id)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Establishes connection to WifiLan service that was might be started on
- // another service with StartAcceptingConnections() using the same service_id.
- // Blocks until connection is established, or server-side is terminated.
- // Returns socket instance. On success, WifiLanSocket.IsValid() return true.
- WifiLanSocket Connect(const std::string& service_id,
- const NsdServiceInfo& service_info,
- CancellationFlag* cancellation_flag)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Establishes connection to WifiLan service by ip address and port for
- // bandwidth upgradation.
- // Returns socket instance. On success, WifiLanSocket.IsValid() return true.
- WifiLanSocket Connect(const std::string& service_id,
- const std::string& ip_address, int port,
- CancellationFlag* cancellation_flag)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Gets ip address + port for remote services on the network to identify and
- // connect to this service.
- //
- // Credential is for the currently-hosted Wifi ServerSocket (if any).
- std::pair<std::string, int> GetCredentials(const std::string& service_id)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- private:
- struct AdvertisingInfo {
- bool Empty() const { return nsd_service_infos.empty(); }
- void Clear() { nsd_service_infos.clear(); }
- void Add(const std::string& service_id,
- const NsdServiceInfo& nsd_service_info) {
- nsd_service_infos.insert({service_id, nsd_service_info});
- }
- void Remove(const std::string& service_id) {
- nsd_service_infos.erase(service_id);
- }
- bool Existed(const std::string& service_id) const {
- return nsd_service_infos.contains(service_id);
- }
- NsdServiceInfo* GetServiceInfo(const std::string& service_id) {
- const auto& it = nsd_service_infos.find(service_id);
- if (it == nsd_service_infos.end()) {
- return nullptr;
- }
- return &it->second;
- }
-
- absl::flat_hash_map<std::string, NsdServiceInfo> nsd_service_infos;
- };
-
- struct DiscoveringInfo {
- bool Empty() const { return service_ids.empty(); }
- void Clear() { service_ids.clear(); }
- void Add(const std::string& service_id) { service_ids.insert(service_id); }
- void Remove(const std::string& service_id) {
- service_ids.erase(service_id);
- }
- bool Existed(const std::string& service_id) const {
- return service_ids.contains(service_id);
- }
-
- absl::flat_hash_set<std::string> service_ids;
- };
-
- static constexpr int kMaxConcurrentAcceptLoops = 5;
-
- // Same as IsAvailable(), but must be called with mutex_ held.
- bool IsAvailableLocked() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Same as IsAdvertising(), but must be called with mutex_ held.
- bool IsAdvertisingLocked(const std::string& service_id)
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Same as IsDiscovering(), but must be called with mutex_ held.
- bool IsDiscoveringLocked(const std::string& service_id)
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Same as IsAcceptingConnections(), but must be called with mutex_ held.
- bool IsAcceptingConnectionsLocked(const std::string& service_id)
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Generates mDNS type.
- std::string GenerateServiceType(const std::string& service_id);
-
- mutable Mutex mutex_;
- WifiLanMedium medium_ ABSL_GUARDED_BY(mutex_);
- AdvertisingInfo advertising_info_ ABSL_GUARDED_BY(mutex_);
- DiscoveringInfo discovering_info_ ABSL_GUARDED_BY(mutex_);
-
- // A thread pool dedicated to running all the accept loops from
- // StartAcceptingConnections().
- MultiThreadExecutor accept_loops_runner_{kMaxConcurrentAcceptLoops};
-
- // A map of service_id -> ServerSocket. If map is non-empty, we
- // are currently listening for incoming connections.
- // WifiLanServerSocket instances are used from accept_loops_runner_,
- // and thus require pointer stability.
- absl::flat_hash_map<std::string, WifiLanServerSocket> server_sockets_
- ABSL_GUARDED_BY(mutex_);
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_MEDIUMS_WIFI_LAN_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mediums/wifi_lan_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/mediums/wifi_lan_test.cc
deleted file mode 100644
index 4640363b98d..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mediums/wifi_lan_test.cc
+++ /dev/null
@@ -1,347 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/mediums/wifi_lan.h"
-
-#include <string>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/strings/string_view.h"
-#include "platform/base/medium_environment.h"
-#include "platform/base/nsd_service_info.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/logging.h"
-#include "platform/public/wifi_lan.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-
-using FeatureFlags = FeatureFlags::Flags;
-
-constexpr FeatureFlags kTestCases[] = {
- FeatureFlags{
- .enable_cancellation_flag = true,
- },
- FeatureFlags{
- .enable_cancellation_flag = false,
- },
-};
-
-constexpr absl::Duration kWaitDuration = absl::Milliseconds(1000);
-constexpr absl::string_view kServiceID{"com.google.location.nearby.apps.test"};
-constexpr absl::string_view kServiceInfoName{"ServiceInfoName"};
-constexpr absl::string_view kEndpointName{"EndpointName"};
-constexpr absl::string_view kEndpointInfoKey{"n"};
-
-class WifiLanTest : public ::testing::TestWithParam<FeatureFlags> {
- protected:
- using DiscoveredServiceCallback = WifiLanMedium::DiscoveredServiceCallback;
-
- WifiLanTest() { env_.Stop(); }
-
- MediumEnvironment& env_{MediumEnvironment::Instance()};
-};
-
-TEST_P(WifiLanTest, CanConnect) {
- FeatureFlags feature_flags = GetParam();
- env_.SetFeatureFlags(feature_flags);
- env_.Start();
- WifiLan wifi_lan_client;
- WifiLan wifi_lan_server;
- std::string service_id(kServiceID);
- std::string service_info_name(kServiceInfoName);
- std::string endpoint_info_name(kEndpointName);
- CountDownLatch discovered_latch(1);
- CountDownLatch accept_latch(1);
-
- WifiLanSocket socket_for_server;
- EXPECT_TRUE(wifi_lan_server.StartAcceptingConnections(
- service_id,
- {
- .accepted_cb =
- [&socket_for_server, &accept_latch](WifiLanSocket socket) {
- socket_for_server = std::move(socket);
- accept_latch.CountDown();
- },
- }));
-
- NsdServiceInfo nsd_service_info;
- nsd_service_info.SetServiceName(service_info_name);
- nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
- endpoint_info_name);
- wifi_lan_server.StartAdvertising(service_id, nsd_service_info);
-
- NsdServiceInfo discovered_service_info;
- wifi_lan_client.StartDiscovery(
- service_id,
- {
- .service_discovered_cb =
- [&discovered_latch, &discovered_service_info](
- NsdServiceInfo service_info, const std::string& service_id) {
- NEARBY_LOGS(INFO)
- << "Discovered service_info=" << &service_info;
- discovered_service_info = service_info;
- discovered_latch.CountDown();
- },
- });
- discovered_latch.Await(kWaitDuration).result();
- ASSERT_TRUE(discovered_service_info.IsValid());
-
- CancellationFlag flag;
- WifiLanSocket socket_for_client =
- wifi_lan_client.Connect(service_id, discovered_service_info, &flag);
- EXPECT_TRUE(accept_latch.Await(kWaitDuration).result());
- EXPECT_TRUE(wifi_lan_server.StopAcceptingConnections(service_id));
- EXPECT_TRUE(wifi_lan_server.StopAdvertising(service_id));
- EXPECT_TRUE(socket_for_server.IsValid());
- EXPECT_TRUE(socket_for_client.IsValid());
- env_.Stop();
-}
-
-TEST_P(WifiLanTest, CanCancelConnect) {
- FeatureFlags feature_flags = GetParam();
- env_.SetFeatureFlags(feature_flags);
- env_.Start();
- WifiLan wifi_lan_client;
- WifiLan wifi_lan_server;
- std::string service_id(kServiceID);
- std::string service_info_name(kServiceInfoName);
- std::string endpoint_info_name(kEndpointName);
- CountDownLatch discovered_latch(1);
- CountDownLatch accept_latch(1);
-
- WifiLanSocket socket_for_server;
- EXPECT_TRUE(wifi_lan_server.StartAcceptingConnections(
- service_id,
- {
- .accepted_cb =
- [&socket_for_server, &accept_latch](WifiLanSocket socket) {
- socket_for_server = std::move(socket);
- accept_latch.CountDown();
- },
- }));
-
- NsdServiceInfo nsd_service_info;
- nsd_service_info.SetServiceName(service_info_name);
- nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
- endpoint_info_name);
- wifi_lan_server.StartAdvertising(service_id, nsd_service_info);
-
- NsdServiceInfo discovered_service_info;
- wifi_lan_client.StartDiscovery(
- service_id,
- {
- .service_discovered_cb =
- [&discovered_latch, &discovered_service_info](
- NsdServiceInfo service_info, const std::string& service_id) {
- NEARBY_LOGS(INFO)
- << "Discovered service_info=" << &service_info;
- discovered_service_info = service_info;
- discovered_latch.CountDown();
- },
- });
- EXPECT_TRUE(discovered_latch.Await(kWaitDuration).result());
- ASSERT_TRUE(discovered_service_info.IsValid());
-
- CancellationFlag flag(true);
- WifiLanSocket socket_for_client =
- wifi_lan_client.Connect(service_id, discovered_service_info, &flag);
- // If FeatureFlag is disabled, Cancelled is false as no-op.
- if (!feature_flags.enable_cancellation_flag) {
- EXPECT_TRUE(accept_latch.Await(kWaitDuration).result());
- EXPECT_TRUE(wifi_lan_server.StopAcceptingConnections(service_id));
- EXPECT_TRUE(wifi_lan_server.StopAdvertising(service_id));
- EXPECT_TRUE(socket_for_server.IsValid());
- EXPECT_TRUE(socket_for_client.IsValid());
- } else {
- EXPECT_FALSE(accept_latch.Await(kWaitDuration).result());
- EXPECT_TRUE(wifi_lan_server.StopAcceptingConnections(service_id));
- EXPECT_TRUE(wifi_lan_server.StopAdvertising(service_id));
- EXPECT_FALSE(socket_for_server.IsValid());
- EXPECT_FALSE(socket_for_client.IsValid());
- }
- env_.Stop();
-}
-
-INSTANTIATE_TEST_SUITE_P(ParametrisedWifiLanTest, WifiLanTest,
- ::testing::ValuesIn(kTestCases));
-
-TEST_F(WifiLanTest, CanConstructValidObject) {
- env_.Start();
- WifiLan wifi_lan_a;
- WifiLan wifi_lan_b;
- std::string service_id(kServiceID);
-
- EXPECT_TRUE(wifi_lan_a.IsAvailable());
- EXPECT_TRUE(wifi_lan_b.IsAvailable());
- env_.Stop();
-}
-
-TEST_F(WifiLanTest, CanStartAdvertising) {
- env_.Start();
- WifiLan wifi_lan_a;
- std::string service_id(kServiceID);
- std::string service_info_name(kServiceInfoName);
- std::string endpoint_info_name(kEndpointName);
-
- EXPECT_TRUE(wifi_lan_a.StartAcceptingConnections(service_id, {}));
-
- NsdServiceInfo nsd_service_info;
- nsd_service_info.SetServiceName(service_info_name);
- nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
- endpoint_info_name);
- EXPECT_TRUE(wifi_lan_a.StartAdvertising(service_id, nsd_service_info));
- EXPECT_TRUE(wifi_lan_a.StopAdvertising(service_id));
- env_.Stop();
-}
-
-TEST_F(WifiLanTest, CanStartMultipleAdvertising) {
- env_.Start();
- WifiLan wifi_lan_a;
- std::string service_id_1(kServiceID);
- std::string service_id_2("com.google.location.nearby.apps.test_1");
- std::string service_info_name_1(kServiceInfoName);
- std::string service_info_name_2("ServiceInfoName_1");
- std::string endpoint_info_name(kEndpointName);
-
- EXPECT_TRUE(wifi_lan_a.StartAcceptingConnections(service_id_1, {}));
- EXPECT_TRUE(wifi_lan_a.StartAcceptingConnections(service_id_2, {}));
-
- NsdServiceInfo nsd_service_info_1;
- nsd_service_info_1.SetServiceName(service_info_name_1);
- nsd_service_info_1.SetTxtRecord(std::string(kEndpointInfoKey),
- endpoint_info_name);
- NsdServiceInfo nsd_service_info_2;
- nsd_service_info_2.SetServiceName(service_info_name_2);
- nsd_service_info_2.SetTxtRecord(std::string(kEndpointInfoKey),
- endpoint_info_name);
- EXPECT_TRUE(wifi_lan_a.StartAdvertising(service_id_1, nsd_service_info_1));
- EXPECT_TRUE(wifi_lan_a.StartAdvertising(service_id_2, nsd_service_info_2));
- EXPECT_TRUE(wifi_lan_a.StopAdvertising(service_id_1));
- EXPECT_TRUE(wifi_lan_a.StopAdvertising(service_id_2));
- EXPECT_TRUE(wifi_lan_a.StopAcceptingConnections(service_id_1));
- EXPECT_TRUE(wifi_lan_a.StopAcceptingConnections(service_id_2));
- env_.Stop();
-}
-
-TEST_F(WifiLanTest, CanStartDiscovery) {
- env_.Start();
- WifiLan wifi_lan_a;
- std::string service_id(kServiceID);
-
- EXPECT_TRUE(
- wifi_lan_a.StartDiscovery(service_id, DiscoveredServiceCallback{}));
- EXPECT_TRUE(wifi_lan_a.StopDiscovery(service_id));
- env_.Stop();
-}
-
-TEST_F(WifiLanTest, CanStartMultipleDiscovery) {
- env_.Start();
- WifiLan wifi_lan_a;
- std::string service_id_1(kServiceID);
- std::string service_id_2("com.google.location.nearby.apps.test_1");
-
- EXPECT_TRUE(
- wifi_lan_a.StartDiscovery(service_id_1, DiscoveredServiceCallback{}));
-
- EXPECT_TRUE(
- wifi_lan_a.StartDiscovery(service_id_2, DiscoveredServiceCallback{}));
- EXPECT_TRUE(wifi_lan_a.StopDiscovery(service_id_1));
- EXPECT_TRUE(wifi_lan_a.StopDiscovery(service_id_2));
- env_.Stop();
-}
-
-TEST_F(WifiLanTest, CanAdvertiseThatOtherMediumDiscover) {
- env_.Start();
- WifiLan wifi_lan_a;
- WifiLan wifi_lan_b;
- std::string service_id(kServiceID);
- std::string service_info_name(kServiceInfoName);
- std::string endpoint_info_name(kEndpointName);
- CountDownLatch discovered_latch(1);
- CountDownLatch lost_latch(1);
-
- wifi_lan_b.StartDiscovery(
- service_id, DiscoveredServiceCallback{
- .service_discovered_cb =
- [&discovered_latch](NsdServiceInfo service_info,
- const std::string& service_id) {
- discovered_latch.CountDown();
- },
- .service_lost_cb =
- [&lost_latch](NsdServiceInfo service_info,
- const std::string& service_id) {
- lost_latch.CountDown();
- },
- });
-
- EXPECT_TRUE(wifi_lan_a.StartAcceptingConnections(service_id, {}));
-
- NsdServiceInfo nsd_service_info;
- nsd_service_info.SetServiceName(service_info_name);
- nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
- endpoint_info_name);
- EXPECT_TRUE(wifi_lan_a.StartAdvertising(service_id, nsd_service_info));
- EXPECT_TRUE(discovered_latch.Await(kWaitDuration).result());
- EXPECT_TRUE(wifi_lan_a.StopAdvertising(service_id));
- EXPECT_TRUE(lost_latch.Await(kWaitDuration).result());
- EXPECT_TRUE(wifi_lan_b.StopDiscovery(service_id));
- env_.Stop();
-}
-
-TEST_F(WifiLanTest, CanDiscoverThatOtherMediumAdvertise) {
- env_.Start();
- WifiLan wifi_lan_a;
- WifiLan wifi_lan_b;
- std::string service_id(kServiceID);
- std::string service_info_name(kServiceInfoName);
- std::string endpoint_info_name(kEndpointName);
- CountDownLatch discovered_latch(1);
- CountDownLatch lost_latch(1);
-
- EXPECT_TRUE(wifi_lan_b.StartAcceptingConnections(service_id, {}));
-
- NsdServiceInfo nsd_service_info;
- nsd_service_info.SetServiceName(service_info_name);
- nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
- endpoint_info_name);
- wifi_lan_b.StartAdvertising(service_id, nsd_service_info);
-
- EXPECT_TRUE(wifi_lan_a.StartDiscovery(
- service_id, DiscoveredServiceCallback{
- .service_discovered_cb =
- [&discovered_latch](NsdServiceInfo service_info,
- const std::string& service_id) {
- discovered_latch.CountDown();
- },
- .service_lost_cb =
- [&lost_latch](NsdServiceInfo service_info,
- const std::string& service_id) {
- lost_latch.CountDown();
- },
- }));
- EXPECT_TRUE(discovered_latch.Await(kWaitDuration).result());
- EXPECT_TRUE(wifi_lan_b.StopAdvertising(service_id));
- EXPECT_TRUE(lost_latch.Await(kWaitDuration).result());
- EXPECT_TRUE(wifi_lan_a.StopDiscovery(service_id));
- env_.Stop();
-}
-
-} // namespace
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mock_service_controller.h b/chromium/third_party/nearby/src/cpp/core/internal/mock_service_controller.h
deleted file mode 100644
index 30173eeb1f7..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mock_service_controller.h
+++ /dev/null
@@ -1,92 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_MOCK_SERVICE_CONTROLLER_H_
-#define CORE_INTERNAL_MOCK_SERVICE_CONTROLLER_H_
-
-#include "gmock/gmock.h"
-#include "core/internal/service_controller.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-/* Mock implementation for ServiceController:
- * All methods execute asynchronously (in a private executor thread).
- * To synchronise, two approaches may be used:
- * 1. For methods that have result callback, we use it to unblock main thread.
- * 2. For methods that do not have callbacks, we provide a mock implementation
- * that unblocks main thread.
- */
-class MockServiceController : public ServiceController {
- public:
- MOCK_METHOD(void, Stop, (), (override));
- MOCK_METHOD(Status, StartAdvertising,
- (ClientProxy * client, const std::string& service_id,
- const ConnectionOptions& options,
- const ConnectionRequestInfo& info),
- (override));
-
- MOCK_METHOD(void, StopAdvertising, (ClientProxy * client), (override));
-
- MOCK_METHOD(Status, StartDiscovery,
- (ClientProxy * client, const std::string& service_id,
- const ConnectionOptions& options,
- const DiscoveryListener& listener),
- (override));
-
- MOCK_METHOD(void, StopDiscovery, (ClientProxy * client), (override));
-
- MOCK_METHOD(void, InjectEndpoint,
- (ClientProxy * client, const std::string& service_id,
- const OutOfBandConnectionMetadata& metadata),
- (override));
-
- MOCK_METHOD(Status, RequestConnection,
- (ClientProxy * client, const std::string& endpoint_id,
- const ConnectionRequestInfo& info,
- const ConnectionOptions& options),
- (override));
-
- MOCK_METHOD(Status, AcceptConnection,
- (ClientProxy * client, const std::string& endpoint_id,
- const PayloadListener& listener),
- (override));
-
- MOCK_METHOD(Status, RejectConnection,
- (ClientProxy * client, const std::string& endpoint_id),
- (override));
-
- MOCK_METHOD(void, InitiateBandwidthUpgrade,
- (ClientProxy * client, const std::string& endpoint_id),
- (override));
-
- MOCK_METHOD(void, SendPayload,
- (ClientProxy * client,
- const std::vector<std::string>& endpoint_ids, Payload payload),
- (override));
-
- MOCK_METHOD(Status, CancelPayload,
- (ClientProxy * client, std::int64_t payload_id), (override));
-
- MOCK_METHOD(void, DisconnectFromEndpoint,
- (ClientProxy * client, const std::string& endpoint_id),
- (override));
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_MOCK_SERVICE_CONTROLLER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/mock_service_controller_router.h b/chromium/third_party/nearby/src/cpp/core/internal/mock_service_controller_router.h
deleted file mode 100644
index 32d8d445ea3..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/mock_service_controller_router.h
+++ /dev/null
@@ -1,101 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_MOCK_SERVICE_CONTROLLER_ROUTER_H_
-#define CORE_INTERNAL_MOCK_SERVICE_CONTROLLER_ROUTER_H_
-
-#include "gmock/gmock.h"
-#include "core/internal/service_controller_router.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-class MockServiceControllerRouter : public ServiceControllerRouter {
- public:
- MOCK_METHOD(void, StartAdvertising,
- (ClientProxy * client, absl::string_view service_id,
- const ConnectionOptions& options,
- const ConnectionRequestInfo& info,
- const ResultCallback& callback),
- (override));
-
- MOCK_METHOD(void, StopAdvertising,
- (ClientProxy * client, const ResultCallback& callback),
- (override));
-
- MOCK_METHOD(void, StartDiscovery,
- (ClientProxy * client, absl::string_view service_id,
- const ConnectionOptions& options,
- const DiscoveryListener& listener,
- const ResultCallback& callback),
- (override));
-
- MOCK_METHOD(void, StopDiscovery,
- (ClientProxy * client, const ResultCallback& callback),
- (override));
-
- MOCK_METHOD(void, InjectEndpoint,
- (ClientProxy * client, absl::string_view service_id,
- const OutOfBandConnectionMetadata& metadata,
- const ResultCallback& callback),
- (override));
-
- MOCK_METHOD(void, RequestConnection,
- (ClientProxy * client, absl::string_view endpoint_id,
- const ConnectionRequestInfo& info,
- const ConnectionOptions& options,
- const ResultCallback& callback),
- (override));
-
- MOCK_METHOD(void, AcceptConnection,
- (ClientProxy * client, absl::string_view endpoint_id,
- const PayloadListener& listener, const ResultCallback& callback),
- (override));
-
- MOCK_METHOD(void, RejectConnection,
- (ClientProxy * client, absl::string_view endpoint_id,
- const ResultCallback& callback),
- (override));
-
- MOCK_METHOD(void, InitiateBandwidthUpgrade,
- (ClientProxy * client, absl::string_view endpoint_id,
- const ResultCallback& callback),
- (override));
-
- MOCK_METHOD(void, SendPayload,
- (ClientProxy * client, absl::Span<const std::string> endpoint_ids,
- Payload payload, const ResultCallback& callback),
- (override));
-
- MOCK_METHOD(void, CancelPayload,
- (ClientProxy * client, std::uint64_t payload_id,
- const ResultCallback& callback),
- (override));
-
- MOCK_METHOD(void, DisconnectFromEndpoint,
- (ClientProxy * client, absl::string_view endpoint_id,
- const ResultCallback& callback),
- (override));
-
- MOCK_METHOD(void, StopAllEndpoints,
- (ClientProxy * client, const ResultCallback& callback),
- (override));
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_MOCK_SERVICE_CONTROLLER_ROUTER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/offline_frames.cc b/chromium/third_party/nearby/src/cpp/core/internal/offline_frames.cc
deleted file mode 100644
index f2862c3e4bc..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/offline_frames.cc
+++ /dev/null
@@ -1,502 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/offline_frames.h"
-
-#include <memory>
-#include <utility>
-
-#include "core/internal/message_lite.h"
-#include "core/internal/offline_frames_validator.h"
-#include "core/status.h"
-#include "platform/base/byte_array.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace parser {
-namespace {
-
-using ExceptionOrOfflineFrame = ExceptionOr<OfflineFrame>;
-using MessageLite = ::google::protobuf::MessageLite;
-
-ByteArray ToBytes(OfflineFrame&& frame) {
- ByteArray bytes(frame.ByteSizeLong());
- frame.set_version(OfflineFrame::V1);
- frame.SerializeToArray(bytes.data(), bytes.size());
- return bytes;
-}
-
-} // namespace
-
-ExceptionOrOfflineFrame FromBytes(const ByteArray& bytes) {
- OfflineFrame frame;
-
- if (frame.ParseFromString(std::string(bytes))) {
- Exception validation_exception = EnsureValidOfflineFrame(frame);
- if (validation_exception.Raised()) {
- return ExceptionOrOfflineFrame(validation_exception);
- }
- return ExceptionOrOfflineFrame(std::move(frame));
- } else {
- return ExceptionOrOfflineFrame(Exception::kInvalidProtocolBuffer);
- }
-}
-
-V1Frame::FrameType GetFrameType(const OfflineFrame& frame) {
- if ((frame.version() == OfflineFrame::V1) && frame.has_v1()) {
- return frame.v1().type();
- }
-
- return V1Frame::UNKNOWN_FRAME_TYPE;
-}
-
-ByteArray ForConnectionRequest(const std::string& endpoint_id,
- const ByteArray& endpoint_info,
- std::int32_t nonce, bool supports_5_ghz,
- const std::string& bssid,
- const std::vector<Medium>& mediums,
- std::int32_t keep_alive_interval_millis,
- std::int32_t keep_alive_timeout_millis) {
- OfflineFrame frame;
-
- frame.set_version(OfflineFrame::V1);
- auto* v1_frame = frame.mutable_v1();
- v1_frame->set_type(V1Frame::CONNECTION_REQUEST);
- auto* connection_request = v1_frame->mutable_connection_request();
- if (!endpoint_id.empty()) connection_request->set_endpoint_id(endpoint_id);
- if (!endpoint_info.Empty()) {
- connection_request->set_endpoint_name(std::string(endpoint_info));
- connection_request->set_endpoint_info(std::string(endpoint_info));
- }
- connection_request->set_nonce(nonce);
- auto* medium_metadata = connection_request->mutable_medium_metadata();
- medium_metadata->set_supports_5_ghz(supports_5_ghz);
- if (!bssid.empty()) medium_metadata->set_bssid(bssid);
- if (!mediums.empty()) {
- for (const auto& medium : mediums) {
- connection_request->add_mediums(MediumToConnectionRequestMedium(medium));
- }
- }
- if (keep_alive_interval_millis > 0) {
- connection_request->set_keep_alive_interval_millis(
- keep_alive_interval_millis);
- }
- if (keep_alive_timeout_millis > 0) {
- connection_request->set_keep_alive_timeout_millis(
- keep_alive_timeout_millis);
- }
-
- return ToBytes(std::move(frame));
-}
-
-ByteArray ForConnectionResponse(std::int32_t status) {
- OfflineFrame frame;
-
- frame.set_version(OfflineFrame::V1);
- auto* v1_frame = frame.mutable_v1();
- v1_frame->set_type(V1Frame::CONNECTION_RESPONSE);
- auto* sub_frame = v1_frame->mutable_connection_response();
-
- // For backward compatiblility, here still sets both status and response
- // parameters until the response feature is roll out in all supported
- // devices.
- sub_frame->set_status(status);
- sub_frame->set_response(status == Status::kSuccess
- ? ConnectionResponseFrame::ACCEPT
- : ConnectionResponseFrame::REJECT);
-
- return ToBytes(std::move(frame));
-}
-
-ByteArray ForDataPayloadTransfer(
- const PayloadTransferFrame::PayloadHeader& header,
- const PayloadTransferFrame::PayloadChunk& chunk) {
- OfflineFrame frame;
-
- frame.set_version(OfflineFrame::V1);
- auto* v1_frame = frame.mutable_v1();
- v1_frame->set_type(V1Frame::PAYLOAD_TRANSFER);
- auto* sub_frame = v1_frame->mutable_payload_transfer();
- sub_frame->set_packet_type(PayloadTransferFrame::DATA);
- *sub_frame->mutable_payload_header() = header;
- *sub_frame->mutable_payload_chunk() = chunk;
-
- return ToBytes(std::move(frame));
-}
-
-ByteArray ForControlPayloadTransfer(
- const PayloadTransferFrame::PayloadHeader& header,
- const PayloadTransferFrame::ControlMessage& control) {
- OfflineFrame frame;
-
- frame.set_version(OfflineFrame::V1);
- auto* v1_frame = frame.mutable_v1();
- v1_frame->set_type(V1Frame::PAYLOAD_TRANSFER);
- auto* sub_frame = v1_frame->mutable_payload_transfer();
- sub_frame->set_packet_type(PayloadTransferFrame::CONTROL);
- *sub_frame->mutable_payload_header() = header;
- *sub_frame->mutable_control_message() = control;
-
- return ToBytes(std::move(frame));
-}
-
-ByteArray ForBwuWifiHotspotPathAvailable(const std::string& ssid,
- const std::string& password,
- std::int32_t port,
- const std::string& gateway,
- bool supports_disabling_encryption) {
- OfflineFrame frame;
-
- frame.set_version(OfflineFrame::V1);
- auto* v1_frame = frame.mutable_v1();
- v1_frame->set_type(V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION);
- auto* sub_frame = v1_frame->mutable_bandwidth_upgrade_negotiation();
- sub_frame->set_event_type(
- BandwidthUpgradeNegotiationFrame::UPGRADE_PATH_AVAILABLE);
- auto* upgrade_path_info = sub_frame->mutable_upgrade_path_info();
- upgrade_path_info->set_medium(UpgradePathInfo::WIFI_HOTSPOT);
- upgrade_path_info->set_supports_client_introduction_ack(true);
- upgrade_path_info->set_supports_disabling_encryption(
- supports_disabling_encryption);
- auto* wifi_hotspot_credentials =
- upgrade_path_info->mutable_wifi_hotspot_credentials();
- wifi_hotspot_credentials->set_ssid(ssid);
- wifi_hotspot_credentials->set_password(password);
- wifi_hotspot_credentials->set_port(port);
- wifi_hotspot_credentials->set_gateway(gateway);
-
- return ToBytes(std::move(frame));
-}
-
-ByteArray ForBwuWifiLanPathAvailable(const std::string& ip_address,
- std::int32_t port) {
- OfflineFrame frame;
-
- frame.set_version(OfflineFrame::V1);
- auto* v1_frame = frame.mutable_v1();
- v1_frame->set_type(V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION);
- auto* sub_frame = v1_frame->mutable_bandwidth_upgrade_negotiation();
- sub_frame->set_event_type(
- BandwidthUpgradeNegotiationFrame::UPGRADE_PATH_AVAILABLE);
- auto* upgrade_path_info = sub_frame->mutable_upgrade_path_info();
- upgrade_path_info->set_medium(UpgradePathInfo::WIFI_LAN);
- upgrade_path_info->set_supports_client_introduction_ack(true);
- auto* wifi_lan_socket = upgrade_path_info->mutable_wifi_lan_socket();
- wifi_lan_socket->set_ip_address(ip_address);
- wifi_lan_socket->set_wifi_port(port);
-
- return ToBytes(std::move(frame));
-}
-
-ByteArray ForBwuWifiAwarePathAvailable(const std::string& service_id,
- const std::string& service_info,
- const std::string& password,
- bool supports_disabling_encryption) {
- OfflineFrame frame;
-
- frame.set_version(OfflineFrame::V1);
- auto* v1_frame = frame.mutable_v1();
- v1_frame->set_type(V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION);
- auto* sub_frame = v1_frame->mutable_bandwidth_upgrade_negotiation();
- sub_frame->set_event_type(
- BandwidthUpgradeNegotiationFrame::UPGRADE_PATH_AVAILABLE);
- auto* upgrade_path_info = sub_frame->mutable_upgrade_path_info();
- upgrade_path_info->set_medium(UpgradePathInfo::WIFI_AWARE);
- upgrade_path_info->set_supports_client_introduction_ack(true);
- upgrade_path_info->set_supports_disabling_encryption(
- supports_disabling_encryption);
- auto* wifi_aware_credentials =
- upgrade_path_info->mutable_wifi_aware_credentials();
- wifi_aware_credentials->set_service_id(service_id);
- wifi_aware_credentials->set_service_info(service_info);
- if (!password.empty()) wifi_aware_credentials->set_password(password);
-
- return ToBytes(std::move(frame));
-}
-
-ByteArray ForBwuWifiDirectPathAvailable(const std::string& ssid,
- const std::string& password,
- std::int32_t port,
- std::int32_t frequency,
- bool supports_disabling_encryption) {
- OfflineFrame frame;
-
- frame.set_version(OfflineFrame::V1);
- auto* v1_frame = frame.mutable_v1();
- v1_frame->set_type(V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION);
- auto* sub_frame = v1_frame->mutable_bandwidth_upgrade_negotiation();
- sub_frame->set_event_type(
- BandwidthUpgradeNegotiationFrame::UPGRADE_PATH_AVAILABLE);
- auto* upgrade_path_info = sub_frame->mutable_upgrade_path_info();
- upgrade_path_info->set_medium(UpgradePathInfo::WIFI_DIRECT);
- upgrade_path_info->set_supports_client_introduction_ack(true);
- upgrade_path_info->set_supports_disabling_encryption(
- supports_disabling_encryption);
- auto* wifi_direct_credentials =
- upgrade_path_info->mutable_wifi_direct_credentials();
- wifi_direct_credentials->set_ssid(ssid);
- wifi_direct_credentials->set_password(password);
- wifi_direct_credentials->set_port(port);
- wifi_direct_credentials->set_frequency(frequency);
-
- return ToBytes(std::move(frame));
-}
-
-ByteArray ForBwuBluetoothPathAvailable(const std::string& service_id,
- const std::string& mac_address) {
- OfflineFrame frame;
-
- frame.set_version(OfflineFrame::V1);
- auto* v1_frame = frame.mutable_v1();
- v1_frame->set_type(V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION);
- auto* sub_frame = v1_frame->mutable_bandwidth_upgrade_negotiation();
- sub_frame->set_event_type(
- BandwidthUpgradeNegotiationFrame::UPGRADE_PATH_AVAILABLE);
- auto* upgrade_path_info = sub_frame->mutable_upgrade_path_info();
- upgrade_path_info->set_medium(UpgradePathInfo::BLUETOOTH);
- upgrade_path_info->set_supports_client_introduction_ack(true);
- auto* bluetooth_credentials =
- upgrade_path_info->mutable_bluetooth_credentials();
- bluetooth_credentials->set_mac_address(mac_address);
- bluetooth_credentials->set_service_name(service_id);
-
- return ToBytes(std::move(frame));
-}
-
-ByteArray ForBwuWebrtcPathAvailable(const std::string& peer_id,
- const LocationHint& location_hint) {
- OfflineFrame frame;
-
- frame.set_version(OfflineFrame::V1);
- auto* v1_frame = frame.mutable_v1();
- v1_frame->set_type(V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION);
- auto* sub_frame = v1_frame->mutable_bandwidth_upgrade_negotiation();
- sub_frame->set_event_type(
- BandwidthUpgradeNegotiationFrame::UPGRADE_PATH_AVAILABLE);
- auto* upgrade_path_info = sub_frame->mutable_upgrade_path_info();
- upgrade_path_info->set_medium(UpgradePathInfo::WEB_RTC);
- upgrade_path_info->set_supports_client_introduction_ack(true);
- auto* webrtc_credentials = upgrade_path_info->mutable_web_rtc_credentials();
- webrtc_credentials->set_peer_id(peer_id);
- auto* local_location_hint = webrtc_credentials->mutable_location_hint();
- *local_location_hint = location_hint;
-
- return ToBytes(std::move(frame));
-}
-
-ByteArray ForBwuLastWrite() {
- OfflineFrame frame;
-
- frame.set_version(OfflineFrame::V1);
- auto* v1_frame = frame.mutable_v1();
- v1_frame->set_type(V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION);
- auto* sub_frame = v1_frame->mutable_bandwidth_upgrade_negotiation();
- sub_frame->set_event_type(
- BandwidthUpgradeNegotiationFrame::LAST_WRITE_TO_PRIOR_CHANNEL);
-
- return ToBytes(std::move(frame));
-}
-
-ByteArray ForBwuSafeToClose() {
- OfflineFrame frame;
-
- frame.set_version(OfflineFrame::V1);
- auto* v1_frame = frame.mutable_v1();
- v1_frame->set_type(V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION);
- auto* sub_frame = v1_frame->mutable_bandwidth_upgrade_negotiation();
- sub_frame->set_event_type(
- BandwidthUpgradeNegotiationFrame::SAFE_TO_CLOSE_PRIOR_CHANNEL);
-
- return ToBytes(std::move(frame));
-}
-
-ByteArray ForBwuIntroduction(const std::string& endpoint_id) {
- OfflineFrame frame;
-
- frame.set_version(OfflineFrame::V1);
- auto* v1_frame = frame.mutable_v1();
- v1_frame->set_type(V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION);
- auto* sub_frame = v1_frame->mutable_bandwidth_upgrade_negotiation();
- sub_frame->set_event_type(
- BandwidthUpgradeNegotiationFrame::CLIENT_INTRODUCTION);
- auto* client_introduction = sub_frame->mutable_client_introduction();
- client_introduction->set_endpoint_id(endpoint_id);
-
- return ToBytes(std::move(frame));
-}
-
-ByteArray ForBwuIntroductionAck() {
- OfflineFrame frame;
-
- frame.set_version(OfflineFrame::V1);
- auto* v1_frame = frame.mutable_v1();
- v1_frame->set_type(V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION);
- auto* sub_frame = v1_frame->mutable_bandwidth_upgrade_negotiation();
- sub_frame->set_event_type(
- BandwidthUpgradeNegotiationFrame::CLIENT_INTRODUCTION_ACK);
-
- return ToBytes(std::move(frame));
-}
-
-ByteArray ForBwuFailure(const UpgradePathInfo& info) {
- OfflineFrame frame;
-
- frame.set_version(OfflineFrame::V1);
- auto* v1_frame = frame.mutable_v1();
- v1_frame->set_type(V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION);
- auto* sub_frame = v1_frame->mutable_bandwidth_upgrade_negotiation();
- sub_frame->set_event_type(BandwidthUpgradeNegotiationFrame::UPGRADE_FAILURE);
- auto* upgrade_path_info = sub_frame->mutable_upgrade_path_info();
- *upgrade_path_info = info;
-
- return ToBytes(std::move(frame));
-}
-
-ByteArray ForKeepAlive() {
- OfflineFrame frame;
-
- frame.set_version(OfflineFrame::V1);
- auto* v1_frame = frame.mutable_v1();
- v1_frame->set_type(V1Frame::KEEP_ALIVE);
- v1_frame->mutable_keep_alive();
-
- return ToBytes(std::move(frame));
-}
-
-ByteArray ForDisconnection() {
- OfflineFrame frame;
-
- frame.set_version(OfflineFrame::V1);
- auto* v1_frame = frame.mutable_v1();
- v1_frame->set_type(V1Frame::DISCONNECTION);
- v1_frame->mutable_disconnection();
-
- return ToBytes(std::move(frame));
-}
-
-UpgradePathInfo::Medium MediumToUpgradePathInfoMedium(Medium medium) {
- switch (medium) {
- case Medium::MDNS:
- return UpgradePathInfo::MDNS;
- case Medium::BLUETOOTH:
- return UpgradePathInfo::BLUETOOTH;
- case Medium::WIFI_HOTSPOT:
- return UpgradePathInfo::WIFI_HOTSPOT;
- case Medium::BLE:
- return UpgradePathInfo::BLE;
- case Medium::WIFI_LAN:
- return UpgradePathInfo::WIFI_LAN;
- case Medium::WIFI_AWARE:
- return UpgradePathInfo::WIFI_AWARE;
- case Medium::NFC:
- return UpgradePathInfo::NFC;
- case Medium::WIFI_DIRECT:
- return UpgradePathInfo::WIFI_DIRECT;
- case Medium::WEB_RTC:
- return UpgradePathInfo::WEB_RTC;
- default:
- return UpgradePathInfo::UNKNOWN_MEDIUM;
- }
-}
-
-Medium UpgradePathInfoMediumToMedium(UpgradePathInfo::Medium medium) {
- switch (medium) {
- case UpgradePathInfo::MDNS:
- return Medium::MDNS;
- case UpgradePathInfo::BLUETOOTH:
- return Medium::BLUETOOTH;
- case UpgradePathInfo::WIFI_HOTSPOT:
- return Medium::WIFI_HOTSPOT;
- case UpgradePathInfo::BLE:
- return Medium::BLE;
- case UpgradePathInfo::WIFI_LAN:
- return Medium::WIFI_LAN;
- case UpgradePathInfo::WIFI_AWARE:
- return Medium::WIFI_AWARE;
- case UpgradePathInfo::NFC:
- return Medium::NFC;
- case UpgradePathInfo::WIFI_DIRECT:
- return Medium::WIFI_DIRECT;
- case UpgradePathInfo::WEB_RTC:
- return Medium::WEB_RTC;
- default:
- return Medium::UNKNOWN_MEDIUM;
- }
-}
-
-ConnectionRequestFrame::Medium MediumToConnectionRequestMedium(Medium medium) {
- switch (medium) {
- case Medium::MDNS:
- return ConnectionRequestFrame::MDNS;
- case Medium::BLUETOOTH:
- return ConnectionRequestFrame::BLUETOOTH;
- case Medium::WIFI_HOTSPOT:
- return ConnectionRequestFrame::WIFI_HOTSPOT;
- case Medium::BLE:
- return ConnectionRequestFrame::BLE;
- case Medium::WIFI_LAN:
- return ConnectionRequestFrame::WIFI_LAN;
- case Medium::WIFI_AWARE:
- return ConnectionRequestFrame::WIFI_AWARE;
- case Medium::NFC:
- return ConnectionRequestFrame::NFC;
- case Medium::WIFI_DIRECT:
- return ConnectionRequestFrame::WIFI_DIRECT;
- case Medium::WEB_RTC:
- return ConnectionRequestFrame::WEB_RTC;
- default:
- return ConnectionRequestFrame::UNKNOWN_MEDIUM;
- }
-}
-
-Medium ConnectionRequestMediumToMedium(ConnectionRequestFrame::Medium medium) {
- switch (medium) {
- case ConnectionRequestFrame::MDNS:
- return Medium::MDNS;
- case ConnectionRequestFrame::BLUETOOTH:
- return Medium::BLUETOOTH;
- case ConnectionRequestFrame::WIFI_HOTSPOT:
- return Medium::WIFI_HOTSPOT;
- case ConnectionRequestFrame::BLE:
- return Medium::BLE;
- case ConnectionRequestFrame::WIFI_LAN:
- return Medium::WIFI_LAN;
- case ConnectionRequestFrame::WIFI_AWARE:
- return Medium::WIFI_AWARE;
- case ConnectionRequestFrame::NFC:
- return Medium::NFC;
- case ConnectionRequestFrame::WIFI_DIRECT:
- return Medium::WIFI_DIRECT;
- case ConnectionRequestFrame::WEB_RTC:
- return Medium::WEB_RTC;
- default:
- return Medium::UNKNOWN_MEDIUM;
- }
-}
-
-std::vector<Medium> ConnectionRequestMediumsToMediums(
- const ConnectionRequestFrame& frame) {
- std::vector<Medium> result;
- for (const auto& int_medium : frame.mediums()) {
- result.push_back(ConnectionRequestMediumToMedium(
- static_cast<ConnectionRequestFrame::Medium>(int_medium)));
- }
- return result;
-}
-
-} // namespace parser
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/offline_frames.h b/chromium/third_party/nearby/src/cpp/core/internal/offline_frames.h
deleted file mode 100644
index 74db1071177..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/offline_frames.h
+++ /dev/null
@@ -1,105 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_OFFLINE_FRAMES_H_
-#define CORE_INTERNAL_OFFLINE_FRAMES_H_
-
-#include <cstdint>
-#include <vector>
-
-#include "core/options.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/exception.h"
-#include "proto/connections/offline_wire_formats.pb.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace parser {
-
-using UpgradePathInfo = BandwidthUpgradeNegotiationFrame::UpgradePathInfo;
-
-// Serialize/Deserialize Nearby Connections Protocol messages.
-
-// Parses incoming message.
-// Returns OfflineFrame if parser was able to understand it, or
-// Exception::kInvalidProtocolBuffer, if parser failed.
-ExceptionOr<OfflineFrame> FromBytes(const ByteArray& offline_frame_bytes);
-
-// Returns FrameType of a parsed message, or
-// V1Frame::UNKNOWN_FRAME_TYPE, if frame contents is not recognized.
-V1Frame::FrameType GetFrameType(const OfflineFrame& offline_frame);
-
-// Builds Connection Request / Response messages.
-ByteArray ForConnectionRequest(const std::string& endpoint_id,
- const ByteArray& endpoint_info,
- std::int32_t nonce, bool supports_5_ghz,
- const std::string& bssid,
- const std::vector<Medium>& mediums,
- std::int32_t keep_alive_interval_millis,
- std::int32_t keep_alive_timeout_millis);
-ByteArray ForConnectionResponse(std::int32_t status);
-
-// Builds Payload transfer messages.
-ByteArray ForDataPayloadTransfer(
- const PayloadTransferFrame::PayloadHeader& header,
- const PayloadTransferFrame::PayloadChunk& chunk);
-ByteArray ForControlPayloadTransfer(
- const PayloadTransferFrame::PayloadHeader& header,
- const PayloadTransferFrame::ControlMessage& control);
-
-// Builds Bandwidth Upgrade [BWU] messages.
-ByteArray ForBwuIntroduction(const std::string& endpoint_id);
-ByteArray ForBwuIntroductionAck();
-ByteArray ForBwuWifiHotspotPathAvailable(const std::string& ssid,
- const std::string& password,
- std::int32_t port,
- const std::string& gateway,
- bool supports_disabling_encryption);
-ByteArray ForBwuWifiLanPathAvailable(const std::string& ip_address,
- std::int32_t port);
-ByteArray ForBwuWifiAwarePathAvailable(const std::string& service_id,
- const std::string& service_info,
- const std::string& password,
- bool supports_disabling_encryption);
-ByteArray ForBwuWifiDirectPathAvailable(const std::string& ssid,
- const std::string& password,
- std::int32_t port,
- std::int32_t frequency,
- bool supports_disabling_encryption);
-ByteArray ForBwuBluetoothPathAvailable(const std::string& service_id,
- const std::string& mac_address);
-ByteArray ForBwuWebrtcPathAvailable(const std::string& peer_id,
- const LocationHint& location_hint_a);
-ByteArray ForBwuFailure(const UpgradePathInfo& info);
-ByteArray ForBwuLastWrite();
-ByteArray ForBwuSafeToClose();
-
-ByteArray ForKeepAlive();
-ByteArray ForDisconnection();
-
-UpgradePathInfo::Medium MediumToUpgradePathInfoMedium(Medium medium);
-Medium UpgradePathInfoMediumToMedium(UpgradePathInfo::Medium medium);
-
-ConnectionRequestFrame::Medium MediumToConnectionRequestMedium(Medium medium);
-Medium ConnectionRequestMediumToMedium(ConnectionRequestFrame::Medium medium);
-std::vector<Medium> ConnectionRequestMediumsToMediums(
- const ConnectionRequestFrame& connection_request_frame);
-
-} // namespace parser
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_OFFLINE_FRAMES_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/offline_frames_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/offline_frames_test.cc
deleted file mode 100644
index 3be49db1e33..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/offline_frames_test.cc
+++ /dev/null
@@ -1,393 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/offline_frames.h"
-
-#include <array>
-#include <memory>
-#include <utility>
-#include <vector>
-
-#include "absl/strings/string_view.h"
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "platform/base/byte_array.h"
-#include "proto/connections/offline_wire_formats.pb.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace parser {
-namespace {
-
-using Medium = proto::connections::Medium;
-using ::testing::EqualsProto;
-
-constexpr absl::string_view kEndpointId{"ABC"};
-constexpr absl::string_view kEndpointName{"XYZ"};
-constexpr int kNonce = 1234;
-constexpr bool kSupports5ghz = true;
-constexpr absl::string_view kBssid{"FF:FF:FF:FF:FF:FF"};
-constexpr std::array<Medium, 9> kMediums = {
- Medium::MDNS, Medium::BLUETOOTH, Medium::WIFI_HOTSPOT,
- Medium::BLE, Medium::WIFI_LAN, Medium::WIFI_AWARE,
- Medium::NFC, Medium::WIFI_DIRECT, Medium::WEB_RTC,
-};
-constexpr int kKeepAliveIntervalMillis = 1000;
-constexpr int kKeepAliveTimeoutMillis = 5000;
-
-TEST(OfflineFramesTest, CanParseMessageFromBytes) {
- OfflineFrame tx_message;
-
- {
- tx_message.set_version(OfflineFrame::V1);
- auto* v1_frame = tx_message.mutable_v1();
- auto* sub_frame = v1_frame->mutable_connection_request();
-
- v1_frame->set_type(V1Frame::CONNECTION_REQUEST);
- // OSS matchers don't like implicitly comparing string_views to strings.
- sub_frame->set_endpoint_id(std::string(kEndpointId));
- sub_frame->set_endpoint_name(std::string(kEndpointName));
- sub_frame->set_endpoint_info(std::string(kEndpointName));
- sub_frame->set_nonce(kNonce);
- sub_frame->set_keep_alive_interval_millis(kKeepAliveIntervalMillis);
- sub_frame->set_keep_alive_timeout_millis(kKeepAliveTimeoutMillis);
- auto* medium_metadata = sub_frame->mutable_medium_metadata();
-
- medium_metadata->set_supports_5_ghz(kSupports5ghz);
- medium_metadata->set_bssid(kBssid);
-
- for (auto& medium : kMediums) {
- sub_frame->add_mediums(MediumToConnectionRequestMedium(medium));
- }
- }
- auto serialized_bytes = ByteArray(tx_message.SerializeAsString());
- auto ret_value = FromBytes(serialized_bytes);
- ASSERT_TRUE(ret_value.ok());
- const auto& rx_message = ret_value.result();
- EXPECT_THAT(rx_message, EqualsProto(tx_message));
- EXPECT_EQ(GetFrameType(rx_message), V1Frame::CONNECTION_REQUEST);
- EXPECT_EQ(
- ConnectionRequestMediumsToMediums(rx_message.v1().connection_request()),
- std::vector(kMediums.begin(), kMediums.end()));
-}
-
-TEST(OfflineFramesTest, CanGenerateConnectionRequest) {
- constexpr char kExpected[] =
- R"pb(
- version: V1
- v1: <
- type: CONNECTION_REQUEST
- connection_request: <
- endpoint_id: "ABC"
- endpoint_name: "XYZ"
- endpoint_info: "XYZ"
- nonce: 1234
- medium_metadata: < supports_5_ghz: true bssid: "FF:FF:FF:FF:FF:FF" >
- mediums: MDNS
- mediums: BLUETOOTH
- mediums: WIFI_HOTSPOT
- mediums: BLE
- mediums: WIFI_LAN
- mediums: WIFI_AWARE
- mediums: NFC
- mediums: WIFI_DIRECT
- mediums: WEB_RTC
- keep_alive_interval_millis: 1000
- keep_alive_timeout_millis: 5000
- >
- >)pb";
- ByteArray bytes = ForConnectionRequest(
- std::string(kEndpointId), ByteArray{std::string(kEndpointName)}, kNonce,
- kSupports5ghz, std::string(kBssid),
- std::vector(kMediums.begin(), kMediums.end()), kKeepAliveIntervalMillis,
- kKeepAliveTimeoutMillis);
- auto response = FromBytes(bytes);
- ASSERT_TRUE(response.ok());
- OfflineFrame message = FromBytes(bytes).result();
- EXPECT_THAT(message, EqualsProto(kExpected));
-}
-
-TEST(OfflineFramesTest, CanGenerateConnectionResponse) {
- constexpr char kExpected[] =
- R"pb(
- version: V1
- v1: <
- type: CONNECTION_RESPONSE
- connection_response: < status: 1 response: REJECT >
- >)pb";
- ByteArray bytes = ForConnectionResponse(1);
- auto response = FromBytes(bytes);
- ASSERT_TRUE(response.ok());
- OfflineFrame message = FromBytes(bytes).result();
- EXPECT_THAT(message, EqualsProto(kExpected));
-}
-
-TEST(OfflineFramesTest, CanGenerateControlPayloadTransfer) {
- PayloadTransferFrame::PayloadHeader header;
- PayloadTransferFrame::ControlMessage control;
- header.set_id(12345);
- header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
- header.set_total_size(1024);
- control.set_event(PayloadTransferFrame::ControlMessage::PAYLOAD_CANCELED);
- control.set_offset(150);
-
- constexpr char kExpected[] =
- R"pb(
- version: V1
- v1: <
- type: PAYLOAD_TRANSFER
- payload_transfer: <
- packet_type: CONTROL,
- payload_header: < type: BYTES id: 12345 total_size: 1024 >
- control_message: < event: PAYLOAD_CANCELED offset: 150 >
- >
- >)pb";
- ByteArray bytes = ForControlPayloadTransfer(header, control);
- auto response = FromBytes(bytes);
- ASSERT_TRUE(response.ok());
- OfflineFrame message = FromBytes(bytes).result();
- EXPECT_THAT(message, EqualsProto(kExpected));
-}
-
-TEST(OfflineFramesTest, CanGenerateDataPayloadTransfer) {
- PayloadTransferFrame::PayloadHeader header;
- PayloadTransferFrame::PayloadChunk chunk;
- header.set_id(12345);
- header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
- header.set_total_size(1024);
- chunk.set_body("payload data");
- chunk.set_offset(150);
- chunk.set_flags(1);
-
- constexpr char kExpected[] =
- R"pb(
- version: V1
- v1: <
- type: PAYLOAD_TRANSFER
- payload_transfer: <
- packet_type: DATA,
- payload_header: < type: BYTES id: 12345 total_size: 1024 >
- payload_chunk: < flags: 1 offset: 150 body: "payload data" >
- >
- >)pb";
- ByteArray bytes = ForDataPayloadTransfer(header, chunk);
- auto response = FromBytes(bytes);
- ASSERT_TRUE(response.ok());
- OfflineFrame message = FromBytes(bytes).result();
- EXPECT_THAT(message, EqualsProto(kExpected));
-}
-
-TEST(OfflineFramesTest, CanGenerateBwuWifiHotspotPathAvailable) {
- constexpr char kExpected[] =
- R"pb(
- version: V1
- v1: <
- type: BANDWIDTH_UPGRADE_NEGOTIATION
- bandwidth_upgrade_negotiation: <
- event_type: UPGRADE_PATH_AVAILABLE
- upgrade_path_info: <
- medium: WIFI_HOTSPOT
- wifi_hotspot_credentials: <
- ssid: "ssid"
- password: "password"
- port: 1234
- gateway: "0.0.0.0"
- >
- supports_disabling_encryption: false
- supports_client_introduction_ack: true
- >
- >
- >)pb";
- ByteArray bytes = ForBwuWifiHotspotPathAvailable("ssid", "password", 1234,
- "0.0.0.0", false);
- auto response = FromBytes(bytes);
- ASSERT_TRUE(response.ok());
- OfflineFrame message = FromBytes(bytes).result();
- EXPECT_THAT(message, EqualsProto(kExpected));
-}
-
-TEST(OfflineFramesTest, CanGenerateBwuWifiLanPathAvailable) {
- constexpr char kExpected[] =
- R"pb(
- version: V1
- v1: <
- type: BANDWIDTH_UPGRADE_NEGOTIATION
- bandwidth_upgrade_negotiation: <
- event_type: UPGRADE_PATH_AVAILABLE
- upgrade_path_info: <
- medium: WIFI_LAN
- wifi_lan_socket: < ip_address: "\x01\x02\x03\x04" wifi_port: 1234 >
- supports_client_introduction_ack: true
- >
- >
- >)pb";
- ByteArray bytes = ForBwuWifiLanPathAvailable("\x01\x02\x03\x04", 1234);
- auto response = FromBytes(bytes);
- ASSERT_TRUE(response.ok());
- OfflineFrame message = FromBytes(bytes).result();
- EXPECT_THAT(message, EqualsProto(kExpected));
-}
-
-TEST(OfflineFramesTest, CanGenerateBwuWifiAwarePathAvailable) {
- constexpr char kExpected[] =
- R"pb(
- version: V1
- v1: <
- type: BANDWIDTH_UPGRADE_NEGOTIATION
- bandwidth_upgrade_negotiation: <
- event_type: UPGRADE_PATH_AVAILABLE
- upgrade_path_info: <
- medium: WIFI_AWARE
- wifi_aware_credentials: <
- service_id: "service_id"
- service_info: "service_info"
- password: "password"
- >
- supports_disabling_encryption: false
- supports_client_introduction_ack: true
- >
- >
- >)pb";
- ByteArray bytes = ForBwuWifiAwarePathAvailable("service_id", "service_info",
- "password", false);
- auto response = FromBytes(bytes);
- ASSERT_TRUE(response.ok());
- OfflineFrame message = FromBytes(bytes).result();
- EXPECT_THAT(message, EqualsProto(kExpected));
-}
-
-TEST(OfflineFramesTest, CanGenerateBwuWifiDirectPathAvailable) {
- constexpr char kExpected[] =
- R"pb(
- version: V1
- v1: <
- type: BANDWIDTH_UPGRADE_NEGOTIATION
- bandwidth_upgrade_negotiation: <
- event_type: UPGRADE_PATH_AVAILABLE
- upgrade_path_info: <
- medium: WIFI_DIRECT
- wifi_direct_credentials: <
- ssid: "DIRECT-A0-0123456789AB"
- password: "password"
- port: 1000
- frequency: 1000
- >
- supports_disabling_encryption: false
- supports_client_introduction_ack: true
- >
- >
- >)pb";
- ByteArray bytes = ForBwuWifiDirectPathAvailable(
- "DIRECT-A0-0123456789AB", "password", 1000, 1000, false);
- auto response = FromBytes(bytes);
- ASSERT_TRUE(response.ok());
- OfflineFrame message = FromBytes(bytes).result();
- EXPECT_THAT(message, EqualsProto(kExpected));
-}
-
-TEST(OfflineFramesTest, CanGenerateBwuBluetoothPathAvailable) {
- constexpr char kExpected[] =
- R"pb(
- version: V1
- v1: <
- type: BANDWIDTH_UPGRADE_NEGOTIATION
- bandwidth_upgrade_negotiation: <
- event_type: UPGRADE_PATH_AVAILABLE
- upgrade_path_info: <
- medium: BLUETOOTH
- bluetooth_credentials: <
- service_name: "service"
- mac_address: "\x11\x22\x33\x44\x55\x66"
- >
- supports_client_introduction_ack: true
- >
- >
- >)pb";
- ByteArray bytes =
- ForBwuBluetoothPathAvailable("service", "\x11\x22\x33\x44\x55\x66");
- auto response = FromBytes(bytes);
- ASSERT_TRUE(response.ok());
- OfflineFrame message = FromBytes(bytes).result();
- EXPECT_THAT(message, EqualsProto(kExpected));
-}
-
-TEST(OfflineFramesTest, CanGenerateBwuLastWrite) {
- constexpr char kExpected[] =
- R"pb(
- version: V1
- v1: <
- type: BANDWIDTH_UPGRADE_NEGOTIATION
- bandwidth_upgrade_negotiation: < event_type: LAST_WRITE_TO_PRIOR_CHANNEL >
- >)pb";
- ByteArray bytes = ForBwuLastWrite();
- auto response = FromBytes(bytes);
- ASSERT_TRUE(response.ok());
- OfflineFrame message = FromBytes(bytes).result();
- EXPECT_THAT(message, EqualsProto(kExpected));
-}
-
-TEST(OfflineFramesTest, CanGenerateBwuSafeToClose) {
- constexpr char kExpected[] =
- R"pb(
- version: V1
- v1: <
- type: BANDWIDTH_UPGRADE_NEGOTIATION
- bandwidth_upgrade_negotiation: < event_type: SAFE_TO_CLOSE_PRIOR_CHANNEL >
- >)pb";
- ByteArray bytes = ForBwuSafeToClose();
- auto response = FromBytes(bytes);
- ASSERT_TRUE(response.ok());
- OfflineFrame message = FromBytes(bytes).result();
- EXPECT_THAT(message, EqualsProto(kExpected));
-}
-
-TEST(OfflineFramesTest, CanGenerateBwuIntroduction) {
- constexpr char kExpected[] =
- R"pb(
- version: V1
- v1: <
- type: BANDWIDTH_UPGRADE_NEGOTIATION
- bandwidth_upgrade_negotiation: <
- event_type: CLIENT_INTRODUCTION
- client_introduction: < endpoint_id: "ABC" >
- >
- >)pb";
- ByteArray bytes = ForBwuIntroduction(std::string(kEndpointId));
- auto response = FromBytes(bytes);
- ASSERT_TRUE(response.ok());
- OfflineFrame message = FromBytes(bytes).result();
- EXPECT_THAT(message, EqualsProto(kExpected));
-}
-
-TEST(OfflineFramesTest, CanGenerateKeepAlive) {
- constexpr char kExpected[] =
- R"pb(
- version: V1
- v1: <
- type: KEEP_ALIVE
- keep_alive: <>
- >)pb";
- ByteArray bytes = ForKeepAlive();
- auto response = FromBytes(bytes);
- ASSERT_TRUE(response.ok());
- OfflineFrame message = FromBytes(bytes).result();
- EXPECT_THAT(message, EqualsProto(kExpected));
-}
-
-} // namespace
-} // namespace parser
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/offline_frames_validator.cc b/chromium/third_party/nearby/src/cpp/core/internal/offline_frames_validator.cc
deleted file mode 100644
index 614c65f8e63..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/offline_frames_validator.cc
+++ /dev/null
@@ -1,381 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/offline_frames_validator.h"
-
-#include <regex> //NOLINT
-
-#include "core/internal/internal_payload.h"
-#include "core/internal/offline_frames.h"
-#include "proto/connections/offline_wire_formats.pb.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace parser {
-namespace {
-
-using PayloadChunk = PayloadTransferFrame::PayloadChunk;
-using ControlMessage = PayloadTransferFrame::ControlMessage;
-using ClientIntroduction = BandwidthUpgradeNegotiationFrame::ClientIntroduction;
-using WifiHotspotCredentials = UpgradePathInfo::WifiHotspotCredentials;
-using WifiLanSocket = UpgradePathInfo::WifiLanSocket;
-using WifiAwareCredentials = UpgradePathInfo::WifiAwareCredentials;
-using WifiDirectCredentials = UpgradePathInfo::WifiDirectCredentials;
-using BluetoothCredentials = UpgradePathInfo::BluetoothCredentials;
-using WebRtcCredentials = UpgradePathInfo::WebRtcCredentials;
-using Medium = location::nearby::connections::Medium;
-
-constexpr absl::string_view kIpv4PatternString{
- "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
- "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
- "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
- "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"};
-constexpr absl::string_view kIpv6PatternString{
- "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
- "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
- "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
- "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
- "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
- "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"};
-constexpr absl::string_view kWifiDirectSsidPatternString{
- "^DIRECT-[a-zA-Z0-9]{2}.*$"};
-constexpr int kWifiDirectSsidMaxLength = 32;
-constexpr int kWifiPasswordSsidMinLength = 8;
-constexpr int kWifiPasswordSsidMaxLength = 64;
-
-inline bool WithinRange(int value, int min, int max) {
- return value >= min && value < max;
-}
-
-Exception EnsureValidConnectionRequestFrame(
- const ConnectionRequestFrame& frame) {
- if (!frame.has_endpoint_id()) return {Exception::kInvalidProtocolBuffer};
- if (!frame.has_endpoint_name()) return {Exception::kInvalidProtocolBuffer};
-
- // For backwards compatibility reasons, no other fields should be
- // null-checked for this frame. Parameter checking (eg. must be within this
- // range) is fine.
- return {Exception::kSuccess};
-}
-
-Exception EnsureValidConnectionResponseFrame(
- const ConnectionResponseFrame& frame) {
- // For backwards compatibility reasons, no other fields should be null-checked
- // for this frame. Parameter checking (eg. must be within this range) is fine.
- return {Exception::kSuccess};
-}
-
-Exception EnsureValidPayloadTransferDataFrame(const PayloadChunk& payload_chunk,
- std::int64_t totalSize) {
- if (!payload_chunk.has_flags()) return {Exception::kInvalidProtocolBuffer};
-
- // Special case. The body can be null iff the chunk is flagged as the last
- // chunk.
- bool is_last_chunk = (payload_chunk.flags() &
- PayloadTransferFrame::PayloadChunk::LAST_CHUNK) != 0;
- if (!payload_chunk.has_body() && !is_last_chunk)
- return {Exception::kInvalidProtocolBuffer};
- if (!payload_chunk.has_offset() || payload_chunk.offset() < 0)
- return {Exception::kInvalidProtocolBuffer};
- if (totalSize != InternalPayload::kIndeterminateSize &&
- totalSize < payload_chunk.offset()) {
- return {Exception::kInvalidProtocolBuffer};
- }
-
- // For backwards compatibility reasons, no other fields should be null-checked
- // for this frame. Parameter checking (eg. must be within this range) is fine.
- return {Exception::kSuccess};
-}
-
-Exception EnsureValidPayloadTransferControlFrame(
- const ControlMessage& control_message, std::int64_t totalSize) {
- if (!control_message.has_offset() || control_message.offset() < 0)
- return {Exception::kInvalidProtocolBuffer};
- if (totalSize != InternalPayload::kIndeterminateSize &&
- totalSize < control_message.offset()) {
- return {Exception::kInvalidProtocolBuffer};
- }
-
- // For backwards compatibility reasons, no other fields should be null-checked
- // for this frame. Parameter checking (eg. must be within this range) is fine.
- return {Exception::kSuccess};
-}
-
-Exception EnsureValidPayloadTransferFrame(const PayloadTransferFrame& frame) {
- if (!frame.has_payload_header()) return {Exception::kInvalidProtocolBuffer};
- if (!frame.payload_header().has_total_size() ||
- (frame.payload_header().total_size() < 0 &&
- frame.payload_header().total_size() !=
- InternalPayload::kIndeterminateSize))
- return {Exception::kInvalidProtocolBuffer};
- if (!frame.has_packet_type()) return {Exception::kInvalidProtocolBuffer};
-
- switch (frame.packet_type()) {
- case PayloadTransferFrame::DATA:
- if (frame.has_payload_chunk()) {
- return EnsureValidPayloadTransferDataFrame(
- frame.payload_chunk(), frame.payload_header().total_size());
- }
- return {Exception::kInvalidProtocolBuffer};
-
- case PayloadTransferFrame::CONTROL:
- if (frame.has_control_message()) {
- return EnsureValidPayloadTransferControlFrame(
- frame.control_message(), frame.payload_header().total_size());
- }
- return {Exception::kInvalidProtocolBuffer};
-
- default:
- break;
- }
-
- // For backwards compatibility reasons, no other fields should be null-checked
- // for this frame. Parameter checking (eg. must be within this range) is fine.
- return {Exception::kSuccess};
-}
-
-Exception EnsureValidBandwidthUpgradeWifiHotspotPathAvailableFrame(
- const WifiHotspotCredentials& wifi_hotspot_credentials) {
- if (!wifi_hotspot_credentials.has_ssid())
- return {Exception::kInvalidProtocolBuffer};
- if (!wifi_hotspot_credentials.has_password() ||
- !WithinRange(wifi_hotspot_credentials.password().length(),
- kWifiPasswordSsidMinLength, kWifiPasswordSsidMaxLength))
- return {Exception::kInvalidProtocolBuffer};
- if (!wifi_hotspot_credentials.has_gateway())
- return {Exception::kInvalidProtocolBuffer};
- const std::regex ip4_pattern(std::string(kIpv4PatternString).c_str());
- const std::regex ip6_pattern(std::string(kIpv6PatternString).c_str());
- if (!(std::regex_match(wifi_hotspot_credentials.gateway(), ip4_pattern) ||
- std::regex_match(wifi_hotspot_credentials.gateway(), ip6_pattern)))
- return {Exception::kInvalidProtocolBuffer};
-
- // For backwards compatibility reasons, no other fields should be null-checked
- // for this frame. Parameter checking (eg. must be within this range) is fine.
- return {Exception::kSuccess};
-}
-
-Exception EnsureValidBandwidthUpgradeWifiLanPathAvailableFrame(
- const WifiLanSocket& wifi_lan_socket) {
- if (!wifi_lan_socket.has_ip_address())
- return {Exception::kInvalidProtocolBuffer};
- if (!wifi_lan_socket.has_wifi_port() || wifi_lan_socket.wifi_port() < 0)
- return {Exception::kInvalidProtocolBuffer};
-
- // For backwards compatibility reasons, no other fields should be null-checked
- // for this frame. Parameter checking (eg. must be within this range) is fine.
- return {Exception::kSuccess};
-}
-
-Exception EnsureValidBandwidthUpgradeWifiAwarePathAvailableFrame(
- const WifiAwareCredentials& wifi_aware_credentials) {
- if (!wifi_aware_credentials.has_service_id())
- return {Exception::kInvalidProtocolBuffer};
- if (!wifi_aware_credentials.has_service_info())
- return {Exception::kInvalidProtocolBuffer};
-
- // For backwards compatibility reasons, no other fields should be null-checked
- // for this frame. Parameter checking (eg. must be within this range) is fine.
- return {Exception::kSuccess};
-}
-
-Exception EnsureValidBandwidthUpgradeWifiDirectPathAvailableFrame(
- const WifiDirectCredentials& wifi_direct_credentials) {
- const std::regex ssid_pattern(
- std::string(kWifiDirectSsidPatternString).c_str());
- if (!wifi_direct_credentials.has_ssid() ||
- !(wifi_direct_credentials.ssid().length() < kWifiDirectSsidMaxLength &&
- std::regex_match(wifi_direct_credentials.ssid(), ssid_pattern)))
- return {Exception::kInvalidProtocolBuffer};
-
- if (!wifi_direct_credentials.has_password() ||
- !WithinRange(wifi_direct_credentials.password().length(),
- kWifiPasswordSsidMinLength, kWifiPasswordSsidMaxLength))
- return {Exception::kInvalidProtocolBuffer};
-
- if (!wifi_direct_credentials.has_frequency() ||
- wifi_direct_credentials.frequency() < -1)
- return {Exception::kInvalidProtocolBuffer};
-
- // For backwards compatibility reasons, no other fields should be null-checked
- // for this frame. Parameter checking (eg. must be within this range) is fine.
- return {Exception::kSuccess};
-}
-
-Exception EnsureValidBandwidthUpgradeBluetoothPathAvailableFrame(
- const BluetoothCredentials& bluetooth_credentials) {
- if (!bluetooth_credentials.has_service_name())
- return {Exception::kInvalidProtocolBuffer};
- if (!bluetooth_credentials.has_mac_address())
- return {Exception::kInvalidProtocolBuffer};
-
- // For backwards compatibility reasons, no other fields should be null-checked
- // for this frame. Parameter checking (eg. must be within this range) is fine.
- return {Exception::kSuccess};
-}
-
-Exception EnsureValidBandwidthUpgradeWebRtcPathAvailableFrame(
- const WebRtcCredentials& web_rtc_credentials) {
- if (!web_rtc_credentials.has_peer_id())
- return {Exception::kInvalidProtocolBuffer};
-
- // For backwards compatibility reasons, no other fields should be null-checked
- // for this frame. Parameter checking (eg. must be within this range) is fine.
- return {Exception::kSuccess};
-}
-
-Exception EnsureValidBandwidthUpgradePathAvailableFrame(
- const UpgradePathInfo& upgrade_path_info) {
- if (!upgrade_path_info.has_medium())
- return {Exception::kInvalidProtocolBuffer};
- switch (static_cast<Medium>(upgrade_path_info.medium())) {
- case Medium::WIFI_HOTSPOT:
- if (upgrade_path_info.has_wifi_hotspot_credentials()) {
- return EnsureValidBandwidthUpgradeWifiHotspotPathAvailableFrame(
- upgrade_path_info.wifi_hotspot_credentials());
- }
- return {Exception::kInvalidProtocolBuffer};
-
- case Medium::WIFI_LAN:
- if (upgrade_path_info.has_wifi_lan_socket()) {
- return EnsureValidBandwidthUpgradeWifiLanPathAvailableFrame(
- upgrade_path_info.wifi_lan_socket());
- }
- return {Exception::kInvalidProtocolBuffer};
-
- case Medium::WIFI_AWARE:
- if (upgrade_path_info.has_wifi_aware_credentials()) {
- return EnsureValidBandwidthUpgradeWifiAwarePathAvailableFrame(
- upgrade_path_info.wifi_aware_credentials());
- }
- return {Exception::kInvalidProtocolBuffer};
-
- case Medium::WIFI_DIRECT:
- if (upgrade_path_info.has_wifi_direct_credentials()) {
- return EnsureValidBandwidthUpgradeWifiDirectPathAvailableFrame(
- upgrade_path_info.wifi_direct_credentials());
- }
- return {Exception::kInvalidProtocolBuffer};
-
- case Medium::BLUETOOTH:
- if (upgrade_path_info.has_bluetooth_credentials()) {
- return EnsureValidBandwidthUpgradeBluetoothPathAvailableFrame(
- upgrade_path_info.bluetooth_credentials());
- }
- return {Exception::kInvalidProtocolBuffer};
-
- case Medium::WEB_RTC:
- if (upgrade_path_info.has_web_rtc_credentials()) {
- return EnsureValidBandwidthUpgradeWebRtcPathAvailableFrame(
- upgrade_path_info.web_rtc_credentials());
- }
- return {Exception::kInvalidProtocolBuffer};
-
- default:
- break;
- }
-
- // For backwards compatibility reasons, no other fields should be null-checked
- // for this frame. Parameter checking (eg. must be within this range) is fine.
- return {Exception::kSuccess};
-}
-
-Exception EnsureValidBandwidthUpgradeClientIntroductionFrame(
- const ClientIntroduction& client_introduction) {
- if (!client_introduction.has_endpoint_id())
- return {Exception::kInvalidProtocolBuffer};
-
- // For backwards compatibility reasons, no other fields should be null-checked
- // for this frame. Parameter checking (eg. must be within this range) is fine.
- return {Exception::kSuccess};
-}
-
-Exception EnsureValidBandwidthUpgradeNegotiationFrame(
- const BandwidthUpgradeNegotiationFrame& frame) {
- if (!frame.has_event_type()) return {Exception::kInvalidProtocolBuffer};
-
- switch (frame.event_type()) {
- case BandwidthUpgradeNegotiationFrame::UPGRADE_PATH_AVAILABLE:
- if (frame.has_upgrade_path_info()) {
- return EnsureValidBandwidthUpgradePathAvailableFrame(
- frame.upgrade_path_info());
- }
- return {Exception::kInvalidProtocolBuffer};
-
- case BandwidthUpgradeNegotiationFrame::CLIENT_INTRODUCTION:
- if (frame.has_client_introduction()) {
- return EnsureValidBandwidthUpgradeClientIntroductionFrame(
- frame.client_introduction());
- }
- return {Exception::kInvalidProtocolBuffer};
-
- default:
- break;
- }
-
- // For backwards compatibility reasons, no other fields should be null-checked
- // for this frame. Parameter checking (eg. must be within this range) is fine.
- return {Exception::kSuccess};
-}
-
-} // namespace
-
-Exception EnsureValidOfflineFrame(const OfflineFrame& offline_frame) {
- V1Frame::FrameType frame_type = GetFrameType(offline_frame);
- switch (frame_type) {
- case V1Frame::CONNECTION_REQUEST:
- if (offline_frame.has_v1() &&
- offline_frame.v1().has_connection_request()) {
- return EnsureValidConnectionRequestFrame(
- offline_frame.v1().connection_request());
- }
- return {Exception::kInvalidProtocolBuffer};
-
- case V1Frame::CONNECTION_RESPONSE:
- if (offline_frame.has_v1() &&
- offline_frame.v1().has_connection_response()) {
- return EnsureValidConnectionResponseFrame(
- offline_frame.v1().connection_response());
- }
- return {Exception::kInvalidProtocolBuffer};
-
- case V1Frame::PAYLOAD_TRANSFER:
- if (offline_frame.has_v1() && offline_frame.v1().has_payload_transfer()) {
- return EnsureValidPayloadTransferFrame(
- offline_frame.v1().payload_transfer());
- }
- return {Exception::kInvalidProtocolBuffer};
-
- case V1Frame::BANDWIDTH_UPGRADE_NEGOTIATION:
- if (offline_frame.has_v1() &&
- offline_frame.v1().has_bandwidth_upgrade_negotiation()) {
- return EnsureValidBandwidthUpgradeNegotiationFrame(
- offline_frame.v1().bandwidth_upgrade_negotiation());
- }
- return {Exception::kInvalidProtocolBuffer};
-
- case V1Frame::KEEP_ALIVE:
- case V1Frame::UNKNOWN_FRAME_TYPE:
- default:
- // Nothing to check for these frames.
- break;
- }
- return {Exception::kSuccess};
-}
-
-} // namespace parser
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/offline_frames_validator.h b/chromium/third_party/nearby/src/cpp/core/internal/offline_frames_validator.h
deleted file mode 100644
index f64c32c31b1..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/offline_frames_validator.h
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_OFFLINE_FRAMES_VALIDATOR_H_
-#define CORE_INTERNAL_OFFLINE_FRAMES_VALIDATOR_H_
-
-#include "platform/base/exception.h"
-#include "proto/connections/offline_wire_formats.pb.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace parser {
-
-Exception EnsureValidOfflineFrame(const OfflineFrame& offline_frame);
-
-} // namespace parser
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_OFFLINE_FRAMES_VALIDATOR_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/offline_frames_validator_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/offline_frames_validator_test.cc
deleted file mode 100644
index 3136fb2d96a..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/offline_frames_validator_test.cc
+++ /dev/null
@@ -1,568 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/offline_frames_validator.h"
-
-#include <string>
-
-#include "absl/strings/string_view.h"
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "core/internal/offline_frames.h"
-#include "platform/base/byte_array.h"
-#include "proto/connections/offline_wire_formats.pb.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace parser {
-namespace {
-
-constexpr absl::string_view kEndpointId{"ABC"};
-constexpr absl::string_view kEndpointName{"XYZ"};
-constexpr int kNonce = 1234;
-constexpr bool kSupports5ghz = true;
-constexpr absl::string_view kBssid{"FF:FF:FF:FF:FF:FF"};
-constexpr int kStatusAccepted = 0;
-constexpr absl::string_view kSsid = "ssid";
-constexpr absl::string_view kPassword = "password";
-constexpr absl::string_view kWifiHotspotGateway = "0.0.0.0";
-constexpr absl::string_view kWifiDirectSsid = "DIRECT-A0-0123456789AB";
-constexpr absl::string_view kWifiDirectPassword = "WIFIDIRECT123456";
-constexpr int kWifiDirectFrequency = 1000;
-constexpr int kPort = 1000;
-constexpr bool kSupportsDisablingEncryption = true;
-constexpr std::array<Medium, 9> kMediums = {
- Medium::MDNS, Medium::BLUETOOTH, Medium::WIFI_HOTSPOT,
- Medium::BLE, Medium::WIFI_LAN, Medium::WIFI_AWARE,
- Medium::NFC, Medium::WIFI_DIRECT, Medium::WEB_RTC,
-};
-constexpr int kKeepAliveIntervalMillis = 1000;
-constexpr int kKeepAliveTimeoutMillis = 5000;
-
-TEST(OfflineFramesValidatorTest, ValidatesAsOkWithValidConnectionRequestFrame) {
- OfflineFrame offline_frame;
-
- ByteArray bytes = ForConnectionRequest(
- std::string(kEndpointId), ByteArray{std::string(kEndpointName)}, kNonce,
- kSupports5ghz, std::string(kBssid),
- std::vector(kMediums.begin(), kMediums.end()), kKeepAliveIntervalMillis,
- kKeepAliveTimeoutMillis);
- offline_frame.ParseFromString(std::string(bytes));
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame);
-
- ASSERT_TRUE(ret_value.Ok());
-}
-
-TEST(OfflineFramesValidatorTest,
- ValidatesAsFailWithNullConnectionRequestFrame) {
- OfflineFrame offline_frame;
-
- ByteArray bytes = ForConnectionRequest(
- std::string(kEndpointId), ByteArray{std::string(kEndpointName)}, kNonce,
- kSupports5ghz, std::string(kBssid),
- std::vector(kMediums.begin(), kMediums.end()), kKeepAliveIntervalMillis,
- kKeepAliveTimeoutMillis);
- offline_frame.ParseFromString(std::string(bytes));
- auto* v1_frame = offline_frame.mutable_v1();
-
- v1_frame->clear_connection_request();
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame);
-
- ASSERT_FALSE(ret_value.Ok());
-}
-
-TEST(OfflineFramesValidatorTest,
- ValidatesAsFailWithNullEndpointIdInConnectionRequestFrame) {
- OfflineFrame offline_frame;
-
- std::string empty_enpoint_id;
- ByteArray bytes = ForConnectionRequest(
- empty_enpoint_id, ByteArray{std::string(kEndpointName)}, kNonce,
- kSupports5ghz, std::string(kBssid),
- std::vector(kMediums.begin(), kMediums.end()), kKeepAliveIntervalMillis,
- kKeepAliveTimeoutMillis);
- offline_frame.ParseFromString(std::string(bytes));
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame);
-
- ASSERT_FALSE(ret_value.Ok());
-}
-
-TEST(OfflineFramesValidatorTest,
- ValidatesAsFailWithNullEndpointInfoInConnectionRequestFrame) {
- OfflineFrame offline_frame;
-
- ByteArray empty_endpoint_info;
- ByteArray bytes = ForConnectionRequest(
- std::string(kEndpointId), empty_endpoint_info, kNonce, kSupports5ghz,
- std::string(kBssid), std::vector(kMediums.begin(), kMediums.end()),
- kKeepAliveIntervalMillis, kKeepAliveTimeoutMillis);
- offline_frame.ParseFromString(std::string(bytes));
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame);
-
- ASSERT_FALSE(ret_value.Ok());
-}
-
-TEST(OfflineFramesValidatorTest,
- ValidatesAsOkWithNullBssidInConnectionRequestFrame) {
- OfflineFrame offline_frame;
-
- std::string empty_bssid;
- ByteArray bytes = ForConnectionRequest(
- std::string(kEndpointId), ByteArray{std::string(kEndpointName)}, kNonce,
- kSupports5ghz, empty_bssid, std::vector(kMediums.begin(), kMediums.end()),
- kKeepAliveIntervalMillis, kKeepAliveTimeoutMillis);
- offline_frame.ParseFromString(std::string(bytes));
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame);
-
- ASSERT_TRUE(ret_value.Ok());
-}
-
-TEST(OfflineFramesValidatorTest,
- ValidatesAsOkWithNullMediumsInConnectionRequestFrame) {
- OfflineFrame offline_frame;
-
- std::vector<Medium> empty_mediums;
- ByteArray bytes = ForConnectionRequest(
- std::string(kEndpointId), ByteArray{std::string(kEndpointName)}, kNonce,
- kSupports5ghz, std::string(kBssid), empty_mediums,
- kKeepAliveIntervalMillis, kKeepAliveTimeoutMillis);
- offline_frame.ParseFromString(std::string(bytes));
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame);
-
- ASSERT_TRUE(ret_value.Ok());
-}
-
-TEST(OfflineFramesValidatorTest,
- ValidatesAsOkWithValidConnectionResponseFrame) {
- OfflineFrame offline_frame;
-
- ByteArray bytes = ForConnectionResponse(kStatusAccepted);
- offline_frame.ParseFromString(std::string(bytes));
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame);
-
- ASSERT_TRUE(ret_value.Ok());
-}
-
-TEST(OfflineFramesValidatorTest,
- ValidatesAsFailWithNullConnectionResponseFrame) {
- OfflineFrame offline_frame;
-
- ByteArray bytes = ForConnectionResponse(kStatusAccepted);
- offline_frame.ParseFromString(std::string(bytes));
- auto* v1_frame = offline_frame.mutable_v1();
-
- v1_frame->clear_connection_response();
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame);
-
- ASSERT_FALSE(ret_value.Ok());
-}
-
-TEST(OfflineFramesValidatorTest,
- ValidatesAsFailWithUnexpectedStatusInConnectionResponseFrame) {
- OfflineFrame offline_frame;
-
- ByteArray bytes = ForConnectionResponse(-1);
- offline_frame.ParseFromString(std::string(bytes));
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame);
-
- // To maintain forward compatibility, we allow unexpected status codes.
- ASSERT_TRUE(ret_value.Ok());
-}
-
-TEST(OfflineFramesValidatorTest, ValidatesAsOkWithValidPayloadTransferFrame) {
- PayloadTransferFrame::PayloadHeader header;
- PayloadTransferFrame::PayloadChunk chunk;
- header.set_id(12345);
- header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
- // Sending files larger than 2gb was previously broken (see cl/372382338).
- // This tests a file larger than int max.
- header.set_total_size(3e10);
- chunk.set_body("payload data");
- chunk.set_offset(150);
- chunk.set_flags(1);
-
- OfflineFrame offline_frame;
-
- ByteArray bytes = ForDataPayloadTransfer(header, chunk);
- offline_frame.ParseFromString(std::string(bytes));
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame);
-
- ASSERT_TRUE(ret_value.Ok());
-}
-
-TEST(OfflineFramesValidatorTest, ValidatesAsFailWithNullPayloadTransferFrame) {
- PayloadTransferFrame::PayloadHeader header;
- PayloadTransferFrame::PayloadChunk chunk;
- chunk.set_body("payload data");
- chunk.set_offset(150);
- chunk.set_flags(1);
-
- OfflineFrame offline_frame;
-
- ByteArray bytes = ForDataPayloadTransfer(header, chunk);
- offline_frame.ParseFromString(std::string(bytes));
- auto* v1_frame = offline_frame.mutable_v1();
-
- v1_frame->clear_payload_transfer();
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame);
-
- ASSERT_FALSE(ret_value.Ok());
-}
-
-TEST(OfflineFramesValidatorTest,
- ValidatesAsFailWithNullPayloadHeaderInPayloadTransferFrame) {
- PayloadTransferFrame::PayloadHeader header;
- PayloadTransferFrame::PayloadChunk chunk;
- header.set_id(12345);
- header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
- header.set_total_size(1024);
- chunk.set_body("payload data");
- chunk.set_offset(150);
- chunk.set_flags(1);
-
- OfflineFrame offline_frame;
-
- ByteArray bytes = ForDataPayloadTransfer(header, chunk);
- offline_frame.ParseFromString(std::string(bytes));
- auto* v1_frame = offline_frame.mutable_v1();
- auto* payload_transfer = v1_frame->mutable_payload_transfer();
-
- payload_transfer->clear_payload_header();
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame);
-
- ASSERT_FALSE(ret_value.Ok());
-}
-
-TEST(OfflineFramesValidatorTest,
- ValidatesAsFailWithInvalidSizeInPayloadHeader) {
- PayloadTransferFrame::PayloadHeader header;
- PayloadTransferFrame::PayloadChunk chunk;
- header.set_id(12345);
- header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
- header.set_total_size(-5);
- chunk.set_body("payload data");
- chunk.set_offset(150);
- chunk.set_flags(1);
-
- OfflineFrame offline_frame;
-
- ByteArray bytes = ForDataPayloadTransfer(header, chunk);
- offline_frame.ParseFromString(std::string(bytes));
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame);
-
- ASSERT_FALSE(ret_value.Ok());
-}
-
-TEST(OfflineFramesValidatorTest,
- ValidatesAsFailWithNullPayloadChunkInPayloadTransferFrame) {
- PayloadTransferFrame::PayloadHeader header;
- PayloadTransferFrame::PayloadChunk chunk;
- header.set_id(12345);
- header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
- header.set_total_size(1024);
- chunk.set_body("payload data");
- chunk.set_offset(150);
- chunk.set_flags(1);
-
- OfflineFrame offline_frame;
-
- ByteArray bytes = ForDataPayloadTransfer(header, chunk);
- offline_frame.ParseFromString(std::string(bytes));
- auto* v1_frame = offline_frame.mutable_v1();
- auto* payload_transfer = v1_frame->mutable_payload_transfer();
-
- payload_transfer->clear_payload_chunk();
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame);
-
- ASSERT_FALSE(ret_value.Ok());
-}
-
-TEST(OfflineFramesValidatorTest,
- ValidatesAsFailWithInvalidOffsetInPayloadChunk) {
- PayloadTransferFrame::PayloadHeader header;
- PayloadTransferFrame::PayloadChunk chunk;
- header.set_id(12345);
- header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
- header.set_total_size(1024);
- chunk.set_body("payload data");
- chunk.set_offset(-1);
- chunk.set_flags(1);
-
- OfflineFrame offline_frame;
-
- ByteArray bytes = ForDataPayloadTransfer(header, chunk);
- offline_frame.ParseFromString(std::string(bytes));
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame);
-
- ASSERT_FALSE(ret_value.Ok());
-}
-
-TEST(OfflineFramesValidatorTest,
- ValidatesAsFailWithInvalidLargeOffsetInPayloadChunk) {
- PayloadTransferFrame::PayloadHeader header;
- PayloadTransferFrame::PayloadChunk chunk;
- header.set_id(12345);
- header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
- header.set_total_size(1024);
- chunk.set_body("payload data");
- chunk.set_offset(4999);
- chunk.set_flags(1);
-
- OfflineFrame offline_frame;
-
- ByteArray bytes = ForDataPayloadTransfer(header, chunk);
- offline_frame.ParseFromString(std::string(bytes));
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame);
-
- ASSERT_FALSE(ret_value.Ok());
-}
-
-TEST(OfflineFramesValidatorTest,
- ValidatesAsFailWithInvalidFlagsInPayloadChunk) {
- PayloadTransferFrame::PayloadHeader header;
- PayloadTransferFrame::PayloadChunk chunk;
- header.set_id(12345);
- header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
- header.set_total_size(1024);
- chunk.set_body("payload data");
- chunk.set_offset(150);
- chunk.set_flags(1);
-
- OfflineFrame offline_frame;
-
- ByteArray bytes = ForDataPayloadTransfer(header, chunk);
- offline_frame.ParseFromString(std::string(bytes));
- auto* v1_frame = offline_frame.mutable_v1();
- auto* payload_transfer = v1_frame->mutable_payload_transfer();
- auto* payload_chunk = payload_transfer->mutable_payload_chunk();
-
- payload_chunk->clear_flags();
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame);
-
- ASSERT_FALSE(ret_value.Ok());
-}
-
-TEST(OfflineFramesValidatorTest,
- ValidatesAsFailWithNullControlMessageInPayloadTransferFrame) {
- PayloadTransferFrame::PayloadHeader header;
- PayloadTransferFrame::ControlMessage control;
- header.set_id(12345);
- header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
- header.set_total_size(1024);
- control.set_event(PayloadTransferFrame::ControlMessage::PAYLOAD_CANCELED);
- control.set_offset(150);
-
- OfflineFrame offline_frame;
-
- ByteArray bytes = ForControlPayloadTransfer(header, control);
- offline_frame.ParseFromString(std::string(bytes));
-
- auto* v1_frame = offline_frame.mutable_v1();
- auto* payload_transfer = v1_frame->mutable_payload_transfer();
-
- payload_transfer->clear_control_message();
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame);
-
- ASSERT_FALSE(ret_value.Ok());
-}
-
-TEST(OfflineFramesValidatorTest,
- ValidatesAsFailWithInvalidNegativeOffsetInControlMessage) {
- PayloadTransferFrame::PayloadHeader header;
- PayloadTransferFrame::ControlMessage control;
- header.set_id(12345);
- header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
- header.set_total_size(1024);
- control.set_event(PayloadTransferFrame::ControlMessage::PAYLOAD_CANCELED);
- control.set_offset(-1);
-
- OfflineFrame offline_frame;
-
- ByteArray bytes = ForControlPayloadTransfer(header, control);
- offline_frame.ParseFromString(std::string(bytes));
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame);
-
- ASSERT_FALSE(ret_value.Ok());
-}
-
-TEST(OfflineFramesValidatorTest,
- ValidatesAsFailWithInvalidLargeOffsetInControlMessage) {
- PayloadTransferFrame::PayloadHeader header;
- PayloadTransferFrame::ControlMessage control;
- header.set_id(12345);
- header.set_type(PayloadTransferFrame::PayloadHeader::BYTES);
- header.set_total_size(1024);
- control.set_event(PayloadTransferFrame::ControlMessage::PAYLOAD_CANCELED);
- control.set_offset(4999);
-
- OfflineFrame offline_frame;
-
- ByteArray bytes = ForControlPayloadTransfer(header, control);
- offline_frame.ParseFromString(std::string(bytes));
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame);
-
- ASSERT_FALSE(ret_value.Ok());
-}
-
-TEST(OfflineFramesValidatorTest,
- ValidatesAsOkWithValidBandwidthUpgradeNegotiationFrame) {
- OfflineFrame offline_frame;
-
- ByteArray bytes = ForBwuWifiHotspotPathAvailable(
- std::string(kSsid), std::string(kPassword), kPort,
- std::string(kWifiHotspotGateway), kSupportsDisablingEncryption);
- offline_frame.ParseFromString(std::string(bytes));
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame);
-
- ASSERT_TRUE(ret_value.Ok());
-}
-
-TEST(OfflineFramesValidatorTest,
- ValidatesAsFailWithNullBandwidthUpgradeNegotiationFrame) {
- OfflineFrame offline_frame;
-
- ByteArray bytes = ForBwuWifiHotspotPathAvailable(
- std::string(kSsid), std::string(kPassword), kPort,
- std::string(kWifiHotspotGateway), kSupportsDisablingEncryption);
- offline_frame.ParseFromString(std::string(bytes));
- auto* v1_frame = offline_frame.mutable_v1();
-
- v1_frame->clear_bandwidth_upgrade_negotiation();
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame);
-
- ASSERT_FALSE(ret_value.Ok());
-}
-
-TEST(OfflineFramesValidatorTest, ValidatesAsOkBandwidthUpgradeWifiDirect) {
- OfflineFrame offline_frame;
-
- ByteArray bytes = ForBwuWifiDirectPathAvailable(
- std::string(kWifiDirectSsid), std::string(kWifiDirectPassword), kPort,
- kWifiDirectFrequency, kSupportsDisablingEncryption);
- offline_frame.ParseFromString(std::string(bytes));
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame);
-
- ASSERT_TRUE(ret_value.Ok());
-}
-
-TEST(OfflineFramesValidatorTest,
- ValidatesValidFrequencyInBandwidthUpgradeWifiDirect) {
- OfflineFrame offline_frame_1;
- OfflineFrame offline_frame_2;
-
- // Anything less than -1 is invalid
- ByteArray bytes = ForBwuWifiDirectPathAvailable(
- std::string(kWifiDirectSsid), std::string(kWifiDirectPassword), kPort, -2,
- kSupportsDisablingEncryption);
- offline_frame_1.ParseFromString(std::string(bytes));
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame_1);
-
- ASSERT_FALSE(ret_value.Ok());
-
- // But -1 itself is not invalid
- bytes = ForBwuWifiDirectPathAvailable(std::string(kWifiDirectSsid),
- std::string(kWifiDirectPassword), kPort,
- -1, kSupportsDisablingEncryption);
- offline_frame_2.ParseFromString(std::string(bytes));
-
- ret_value = EnsureValidOfflineFrame(offline_frame_2);
-
- ASSERT_TRUE(ret_value.Ok());
-}
-
-TEST(OfflineFramesValidatorTest,
- ValidatesAsFailWithInvalidSsidInBandwidthUpgradeWifiDirect) {
- OfflineFrame offline_frame_1;
- OfflineFrame offline_frame_2;
-
- std::string wifi_direct_ssid{"DIRECT-A*-0123456789AB"};
- ByteArray bytes = ForBwuWifiDirectPathAvailable(
- wifi_direct_ssid, std::string(kWifiDirectPassword), kPort,
- kWifiDirectFrequency, kSupportsDisablingEncryption);
- offline_frame_1.ParseFromString(std::string(bytes));
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame_1);
-
- ASSERT_FALSE(ret_value.Ok());
-
- std::string wifi_direct_ssid_wrong_length =
- std::string{kWifiDirectSsid} + "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
- bytes = ForBwuWifiDirectPathAvailable(
- wifi_direct_ssid_wrong_length, std::string(kWifiDirectPassword), kPort,
- kWifiDirectFrequency, kSupportsDisablingEncryption);
- offline_frame_2.ParseFromString(std::string(bytes));
-
- ret_value = EnsureValidOfflineFrame(offline_frame_2);
-
- ASSERT_FALSE(ret_value.Ok());
-}
-
-TEST(OfflineFramesValidatorTest,
- ValidatesAsFailWithInvalidPasswordInBandwidthUpgradeWifiDirect) {
- OfflineFrame offline_frame_1;
- OfflineFrame offline_frame_2;
-
- std::string short_wifi_direct_password{"Test"};
- ByteArray bytes = ForBwuWifiDirectPathAvailable(
- std::string(kWifiDirectSsid), short_wifi_direct_password, kPort,
- kWifiDirectFrequency, kSupportsDisablingEncryption);
- offline_frame_1.ParseFromString(std::string(bytes));
-
- auto ret_value = EnsureValidOfflineFrame(offline_frame_1);
-
- ASSERT_FALSE(ret_value.Ok());
-
- std::string long_wifi_direct_password =
- std::string{kWifiDirectSsid} +
- "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789";
- bytes = ForBwuWifiDirectPathAvailable(
- std::string(kWifiDirectSsid), long_wifi_direct_password, kPort,
- kWifiDirectFrequency, kSupportsDisablingEncryption);
- offline_frame_2.ParseFromString(std::string(bytes));
-
- ret_value = EnsureValidOfflineFrame(offline_frame_2);
-
- ASSERT_FALSE(ret_value.Ok());
-}
-
-} // namespace
-} // namespace parser
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/offline_service_controller.cc b/chromium/third_party/nearby/src/cpp/core/internal/offline_service_controller.cc
deleted file mode 100644
index a86eea9d165..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/offline_service_controller.cc
+++ /dev/null
@@ -1,141 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/offline_service_controller.h"
-
-#include <string>
-
-#include "absl/strings/str_join.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-OfflineServiceController::~OfflineServiceController() { Stop(); }
-
-void OfflineServiceController::Stop() {
- NEARBY_LOGS(INFO) << "Initiating shutdown of OfflineServiceController.";
- if (stop_.Set(true)) return;
- payload_manager_.DisconnectFromEndpointManager();
- pcp_manager_.DisconnectFromEndpointManager();
- NEARBY_LOGS(INFO) << "OfflineServiceController has shut down.";
-}
-
-Status OfflineServiceController::StartAdvertising(
- ClientProxy* client, const std::string& service_id,
- const ConnectionOptions& options, const ConnectionRequestInfo& info) {
- if (stop_) return {Status::kOutOfOrderApiCall};
- NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
- << " requested advertising to start.";
- return pcp_manager_.StartAdvertising(client, service_id, options, info);
-}
-
-void OfflineServiceController::StopAdvertising(ClientProxy* client) {
- if (stop_) return;
- NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
- << " requested advertising to stop.";
- pcp_manager_.StopAdvertising(client);
-}
-
-Status OfflineServiceController::StartDiscovery(
- ClientProxy* client, const std::string& service_id,
- const ConnectionOptions& options, const DiscoveryListener& listener) {
- if (stop_) return {Status::kOutOfOrderApiCall};
- NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
- << " requested discovery to start.";
- return pcp_manager_.StartDiscovery(client, service_id, options, listener);
-}
-
-void OfflineServiceController::StopDiscovery(ClientProxy* client) {
- if (stop_) return;
- NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
- << " requested discovery to stop.";
- pcp_manager_.StopDiscovery(client);
-}
-
-void OfflineServiceController::InjectEndpoint(
- ClientProxy* client, const std::string& service_id,
- const OutOfBandConnectionMetadata& metadata) {
- if (stop_) return;
- pcp_manager_.InjectEndpoint(client, service_id, metadata);
-}
-
-Status OfflineServiceController::RequestConnection(
- ClientProxy* client, const std::string& endpoint_id,
- const ConnectionRequestInfo& info, const ConnectionOptions& options) {
- if (stop_) return {Status::kOutOfOrderApiCall};
- NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
- << " requested a connection to endpoint_id=" << endpoint_id;
- return pcp_manager_.RequestConnection(client, endpoint_id, info, options);
-}
-
-Status OfflineServiceController::AcceptConnection(
- ClientProxy* client, const std::string& endpoint_id,
- const PayloadListener& listener) {
- if (stop_) return {Status::kOutOfOrderApiCall};
- NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
- << " accepted the connection with endpoint_id="
- << endpoint_id;
- return pcp_manager_.AcceptConnection(client, endpoint_id, listener);
-}
-
-Status OfflineServiceController::RejectConnection(
- ClientProxy* client, const std::string& endpoint_id) {
- if (stop_) return {Status::kOutOfOrderApiCall};
- NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
- << " rejected the connection with endpoint_id="
- << endpoint_id;
- return pcp_manager_.RejectConnection(client, endpoint_id);
-}
-
-void OfflineServiceController::InitiateBandwidthUpgrade(
- ClientProxy* client, const std::string& endpoint_id) {
- if (stop_) return;
- NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
- << " initiated a manual bandwidth upgrade with endpoint_id="
- << endpoint_id;
- bwu_manager_.InitiateBwuForEndpoint(client, endpoint_id);
-}
-
-void OfflineServiceController::SendPayload(
- ClientProxy* client, const std::vector<std::string>& endpoint_ids,
- Payload payload) {
- if (stop_) return;
- NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
- << " is sending payload_id=" << payload.GetId()
- << " to endpoint_ids={" << absl::StrJoin(endpoint_ids, ",")
- << "}";
- payload_manager_.SendPayload(client, endpoint_ids, std::move(payload));
-}
-
-Status OfflineServiceController::CancelPayload(ClientProxy* client,
- std::int64_t payload_id) {
- if (stop_) return {Status::kOutOfOrderApiCall};
- NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
- << " cancelled payload_id=" << payload_id;
- return payload_manager_.CancelPayload(client, payload_id);
-}
-
-void OfflineServiceController::DisconnectFromEndpoint(
- ClientProxy* client, const std::string& endpoint_id) {
- if (stop_) return;
- NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
- << " requested a disconnection from endpoint_id="
- << endpoint_id;
- endpoint_manager_.UnregisterEndpoint(client, endpoint_id);
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/offline_service_controller.h b/chromium/third_party/nearby/src/cpp/core/internal/offline_service_controller.h
deleted file mode 100644
index 6e397de9b02..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/offline_service_controller.h
+++ /dev/null
@@ -1,99 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_OFFLINE_SERVICE_CONTROLLER_H_
-#define CORE_INTERNAL_OFFLINE_SERVICE_CONTROLLER_H_
-
-#include <cstdint>
-#include <string>
-#include <vector>
-
-#include "core/internal/bwu_manager.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/endpoint_channel_manager.h"
-#include "core/internal/endpoint_manager.h"
-#include "core/internal/injected_bluetooth_device_store.h"
-#include "core/internal/mediums/mediums.h"
-#include "core/internal/payload_manager.h"
-#include "core/internal/pcp_manager.h"
-#include "core/internal/service_controller.h"
-#include "core/listeners.h"
-#include "core/options.h"
-#include "core/payload.h"
-#include "core/status.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-class OfflineServiceController : public ServiceController {
- public:
- OfflineServiceController() = default;
- ~OfflineServiceController() override;
-
- Status StartAdvertising(ClientProxy* client, const std::string& service_id,
- const ConnectionOptions& options,
- const ConnectionRequestInfo& info) override;
- void StopAdvertising(ClientProxy* client) override;
-
- Status StartDiscovery(ClientProxy* client, const std::string& service_id,
- const ConnectionOptions& options,
- const DiscoveryListener& listener) override;
- void StopDiscovery(ClientProxy* client) override;
-
- void InjectEndpoint(ClientProxy* client, const std::string& service_id,
- const OutOfBandConnectionMetadata& metadata) override;
-
- Status RequestConnection(ClientProxy* client, const std::string& endpoint_id,
- const ConnectionRequestInfo& info,
- const ConnectionOptions& options) override;
- Status AcceptConnection(ClientProxy* client, const std::string& endpoint_id,
- const PayloadListener& listener) override;
- Status RejectConnection(ClientProxy* client,
- const std::string& endpoint_id) override;
-
- void InitiateBandwidthUpgrade(ClientProxy* client,
- const std::string& endpoint_id) override;
-
- void SendPayload(ClientProxy* client,
- const std::vector<std::string>& endpoint_ids,
- Payload payload) override;
- Status CancelPayload(ClientProxy* client, Payload::Id payload_id) override;
-
- void DisconnectFromEndpoint(ClientProxy* client,
- const std::string& endpoint_id) override;
-
- void Stop() override;
-
- private:
- // Note that the order of declaration of these is crucial, because we depend
- // on the destructors running (strictly) in the reverse order; a deviation
- // from that will lead to crashes at runtime.
- AtomicBoolean stop_{false};
- Mediums mediums_;
- EndpointChannelManager channel_manager_;
- EndpointManager endpoint_manager_{&channel_manager_};
- PayloadManager payload_manager_{endpoint_manager_};
- BwuManager bwu_manager_{
- mediums_, endpoint_manager_, channel_manager_, {}, {}};
- InjectedBluetoothDeviceStore injected_bluetooth_device_store_;
- PcpManager pcp_manager_{mediums_, channel_manager_, endpoint_manager_,
- bwu_manager_, injected_bluetooth_device_store_};
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_OFFLINE_SERVICE_CONTROLLER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/offline_service_controller_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/offline_service_controller_test.cc
deleted file mode 100644
index 35f0484516a..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/offline_service_controller_test.cc
+++ /dev/null
@@ -1,388 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/offline_service_controller.h"
-
-#include <array>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "core/internal/offline_simulation_user.h"
-#include "platform/base/medium_environment.h"
-#include "platform/base/output_stream.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/logging.h"
-#include "platform/public/pipe.h"
-#include "platform/public/system_clock.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-
-using ::testing::Eq;
-
-constexpr std::array<char, 6> kFakeMacAddress = {'a', 'b', 'c', 'd', 'e', 'f'};
-constexpr absl::string_view kServiceId = "service-id";
-constexpr absl::string_view kDeviceA = "device-a";
-constexpr absl::string_view kDeviceB = "device-b";
-constexpr absl::string_view kMessage = "message";
-constexpr absl::Duration kProgressTimeout = absl::Milliseconds(1500);
-constexpr absl::Duration kDefaultTimeout = absl::Milliseconds(1500);
-constexpr absl::Duration kDisconnectTimeout = absl::Milliseconds(15000);
-
-constexpr BooleanMediumSelector kTestCases[] = {
- BooleanMediumSelector{
- .bluetooth = true,
- },
- BooleanMediumSelector{
- .wifi_lan = true,
- },
- BooleanMediumSelector{
- .bluetooth = true,
- .wifi_lan = true,
- },
-};
-
-class OfflineServiceControllerTest
- : public ::testing::TestWithParam<BooleanMediumSelector> {
- protected:
- OfflineServiceControllerTest() { env_.Stop(); }
-
- bool SetupConnection(OfflineSimulationUser& user_a,
- OfflineSimulationUser& user_b) {
- user_a.StartAdvertising(std::string(kServiceId), &connect_latch_);
- user_b.StartDiscovery(std::string(kServiceId), &discover_latch_);
- EXPECT_TRUE(discover_latch_.Await(kDefaultTimeout).result());
- EXPECT_EQ(user_b.GetDiscovered().service_id, kServiceId);
- EXPECT_EQ(user_b.GetDiscovered().endpoint_info, user_a.GetInfo());
- EXPECT_FALSE(user_b.GetDiscovered().endpoint_id.empty());
- NEARBY_LOG(INFO, "EP-B: [discovered] %s",
- user_b.GetDiscovered().endpoint_id.c_str());
- user_b.RequestConnection(&connect_latch_);
- EXPECT_TRUE(connect_latch_.Await(kDefaultTimeout).result());
- EXPECT_FALSE(user_a.GetDiscovered().endpoint_id.empty());
- NEARBY_LOG(INFO, "EP-A: [discovered] %s",
- user_a.GetDiscovered().endpoint_id.c_str());
- NEARBY_LOG(INFO, "Both users discovered their peers.");
- user_a.AcceptConnection(&accept_latch_);
- user_b.AcceptConnection(&accept_latch_);
- EXPECT_TRUE(accept_latch_.Await(kDefaultTimeout).result());
- NEARBY_LOG(INFO, "Both users reached connected state.");
- return user_a.IsConnected() && user_b.IsConnected();
- }
-
- CountDownLatch discover_latch_{1};
- CountDownLatch lost_latch_{1};
- CountDownLatch connect_latch_{2};
- CountDownLatch accept_latch_{2};
- CountDownLatch payload_latch_{1};
- MediumEnvironment& env_ = MediumEnvironment::Instance();
-};
-
-TEST_P(OfflineServiceControllerTest, CanCreateOne) {
- env_.Start();
- OfflineSimulationUser user_a(kDeviceA, GetParam());
- env_.Stop();
-}
-
-TEST_P(OfflineServiceControllerTest, CanCreateMany) {
- env_.Start();
- OfflineSimulationUser user_a(kDeviceA, GetParam());
- OfflineSimulationUser user_b(kDeviceB, GetParam());
- env_.Stop();
-}
-
-TEST_P(OfflineServiceControllerTest, CanStartAdvertising) {
- env_.Start();
- OfflineSimulationUser user_a(kDeviceA, GetParam());
- OfflineSimulationUser user_b(kDeviceB, GetParam());
- EXPECT_FALSE(user_a.IsAdvertising());
- EXPECT_THAT(user_a.StartAdvertising(std::string(kServiceId), nullptr),
- Eq(Status{Status::kSuccess}));
- EXPECT_TRUE(user_a.IsAdvertising());
- env_.Stop();
-}
-
-TEST_P(OfflineServiceControllerTest, CanStartDiscoveryBeforeAdvertising) {
- env_.Start();
- OfflineSimulationUser user_a(kDeviceA, GetParam());
- OfflineSimulationUser user_b(kDeviceB, GetParam());
- EXPECT_FALSE(user_b.IsDiscovering());
- EXPECT_THAT(user_b.StartDiscovery(std::string(kServiceId), &discover_latch_),
- Eq(Status{Status::kSuccess}));
- EXPECT_TRUE(user_b.IsDiscovering());
- EXPECT_THAT(user_a.StartAdvertising(std::string(kServiceId), nullptr),
- Eq(Status{Status::kSuccess}));
- EXPECT_TRUE(discover_latch_.Await(kDefaultTimeout).result());
- user_a.Stop();
- user_b.Stop();
- env_.Stop();
-}
-
-TEST_P(OfflineServiceControllerTest, CanStartDiscoveryAfterAdvertising) {
- env_.Start();
- OfflineSimulationUser user_a(kDeviceA, GetParam());
- OfflineSimulationUser user_b(kDeviceB, GetParam());
- EXPECT_FALSE(user_b.IsDiscovering());
- EXPECT_FALSE(user_b.IsAdvertising());
- EXPECT_THAT(user_a.StartAdvertising(std::string(kServiceId), nullptr),
- Eq(Status{Status::kSuccess}));
- EXPECT_THAT(user_b.StartDiscovery(std::string(kServiceId), &discover_latch_),
- Eq(Status{Status::kSuccess}));
- EXPECT_TRUE(user_a.IsAdvertising());
- EXPECT_TRUE(user_b.IsDiscovering());
- EXPECT_TRUE(discover_latch_.Await(kDefaultTimeout).result());
- user_a.Stop();
- user_b.Stop();
- env_.Stop();
-}
-
-TEST_P(OfflineServiceControllerTest, CanStopAdvertising) {
- env_.Start();
- OfflineSimulationUser user_a(kDeviceA, GetParam());
- OfflineSimulationUser user_b(kDeviceB, GetParam());
- EXPECT_FALSE(user_a.IsAdvertising());
- EXPECT_THAT(user_a.StartAdvertising(std::string(kServiceId), nullptr),
- Eq(Status{Status::kSuccess}));
- EXPECT_TRUE(user_a.IsAdvertising());
- user_a.StopAdvertising();
- EXPECT_FALSE(user_a.IsAdvertising());
- EXPECT_THAT(user_b.StartDiscovery(std::string(kServiceId), &discover_latch_,
- &lost_latch_),
- Eq(Status{Status::kSuccess}));
- EXPECT_TRUE(user_b.IsDiscovering());
- auto discover_none = discover_latch_.Await(kDefaultTimeout).GetResult();
- if (!discover_none) {
- EXPECT_TRUE(true);
- } else {
- // There are rare cases (1/1000) that advertisment data has been captured by
- // discovery device before advertising is stopped. So we need to check if
- // lost_cb has grabbed the event in the end to prove the advertising service
- // is stopped.
- EXPECT_TRUE(lost_latch_.Await(kDefaultTimeout).result());
- }
- user_a.Stop();
- user_b.Stop();
- env_.Stop();
-}
-
-TEST_P(OfflineServiceControllerTest, CanStopDiscovery) {
- env_.Start();
- OfflineSimulationUser user_a(kDeviceA, GetParam());
- OfflineSimulationUser user_b(kDeviceB, GetParam());
- EXPECT_FALSE(user_b.IsDiscovering());
- EXPECT_THAT(user_b.StartDiscovery(std::string(kServiceId), &discover_latch_),
- Eq(Status{Status::kSuccess}));
- EXPECT_TRUE(user_b.IsDiscovering());
- user_b.StopDiscovery();
- EXPECT_FALSE(user_b.IsDiscovering());
- EXPECT_THAT(user_a.StartAdvertising(std::string(kServiceId), nullptr),
- Eq(Status{Status::kSuccess}));
- EXPECT_FALSE(discover_latch_.Await(kDefaultTimeout).result());
- user_a.Stop();
- user_b.Stop();
- env_.Stop();
-}
-
-TEST_P(OfflineServiceControllerTest, CanConnect) {
- env_.Start();
- OfflineSimulationUser user_a(kDeviceA, GetParam());
- OfflineSimulationUser user_b(kDeviceB, GetParam());
- EXPECT_THAT(user_a.StartAdvertising(std::string(kServiceId), &connect_latch_),
- Eq(Status{Status::kSuccess}));
- EXPECT_THAT(user_b.StartDiscovery(std::string(kServiceId), &discover_latch_),
- Eq(Status{Status::kSuccess}));
- EXPECT_TRUE(discover_latch_.Await(kDefaultTimeout).result());
- EXPECT_THAT(user_b.RequestConnection(&connect_latch_),
- Eq(Status{Status::kSuccess}));
- EXPECT_TRUE(connect_latch_.Await(kDefaultTimeout).result());
- user_a.Stop();
- user_b.Stop();
- env_.Stop();
-}
-
-TEST_P(OfflineServiceControllerTest, CanAcceptConnection) {
- env_.Start();
- OfflineSimulationUser user_a(kDeviceA, GetParam());
- OfflineSimulationUser user_b(kDeviceB, GetParam());
- EXPECT_THAT(user_a.StartAdvertising(std::string(kServiceId), &connect_latch_),
- Eq(Status{Status::kSuccess}));
- EXPECT_THAT(user_b.StartDiscovery(std::string(kServiceId), &discover_latch_),
- Eq(Status{Status::kSuccess}));
- EXPECT_TRUE(discover_latch_.Await(kDefaultTimeout).result());
- EXPECT_THAT(user_b.RequestConnection(&connect_latch_),
- Eq(Status{Status::kSuccess}));
- EXPECT_TRUE(connect_latch_.Await(kDefaultTimeout).result());
- EXPECT_THAT(user_a.AcceptConnection(&accept_latch_),
- Eq(Status{Status::kSuccess}));
- EXPECT_THAT(user_b.AcceptConnection(&accept_latch_),
- Eq(Status{Status::kSuccess}));
- EXPECT_TRUE(accept_latch_.Await(kDefaultTimeout).result());
- EXPECT_TRUE(user_a.IsConnected());
- EXPECT_TRUE(user_b.IsConnected());
- user_a.Stop();
- user_b.Stop();
- env_.Stop();
-}
-
-TEST_P(OfflineServiceControllerTest, CanRejectConnection) {
- env_.Start();
- OfflineSimulationUser user_a(kDeviceA, GetParam());
- OfflineSimulationUser user_b(kDeviceB, GetParam());
- CountDownLatch reject_latch(1);
- EXPECT_THAT(user_a.StartAdvertising(std::string(kServiceId), &connect_latch_),
- Eq(Status{Status::kSuccess}));
- EXPECT_THAT(user_b.StartDiscovery(std::string(kServiceId), &discover_latch_),
- Eq(Status{Status::kSuccess}));
- EXPECT_TRUE(discover_latch_.Await(kDefaultTimeout).result());
- EXPECT_THAT(user_b.RequestConnection(&connect_latch_),
- Eq(Status{Status::kSuccess}));
- EXPECT_TRUE(connect_latch_.Await(kDefaultTimeout).result());
- user_a.ExpectRejectedConnection(reject_latch);
- EXPECT_THAT(user_b.RejectConnection(nullptr), Eq(Status{Status::kSuccess}));
- EXPECT_TRUE(reject_latch.Await(kDefaultTimeout).result());
- user_a.Stop();
- user_b.Stop();
- env_.Stop();
-}
-
-TEST_P(OfflineServiceControllerTest, CanSendBytePayload) {
- env_.Start();
- OfflineSimulationUser user_a(kDeviceA, GetParam());
- OfflineSimulationUser user_b(kDeviceB, GetParam());
- ASSERT_TRUE(SetupConnection(user_a, user_b));
- ByteArray message(std::string{kMessage});
- user_a.SendPayload(Payload(message));
- user_b.ExpectPayload(payload_latch_);
- EXPECT_TRUE(payload_latch_.Await(kDefaultTimeout).result());
- EXPECT_EQ(user_b.GetPayload().AsBytes(), message);
- user_a.Stop();
- user_b.Stop();
- env_.Stop();
-}
-
-TEST_P(OfflineServiceControllerTest, CanSendStreamPayload) {
- env_.Start();
- OfflineSimulationUser user_a(kDeviceA, GetParam());
- OfflineSimulationUser user_b(kDeviceB, GetParam());
- ASSERT_TRUE(SetupConnection(user_a, user_b));
- ByteArray message(std::string{kMessage});
- auto pipe = std::make_shared<Pipe>();
- OutputStream& tx = pipe->GetOutputStream();
- user_a.SendPayload(Payload([pipe]() -> InputStream& {
- return pipe->GetInputStream(); // NOLINT
- }));
- user_b.ExpectPayload(payload_latch_);
- tx.Write(message);
- EXPECT_TRUE(payload_latch_.Await(kDefaultTimeout).result());
- EXPECT_NE(user_b.GetPayload().AsStream(), nullptr);
- InputStream& rx = *user_b.GetPayload().AsStream();
- ASSERT_TRUE(user_b.WaitForProgress(
- [size = message.size()](const PayloadProgressInfo& info) -> bool {
- return info.bytes_transferred >= size;
- },
- kProgressTimeout));
- EXPECT_EQ(rx.Read(Pipe::kChunkSize).result(), message);
- user_a.Stop();
- user_b.Stop();
- env_.Stop();
-}
-
-TEST_P(OfflineServiceControllerTest, CanCancelStreamPayload) {
- env_.Start();
- OfflineSimulationUser user_a(kDeviceA, GetParam());
- OfflineSimulationUser user_b(kDeviceB, GetParam());
- ASSERT_TRUE(SetupConnection(user_a, user_b));
- ByteArray message(std::string{kMessage});
- auto pipe = std::make_shared<Pipe>();
- OutputStream& tx = pipe->GetOutputStream();
- user_a.SendPayload(Payload([pipe]() -> InputStream& {
- return pipe->GetInputStream(); // NOLINT
- }));
- user_b.ExpectPayload(payload_latch_);
- tx.Write(message);
- EXPECT_TRUE(payload_latch_.Await(kDefaultTimeout).result());
- EXPECT_NE(user_b.GetPayload().AsStream(), nullptr);
- InputStream& rx = *user_b.GetPayload().AsStream();
- ASSERT_TRUE(user_b.WaitForProgress(
- [size = message.size()](const PayloadProgressInfo& info) -> bool {
- return info.bytes_transferred >= size;
- },
- kProgressTimeout));
- EXPECT_EQ(rx.Read(Pipe::kChunkSize).result(), message);
- user_b.CancelPayload();
- int count = 0;
- while (true) {
- count++;
- if (!tx.Write(message).Ok()) break;
- SystemClock::Sleep(kDefaultTimeout);
- }
- EXPECT_TRUE(user_a.WaitForProgress(
- [](const PayloadProgressInfo& info) -> bool {
- return info.status == PayloadProgressInfo::Status::kCanceled;
- },
- kProgressTimeout));
- EXPECT_LT(count, 10);
- user_a.Stop();
- user_b.Stop();
- env_.Stop();
-}
-
-TEST_P(OfflineServiceControllerTest, CanDisconnect) {
- env_.Start();
- CountDownLatch disconnect_latch(1);
- OfflineSimulationUser user_a(kDeviceA, GetParam());
- OfflineSimulationUser user_b(kDeviceB, GetParam());
- ASSERT_TRUE(SetupConnection(user_a, user_b));
- NEARBY_LOGS(INFO) << "Disconnecting";
- user_b.ExpectDisconnect(disconnect_latch);
- user_b.Disconnect();
- EXPECT_TRUE(disconnect_latch.Await(kDisconnectTimeout).result());
- NEARBY_LOGS(INFO) << "Disconnected";
- EXPECT_FALSE(user_b.IsConnected());
- user_a.Stop();
- user_b.Stop();
- env_.Stop();
-}
-
-INSTANTIATE_TEST_SUITE_P(ParametrisedOfflineServiceControllerTest,
- OfflineServiceControllerTest,
- ::testing::ValuesIn(kTestCases));
-
-// Verifies that InjectEndpoint() can be run successfully; does not test the
-// full connection flow given that normal discovery/advertisement is skipped.
-// Note: Not parameterized because InjectEndpoint only works over Bluetooth.
-TEST_F(OfflineServiceControllerTest, InjectEndpoint) {
- env_.Start();
- OfflineSimulationUser user_a(kDeviceA,
- BooleanMediumSelector{.bluetooth = true});
- EXPECT_THAT(user_a.StartDiscovery(std::string(kServiceId),
- /*found_latch=*/nullptr),
- Eq(Status{Status::kSuccess}));
- EXPECT_TRUE(user_a.IsDiscovering());
- user_a.InjectEndpoint(
- std::string(kServiceId),
- OutOfBandConnectionMetadata{
- .medium = Medium::BLUETOOTH,
- .remote_bluetooth_mac_address = ByteArray(kFakeMacAddress),
- });
- user_a.Stop();
- env_.Stop();
-}
-
-} // namespace
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/offline_simulation_user.cc b/chromium/third_party/nearby/src/cpp/core/internal/offline_simulation_user.cc
deleted file mode 100644
index 6b6db548c9a..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/offline_simulation_user.cc
+++ /dev/null
@@ -1,202 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/offline_simulation_user.h"
-
-#include "absl/functional/bind_front.h"
-#include "core/listeners.h"
-#include "platform/base/byte_array.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/system_clock.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-void OfflineSimulationUser::OnConnectionInitiated(
- const std::string& endpoint_id, const ConnectionResponseInfo& info,
- bool is_outgoing) {
- if (is_outgoing) {
- NEARBY_LOG(INFO, "RequestConnection: initiated_cb called");
- } else {
- NEARBY_LOG(INFO, "StartAdvertising: initiated_cb called");
- discovered_ = DiscoveredInfo{
- .endpoint_id = endpoint_id,
- .endpoint_info = GetInfo(),
- .service_id = service_id_,
- };
- }
- if (initiated_latch_) initiated_latch_->CountDown();
-}
-
-void OfflineSimulationUser::OnConnectionAccepted(
- const std::string& endpoint_id) {
- if (accept_latch_) accept_latch_->CountDown();
-}
-
-void OfflineSimulationUser::OnConnectionRejected(const std::string& endpoint_id,
- Status status) {
- if (reject_latch_) reject_latch_->CountDown();
-}
-
-void OfflineSimulationUser::OnEndpointDisconnect(
- const std::string& endpoint_id) {
- NEARBY_LOGS(INFO) << "OnEndpointDisconnect: self=" << this
- << "; id=" << endpoint_id;
- if (disconnect_latch_) disconnect_latch_->CountDown();
-}
-
-void OfflineSimulationUser::OnEndpointFound(const std::string& endpoint_id,
- const ByteArray& endpoint_info,
- const std::string& service_id) {
- NEARBY_LOG(INFO, "Device discovered: id=%s", endpoint_id.c_str());
- discovered_ = DiscoveredInfo{
- .endpoint_id = endpoint_id,
- .endpoint_info = endpoint_info,
- .service_id = service_id,
- };
- if (found_latch_) found_latch_->CountDown();
-}
-
-void OfflineSimulationUser::OnEndpointLost(const std::string& endpoint_id) {
- if (lost_latch_) lost_latch_->CountDown();
-}
-
-void OfflineSimulationUser::OnPayload(const std::string& endpoint_id,
- Payload payload) {
- payload_ = std::move(payload);
- if (payload_latch_) payload_latch_->CountDown();
-}
-
-void OfflineSimulationUser::OnPayloadProgress(const std::string& endpoint_id,
- const PayloadProgressInfo& info) {
- MutexLock lock(&progress_mutex_);
- progress_info_ = info;
- if (future_ && predicate_ && predicate_(info)) future_->Set(true);
-}
-
-bool OfflineSimulationUser::WaitForProgress(
- std::function<bool(const PayloadProgressInfo&)> predicate,
- absl::Duration timeout) {
- Future<bool> future;
- {
- MutexLock lock(&progress_mutex_);
- if (predicate(progress_info_)) return true;
- future_ = &future;
- predicate_ = std::move(predicate);
- }
- auto response = future.Get(timeout);
- {
- MutexLock lock(&progress_mutex_);
- future_ = nullptr;
- predicate_ = nullptr;
- }
- return response.ok() && response.result();
-}
-
-Status OfflineSimulationUser::StartAdvertising(const std::string& service_id,
- CountDownLatch* latch) {
- initiated_latch_ = latch;
- service_id_ = service_id;
- ConnectionListener listener = {
- .initiated_cb =
- std::bind(&OfflineSimulationUser::OnConnectionInitiated, this,
- std::placeholders::_1, std::placeholders::_2, false),
- .accepted_cb =
- absl::bind_front(&OfflineSimulationUser::OnConnectionAccepted, this),
- .rejected_cb =
- absl::bind_front(&OfflineSimulationUser::OnConnectionRejected, this),
- .disconnected_cb =
- absl::bind_front(&OfflineSimulationUser::OnEndpointDisconnect, this),
- };
- return ctrl_.StartAdvertising(&client_, service_id_, options_,
- {
- .endpoint_info = info_,
- .listener = std::move(listener),
- });
-}
-
-void OfflineSimulationUser::StopAdvertising() {
- ctrl_.StopAdvertising(&client_);
-}
-
-Status OfflineSimulationUser::StartDiscovery(const std::string& service_id,
- CountDownLatch* found_latch,
- CountDownLatch* lost_latch) {
- found_latch_ = found_latch;
- lost_latch_ = lost_latch;
- DiscoveryListener listener = {
- .endpoint_found_cb =
- absl::bind_front(&OfflineSimulationUser::OnEndpointFound, this),
- .endpoint_lost_cb =
- absl::bind_front(&OfflineSimulationUser::OnEndpointLost, this),
- };
- return ctrl_.StartDiscovery(&client_, service_id, options_,
- std::move(listener));
-}
-
-void OfflineSimulationUser::StopDiscovery() { ctrl_.StopDiscovery(&client_); }
-
-void OfflineSimulationUser::InjectEndpoint(
- const std::string& service_id,
- const OutOfBandConnectionMetadata& metadata) {
- ctrl_.InjectEndpoint(&client_, service_id, metadata);
-}
-
-Status OfflineSimulationUser::RequestConnection(CountDownLatch* latch) {
- initiated_latch_ = latch;
- ConnectionListener listener = {
- .initiated_cb =
- std::bind(&OfflineSimulationUser::OnConnectionInitiated, this,
- std::placeholders::_1, std::placeholders::_2, true),
- .accepted_cb =
- absl::bind_front(&OfflineSimulationUser::OnConnectionAccepted, this),
- .rejected_cb =
- absl::bind_front(&OfflineSimulationUser::OnConnectionRejected, this),
- .disconnected_cb =
- absl::bind_front(&OfflineSimulationUser::OnEndpointDisconnect, this),
- };
- client_.AddCancellationFlag(discovered_.endpoint_id);
- return ctrl_.RequestConnection(&client_, discovered_.endpoint_id,
- {
- .endpoint_info = discovered_.endpoint_info,
- .listener = std::move(listener),
- },
- connection_options_);
-}
-
-Status OfflineSimulationUser::AcceptConnection(CountDownLatch* latch) {
- accept_latch_ = latch;
- PayloadListener listener = {
- .payload_cb = absl::bind_front(&OfflineSimulationUser::OnPayload, this),
- .payload_progress_cb =
- absl::bind_front(&OfflineSimulationUser::OnPayloadProgress, this),
- };
- return ctrl_.AcceptConnection(&client_, discovered_.endpoint_id,
- std::move(listener));
-}
-
-Status OfflineSimulationUser::RejectConnection(CountDownLatch* latch) {
- reject_latch_ = latch;
- return ctrl_.RejectConnection(&client_, discovered_.endpoint_id);
-}
-
-void OfflineSimulationUser::Disconnect() {
- NEARBY_LOGS(INFO) << "Disconnecting from id=" << discovered_.endpoint_id;
- ctrl_.DisconnectFromEndpoint(&client_, discovered_.endpoint_id);
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/offline_simulation_user.h b/chromium/third_party/nearby/src/cpp/core/internal/offline_simulation_user.h
deleted file mode 100644
index 01de6f886de..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/offline_simulation_user.h
+++ /dev/null
@@ -1,202 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_OFFLINE_SIMULATION_USER_H_
-#define CORE_INTERNAL_OFFLINE_SIMULATION_USER_H_
-
-#include <string>
-
-#include "gtest/gtest.h"
-#include "absl/strings/string_view.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/offline_service_controller.h"
-#include "core/options.h"
-#include "platform/public/atomic_boolean.h"
-#include "platform/public/condition_variable.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/future.h"
-
-// Test-only class to help run end-to-end simulations for nearby connections
-// protocol.
-//
-// This is a "standalone" version of PcpManager. It can run independently,
-// provided MediumEnvironment has adequate support for all medium types in use.
-namespace location {
-namespace nearby {
-namespace connections {
-
-class OfflineSimulationUser {
- public:
- struct DiscoveredInfo {
- std::string endpoint_id;
- ByteArray endpoint_info;
- std::string service_id;
-
- bool Empty() const { return endpoint_id.empty(); }
- void Clear() { endpoint_id.clear(); }
- };
-
- explicit OfflineSimulationUser(
- absl::string_view device_name,
- BooleanMediumSelector allowed = BooleanMediumSelector())
- : connection_options_{
- .keep_alive_interval_millis = FeatureFlags::GetInstance()
- .GetFlags()
- .keep_alive_interval_millis,
- .keep_alive_timeout_millis = FeatureFlags::GetInstance()
- .GetFlags()
- .keep_alive_timeout_millis,
- },
- info_{ByteArray{std::string(device_name)}},
- options_{
- .strategy = Strategy::kP2pCluster,
- .allowed = allowed,
- } {}
- virtual ~OfflineSimulationUser() = default;
-
- // Calls PcpManager::StartAdvertising().
- // If latch is provided, will call latch->CountDown() in the initiated_cb
- // callback.
- Status StartAdvertising(const std::string& service_id, CountDownLatch* latch);
-
- // Calls PcpManager::StopAdvertising().
- void StopAdvertising();
-
- // Calls PcpManager::StartDiscovery().
- // If found_latch is provided, will call found_latch->CountDown() in the
- // endpoint_found_cb callback.
- // If lost_latch is provided, will call lost_latch->CountDown() in the
- // endpoint_lost_cb callback.
- Status StartDiscovery(const std::string& service_id,
- CountDownLatch* found_latch,
- CountDownLatch* lost_latch = nullptr);
-
- // Calls PcpManager::StopDiscovery().
- void StopDiscovery();
-
- // Calls PcpManager::InjectEndpoint();
- void InjectEndpoint(const std::string& service_id,
- const OutOfBandConnectionMetadata& metadata);
-
- // Calls PcpManager::RequestConnection().
- // If latch is provided, latch->CountDown() will be called in the initiated_cb
- // callback.
- Status RequestConnection(CountDownLatch* latch);
-
- // Calls PcpManager::AcceptConnection.
- // If latch is provided, latch->CountDown() will be called in the accepted_cb
- // callback.
- Status AcceptConnection(CountDownLatch* latch);
-
- // Calls PcpManager::RejectConnection.
- // If latch is provided, latch->CountDown() will be called in the rejected_cb
- // callback.
- Status RejectConnection(CountDownLatch* latch);
-
- // Unlike acceptance, rejection does not have to be mutual, in order to work.
- // This method will allow to synchronize on the remote rejection, without
- // performing a local rejection.
- // latch.CountDown() will be called in the rejected_cb callback.
- void ExpectRejectedConnection(CountDownLatch& latch) {
- reject_latch_ = &latch;
- }
-
- void ExpectPayload(CountDownLatch& latch) { payload_latch_ = &latch; }
- void ExpectDisconnect(CountDownLatch& latch) { disconnect_latch_ = &latch; }
-
- const DiscoveredInfo& GetDiscovered() const { return discovered_; }
- ByteArray GetInfo() const { return info_; }
-
- bool WaitForProgress(std::function<bool(const PayloadProgressInfo&)> pred,
- absl::Duration timeout);
-
- Payload& GetPayload() { return payload_; }
- void SendPayload(Payload payload) {
- sender_payload_id_ = payload.GetId();
- ctrl_.SendPayload(&client_, {discovered_.endpoint_id}, std::move(payload));
- }
-
- Status CancelPayload() {
- if (sender_payload_id_) {
- return ctrl_.CancelPayload(&client_, sender_payload_id_);
- } else {
- return ctrl_.CancelPayload(&client_, payload_.GetId());
- }
- }
-
- void Disconnect();
-
- bool IsAdvertising() const { return client_.IsAdvertising(); }
-
- bool IsDiscovering() const { return client_.IsDiscovering(); }
-
- bool IsConnected() const {
- return client_.IsConnectedToEndpoint(discovered_.endpoint_id);
- }
-
- void Stop() {
- StopAdvertising();
- StopDiscovery();
- ctrl_.Stop();
- }
-
- protected:
- // ConnectionListener callbacks
- void OnConnectionInitiated(const std::string& endpoint_id,
- const ConnectionResponseInfo& info,
- bool is_outgoing);
- void OnConnectionAccepted(const std::string& endpoint_id);
- void OnConnectionRejected(const std::string& endpoint_id, Status status);
- void OnEndpointDisconnect(const std::string& endpoint_id);
-
- // DiscoveryListener callbacks
- void OnEndpointFound(const std::string& endpoint_id,
- const ByteArray& endpoint_info,
- const std::string& service_id);
- void OnEndpointLost(const std::string& endpoint_id);
-
- // PayloadListener callbacks
- void OnPayload(const std::string& endpoint_id, Payload payload);
- void OnPayloadProgress(const std::string& endpoint_id,
- const PayloadProgressInfo& info);
-
- std::string service_id_;
- DiscoveredInfo discovered_;
- ConnectionOptions connection_options_;
-
- Mutex progress_mutex_;
- ConditionVariable progress_sync_{&progress_mutex_};
- PayloadProgressInfo progress_info_;
- Payload payload_;
- Payload::Id sender_payload_id_ = 0;
- CountDownLatch* initiated_latch_ = nullptr;
- CountDownLatch* accept_latch_ = nullptr;
- CountDownLatch* reject_latch_ = nullptr;
- CountDownLatch* found_latch_ = nullptr;
- CountDownLatch* lost_latch_ = nullptr;
- CountDownLatch* payload_latch_ = nullptr;
- CountDownLatch* disconnect_latch_ = nullptr;
- Future<bool>* future_ = nullptr;
- std::function<bool(const PayloadProgressInfo&)> predicate_;
- ByteArray info_;
- ConnectionOptions options_;
- ClientProxy client_;
- OfflineServiceController ctrl_;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_OFFLINE_SIMULATION_USER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/p2p_cluster_pcp_handler.cc b/chromium/third_party/nearby/src/cpp/core/internal/p2p_cluster_pcp_handler.cc
deleted file mode 100644
index 1bcc5999da4..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/p2p_cluster_pcp_handler.cc
+++ /dev/null
@@ -1,1364 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/p2p_cluster_pcp_handler.h"
-
-#include "absl/functional/bind_front.h"
-#include "absl/strings/escaping.h"
-#include "core/internal/base_pcp_handler.h"
-#include "core/internal/ble_advertisement.h"
-#include "core/internal/ble_endpoint_channel.h"
-#include "core/internal/bluetooth_endpoint_channel.h"
-#include "core/internal/bwu_manager.h"
-#include "core/internal/mediums/utils.h"
-#include "core/internal/mediums/webrtc_socket_wrapper.h"
-#include "core/internal/webrtc_endpoint_channel.h"
-#include "core/internal/wifi_lan_endpoint_channel.h"
-#include "platform/base/nsd_service_info.h"
-#include "platform/base/types.h"
-#include "platform/public/crypto.h"
-#include "proto/connections_enums.pb.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-ByteArray P2pClusterPcpHandler::GenerateHash(const std::string& source,
- size_t size) {
- return Utils::Sha256Hash(source, size);
-}
-
-bool P2pClusterPcpHandler::ShouldAdvertiseBluetoothMacOverBle(
- PowerLevel power_level) {
- return power_level == PowerLevel::kHighPower;
-}
-
-bool P2pClusterPcpHandler::ShouldAcceptBluetoothConnections(
- const ConnectionOptions& options) {
- return options.enable_bluetooth_listening;
-}
-
-P2pClusterPcpHandler::P2pClusterPcpHandler(
- Mediums* mediums, EndpointManager* endpoint_manager,
- EndpointChannelManager* endpoint_channel_manager, BwuManager* bwu_manager,
- InjectedBluetoothDeviceStore& injected_bluetooth_device_store, Pcp pcp)
- : BasePcpHandler(mediums, endpoint_manager, endpoint_channel_manager,
- bwu_manager, pcp),
- bluetooth_radio_(mediums->GetBluetoothRadio()),
- bluetooth_medium_(mediums->GetBluetoothClassic()),
- ble_medium_(mediums->GetBle()),
- wifi_lan_medium_(mediums->GetWifiLan()),
- webrtc_medium_(mediums->GetWebRtc()),
- injected_bluetooth_device_store_(injected_bluetooth_device_store) {}
-
-// Returns a vector or mediums sorted in order or decreasing priority for
-// all the supported mediums.
-// Example: WiFi_LAN, WEB_RTC, BT, BLE
-std::vector<proto::connections::Medium>
-P2pClusterPcpHandler::GetConnectionMediumsByPriority() {
- std::vector<proto::connections::Medium> mediums;
- if (wifi_lan_medium_.IsAvailable()) {
- mediums.push_back(proto::connections::WIFI_LAN);
- }
- if (webrtc_medium_.IsAvailable()) {
- mediums.push_back(proto::connections::WEB_RTC);
- }
- if (bluetooth_medium_.IsAvailable()) {
- mediums.push_back(proto::connections::BLUETOOTH);
- }
- if (ble_medium_.IsAvailable()) {
- mediums.push_back(proto::connections::BLE);
- }
- return mediums;
-}
-
-proto::connections::Medium P2pClusterPcpHandler::GetDefaultUpgradeMedium() {
- return proto::connections::WIFI_LAN;
-}
-
-BasePcpHandler::StartOperationResult P2pClusterPcpHandler::StartAdvertisingImpl(
- ClientProxy* client, const std::string& service_id,
- const std::string& local_endpoint_id, const ByteArray& local_endpoint_info,
- const ConnectionOptions& options) {
- std::vector<proto::connections::Medium> mediums_started_successfully;
-
- WebRtcState web_rtc_state{WebRtcState::kUnconnectable};
-
- if (options.allowed.wifi_lan) {
- proto::connections::Medium wifi_lan_medium =
- StartWifiLanAdvertising(client, service_id, local_endpoint_id,
- local_endpoint_info, web_rtc_state);
- if (wifi_lan_medium != proto::connections::UNKNOWN_MEDIUM) {
- NEARBY_LOGS(INFO)
- << "P2pClusterPcpHandler::StartAdvertisingImpl: WifiLan added";
- mediums_started_successfully.push_back(wifi_lan_medium);
- }
- }
-
- if (options.allowed.bluetooth) {
- const ByteArray bluetooth_hash =
- GenerateHash(service_id, BluetoothDeviceName::kServiceIdHashLength);
- proto::connections::Medium bluetooth_medium = StartBluetoothAdvertising(
- client, service_id, bluetooth_hash, local_endpoint_id,
- local_endpoint_info, web_rtc_state);
- if (bluetooth_medium != proto::connections::UNKNOWN_MEDIUM) {
- NEARBY_LOG(INFO, "P2pClusterPcpHandler::StartAdvertisingImpl: BT added");
- mediums_started_successfully.push_back(bluetooth_medium);
- bluetooth_classic_advertiser_client_id_ = client->GetClientId();
- }
- }
-
- if (options.allowed.ble) {
- proto::connections::Medium ble_medium =
- StartBleAdvertising(client, service_id, local_endpoint_id,
- local_endpoint_info, options, web_rtc_state);
- if (ble_medium != proto::connections::UNKNOWN_MEDIUM) {
- NEARBY_LOGS(INFO)
- << "P2pClusterPcpHandler::StartAdvertisingImpl: Ble added";
- mediums_started_successfully.push_back(ble_medium);
- }
- }
-
- if (mediums_started_successfully.empty()) {
- NEARBY_LOGS(ERROR) << "Failed StartAdvertising("
- << absl::BytesToHexString(local_endpoint_info.data())
- << ") for client=" << client->GetClientId();
- return {
- .status = {Status::kBluetoothError},
- };
- }
-
- // The rest of the operations for startAdvertising() will continue
- // asynchronously via
- // IncomingBluetoothConnectionProcessor.onIncomingBluetoothConnection(), so
- // leave it to that to signal any errors that may occur.
- return {
- .status = {Status::kSuccess},
- .mediums = std::move(mediums_started_successfully),
- };
-}
-
-Status P2pClusterPcpHandler::StopAdvertisingImpl(ClientProxy* client) {
- if (client->GetClientId() == bluetooth_classic_advertiser_client_id_) {
- bluetooth_medium_.TurnOffDiscoverability();
- bluetooth_classic_advertiser_client_id_ = 0;
- } else {
- NEARBY_LOGS(INFO) << "Skipped BT TurnOffDiscoverability for client="
- << client->GetClientId()
- << ", client that turned on discoverability is "
- << bluetooth_classic_advertiser_client_id_;
- }
-
- bluetooth_medium_.StopAcceptingConnections(client->GetAdvertisingServiceId());
-
- ble_medium_.StopAdvertising(client->GetAdvertisingServiceId());
- ble_medium_.StopAcceptingConnections(client->GetAdvertisingServiceId());
-
- wifi_lan_medium_.StopAdvertising(client->GetAdvertisingServiceId());
- wifi_lan_medium_.StopAcceptingConnections(client->GetAdvertisingServiceId());
-
- return {Status::kSuccess};
-}
-
-bool P2pClusterPcpHandler::IsRecognizedBluetoothEndpoint(
- const std::string& name_string, const std::string& service_id,
- const BluetoothDeviceName& name) const {
- if (!name.IsValid()) {
- NEARBY_LOGS(INFO)
- << name_string
- << " doesn't conform to the BluetoothDeviceName format, discarding.";
- return false;
- }
-
- if (name.GetPcp() != GetPcp()) {
- NEARBY_LOGS(INFO) << name_string << " doesn't match on Pcp; expected "
- << PcpToStrategy(GetPcp()).GetName() << ", found "
- << PcpToStrategy(name.GetPcp()).GetName();
- return false;
- }
-
- ByteArray expected_service_id_hash =
- GenerateHash(service_id, BluetoothDeviceName::kServiceIdHashLength);
-
- if (name.GetServiceIdHash() != expected_service_id_hash) {
- NEARBY_LOGS(INFO) << name_string
- << " doesn't match on expected service_id_hash; expected "
- << absl::BytesToHexString(expected_service_id_hash.data())
- << ", found "
- << absl::BytesToHexString(name.GetServiceIdHash().data());
- return false;
- }
-
- return true;
-}
-
-void P2pClusterPcpHandler::BluetoothDeviceDiscoveredHandler(
- ClientProxy* client, const std::string& service_id,
- BluetoothDevice device) {
- RunOnPcpHandlerThread(
- "p2p-bt-device-discovered",
- [this, client, service_id, device]()
- RUN_ON_PCP_HANDLER_THREAD() {
- // Make sure we are still discovering before proceeding.
- if (!client->IsDiscovering()) {
- NEARBY_LOGS(WARNING) << "Skipping discovery of BluetoothDevice "
- << device.GetName()
- << " because we are no longer discovering.";
- return;
- }
-
- // Parse the Bluetooth device name.
- const std::string device_name_string = device.GetName();
- BluetoothDeviceName device_name(device_name_string);
-
- // Make sure the Bluetooth device name points to a valid
- // endpoint we're discovering.
- if (!IsRecognizedBluetoothEndpoint(device_name_string, service_id,
- device_name)) {
- NEARBY_LOGS(INFO) << "Found unrecognized BluetoothDeviceName "
- << device_name_string;
- return;
- }
-
- // Report the discovered endpoint to the client.
- NEARBY_LOGS(INFO)
- << "Found BluetoothDeviceName " << device_name_string
- << " (with endpoint_id=" << device_name.GetEndpointId()
- << " and endpoint_info="
- << absl::BytesToHexString(device_name.GetEndpointInfo().data())
- << ").";
- OnEndpointFound(
- client,
- std::make_shared<BluetoothEndpoint>(BluetoothEndpoint{
- {device_name.GetEndpointId(), device_name.GetEndpointInfo(),
- service_id, proto::connections::Medium::BLUETOOTH,
- device_name.GetWebRtcState()},
- device,
- }));
- });
-}
-
-void P2pClusterPcpHandler::BluetoothNameChangedHandler(
- ClientProxy* client, const std::string& service_id,
- BluetoothDevice device) {
- RunOnPcpHandlerThread(
- "p2p-bt-name-changed",
- [this, client, service_id, device]() RUN_ON_PCP_HANDLER_THREAD() {
- // Make sure we are still discovering before proceeding.
- if (!client->IsDiscovering()) {
- NEARBY_LOGS(WARNING)
- << "Ignoring lost BluetoothDevice " << device.GetName()
- << " because Connections is no longer discovering.";
- return;
- }
-
- // Parse the Bluetooth device name.
- const std::string device_name_string = device.GetName();
- BluetoothDeviceName device_name(device_name_string);
- NEARBY_LOGS(INFO) << "BT discovery handler (CHANGED) [client_id="
- << client->GetClientId()
- << ", service_id=" << service_id
- << "]: processing new name " << device_name_string;
-
- // By this point, the BluetoothDevice passed to us has a different name
- // than what we may have discovered before. We need to iterate over the
- // found BluetoothEndpoints and compare their addresses to see the
- // devices are the same. We are not guaranteed to discover a match,
- // since the old name may not have been formatted for Nearby
- // Connections.
- for (auto endpoint :
- GetDiscoveredEndpoints(proto::connections::Medium::BLUETOOTH)) {
- BluetoothEndpoint* bluetoothEndpoint =
- static_cast<BluetoothEndpoint*>(endpoint);
- NEARBY_LOGS(INFO)
- << "BT discovery handler (CHANGED) [client_id="
- << client->GetClientId() << ", service_id=" << service_id
- << "]: comparing MAC addresses with existing endpoint "
- << bluetoothEndpoint->bluetooth_device.GetName()
- << ". They have MAC address "
- << bluetoothEndpoint->bluetooth_device.GetMacAddress()
- << " and the new endpoint has MAC address "
- << device.GetMacAddress();
- if (bluetoothEndpoint->bluetooth_device.GetMacAddress() ==
- device.GetMacAddress()) {
- // Report the BluetoothEndpoint as lost to the client.
- NEARBY_LOGS(INFO) << "Reporting lost BluetoothDevice "
- << bluetoothEndpoint->bluetooth_device.GetName()
- << ", due to device name change.";
- OnEndpointLost(client, *endpoint);
- break;
- }
- }
-
- // Make sure the Bluetooth device name points to a valid
- // endpoint we're discovering.
- if (!IsRecognizedBluetoothEndpoint(device_name_string, service_id,
- device_name)) {
- NEARBY_LOGS(INFO) << "Found unrecognized BluetoothDeviceName "
- << device_name_string;
- return;
- }
-
- // Report the discovered endpoint to the client.
- NEARBY_LOGS(INFO) << "Found BluetoothDeviceName " << device_name_string
- << " (with endpoint_id="
- << device_name.GetEndpointId()
- << " and endpoint_info="
- << absl::BytesToHexString(
- device_name.GetEndpointInfo().data())
- << ").";
- OnEndpointFound(
- client,
- std::make_shared<BluetoothEndpoint>(BluetoothEndpoint{
- {device_name.GetEndpointId(), device_name.GetEndpointInfo(),
- service_id, proto::connections::Medium::BLUETOOTH,
- device_name.GetWebRtcState()},
- device,
- }));
- });
-}
-
-void P2pClusterPcpHandler::BluetoothDeviceLostHandler(
- ClientProxy* client, const std::string& service_id,
- BluetoothDevice& device) {
- const std::string& device_name_string = device.GetName();
- RunOnPcpHandlerThread(
- "p2p-bt-device-lost", [this, client, service_id,
- device_name_string]() RUN_ON_PCP_HANDLER_THREAD() {
- // Make sure we are still discovering before proceeding.
- if (!client->IsDiscovering()) {
- NEARBY_LOGS(WARNING)
- << "Ignoring lost BluetoothDevice " << device_name_string
- << " because Connections is no "
- "longer discovering.";
- return;
- }
-
- // Parse the Bluetooth device name.
- BluetoothDeviceName device_name(device_name_string);
-
- // Make sure the Bluetooth device name points to a valid
- // endpoint we're discovering.
- if (!IsRecognizedBluetoothEndpoint(device_name_string, service_id,
- device_name))
- return;
-
- // Report the BluetoothEndpoint as lost to the client.
- NEARBY_LOGS(INFO) << "Processing lost BluetoothDeviceName "
- << device_name_string;
- OnEndpointLost(client, DiscoveredEndpoint{
- device_name.GetEndpointId(),
- device_name.GetEndpointInfo(), service_id,
- proto::connections::Medium::BLUETOOTH,
- WebRtcState::kUndefined});
- });
-}
-
-bool P2pClusterPcpHandler::IsRecognizedBleEndpoint(
- const std::string& service_id,
- const BleAdvertisement& advertisement) const {
- if (!advertisement.IsValid()) {
- NEARBY_LOGS(INFO)
- << "BleAdvertisement doesn't conform to the format, discarding.";
- return false;
- }
-
- if (advertisement.GetVersion() != kBleAdvertisementVersion) {
- NEARBY_LOGS(INFO) << "BleAdvertisement has an unknown version; expected "
- << static_cast<int>(kBleAdvertisementVersion)
- << ", found "
- << static_cast<int>(advertisement.GetVersion());
- return false;
- }
-
- if (advertisement.GetPcp() != GetPcp()) {
- NEARBY_LOGS(INFO) << "BleAdvertisement doesn't match on Pcp; expected "
- << PcpToStrategy(GetPcp()).GetName() << ", found "
- << PcpToStrategy(advertisement.GetPcp()).GetName();
- return false;
- }
-
- // Check ServiceId for normal advertisement.
- // ServiceIdHash is empty for fast advertisement.
- if (!advertisement.IsFastAdvertisement()) {
- ByteArray expected_service_id_hash =
- GenerateHash(service_id, BleAdvertisement::kServiceIdHashLength);
-
- if (advertisement.GetServiceIdHash() != expected_service_id_hash) {
- NEARBY_LOGS(INFO)
- << "BleAdvertisement doesn't match on expected service_id_hash; "
- "expected "
- << absl::BytesToHexString(expected_service_id_hash.data())
- << ", found "
- << absl::BytesToHexString(advertisement.GetServiceIdHash().data());
- return false;
- }
- }
-
- return true;
-}
-
-void P2pClusterPcpHandler::BlePeripheralDiscoveredHandler(
- ClientProxy* client, BlePeripheral& peripheral,
- const std::string& service_id, const ByteArray& advertisement_bytes,
- bool fast_advertisement) {
- RunOnPcpHandlerThread(
- "p2p-ble-device-discovered",
- [this, client, &peripheral, service_id, advertisement_bytes,
- fast_advertisement]() RUN_ON_PCP_HANDLER_THREAD() {
- // Make sure we are still discovering before proceeding.
- if (!client->IsDiscovering()) {
- NEARBY_LOGS(WARNING)
- << "Skipping discovery of BleAdvertisement header "
- << absl::BytesToHexString(advertisement_bytes.data())
- << " because we are no longer discovering.";
- return;
- }
-
- // Parse the BLE advertisement bytes.
- BleAdvertisement advertisement(fast_advertisement, advertisement_bytes);
-
- // Make sure the BLE advertisement points to a valid
- // endpoint we're discovering.
- if (!IsRecognizedBleEndpoint(service_id, advertisement)) return;
-
- // Store all the state we need to be able to re-create a BleEndpoint
- // in BlePeripheralLostHandler, since that isn't privy to
- // the bytes of the ble advertisement itself.
- found_ble_endpoints_.emplace(
- peripheral.GetName(),
- BleEndpointState(advertisement.GetEndpointId(),
- advertisement.GetEndpointInfo()));
-
- // Report the discovered endpoint to the client.
- NEARBY_LOGS(INFO) << "Found BleAdvertisement "
- << absl::BytesToHexString(advertisement_bytes.data())
- << " (with endpoint_id="
- << advertisement.GetEndpointId()
- << ", and endpoint_info="
- << absl::BytesToHexString(
- advertisement.GetEndpointInfo().data())
- << ").",
- OnEndpointFound(client,
- std::make_shared<BleEndpoint>(BleEndpoint{
- {advertisement.GetEndpointId(),
- advertisement.GetEndpointInfo(), service_id,
- proto::connections::Medium::BLE,
- advertisement.GetWebRtcState()},
- peripheral,
- }));
-
- // Make sure we can connect to this device via Classic Bluetooth.
- std::string remote_bluetooth_mac_address =
- advertisement.GetBluetoothMacAddress();
- if (remote_bluetooth_mac_address.empty()) {
- NEARBY_LOGS(INFO)
- << "No Bluetooth Classic MAC address found in advertisement.";
- return;
- }
-
- BluetoothDevice remote_bluetooth_device =
- bluetooth_medium_.GetRemoteDevice(remote_bluetooth_mac_address);
- if (!remote_bluetooth_device.IsValid()) {
- NEARBY_LOGS(INFO)
- << "A valid Bluetooth device could not be derived from the MAC "
- "address "
- << remote_bluetooth_mac_address;
- return;
- }
-
- OnEndpointFound(client,
- std::make_shared<BluetoothEndpoint>(BluetoothEndpoint{
- {
- advertisement.GetEndpointId(),
- advertisement.GetEndpointInfo(),
- service_id,
- proto::connections::Medium::BLUETOOTH,
- advertisement.GetWebRtcState(),
- },
- remote_bluetooth_device,
- }));
- });
-}
-
-void P2pClusterPcpHandler::BlePeripheralLostHandler(
- ClientProxy* client, BlePeripheral& peripheral,
- const std::string& service_id) {
- std::string peripheral_name = peripheral.GetName();
- NEARBY_LOG(INFO, "Ble: [LOST, SCHED] peripheral_name=%s",
- peripheral_name.c_str());
- RunOnPcpHandlerThread(
- "p2p-ble-device-lost",
- [this, client, service_id, &peripheral]() RUN_ON_PCP_HANDLER_THREAD() {
- // Make sure we are still discovering before proceeding.
- if (!client->IsDiscovering()) {
- NEARBY_LOGS(WARNING)
- << "Ignoring lost BlePeripheral " << peripheral.GetName()
- << " because we are no longer discovering.";
- return;
- }
-
- // Remove this BlePeripheral from found_ble_endpoints_, and
- // report the endpoint as lost to the client.
- auto item = found_ble_endpoints_.find(peripheral.GetName());
- if (item != found_ble_endpoints_.end()) {
- BleEndpointState ble_endpoint_state(item->second);
- found_ble_endpoints_.erase(item);
-
- // Report the discovered endpoint to the client.
- NEARBY_LOGS(INFO)
- << "Lost BleEndpoint for BlePeripheral " << peripheral.GetName()
- << " (with endpoint_id=" << ble_endpoint_state.endpoint_id
- << " and endpoint_info="
- << absl::BytesToHexString(ble_endpoint_state.endpoint_info.data())
- << ").";
- OnEndpointLost(client, DiscoveredEndpoint{
- ble_endpoint_state.endpoint_id,
- ble_endpoint_state.endpoint_info,
- service_id,
- proto::connections::Medium::BLE,
- WebRtcState::kUndefined,
- });
- }
- });
-}
-
-bool P2pClusterPcpHandler::IsRecognizedWifiLanEndpoint(
- const std::string& service_id,
- const WifiLanServiceInfo& wifi_lan_service_info) const {
- if (!wifi_lan_service_info.IsValid()) {
- NEARBY_LOGS(INFO)
- << "WifiLanServiceInfo doesn't conform to the format, discarding.";
- return false;
- }
-
- if (wifi_lan_service_info.GetPcp() != GetPcp()) {
- NEARBY_LOGS(INFO)
- << "WifiLanServiceInfo doesn't match on Pcp; expected "
- << PcpToStrategy(GetPcp()).GetName() << ", found "
- << PcpToStrategy(wifi_lan_service_info.GetPcp()).GetName();
- return false;
- }
-
- ByteArray expected_service_id_hash =
- GenerateHash(service_id, WifiLanServiceInfo::kServiceIdHashLength);
-
- if (wifi_lan_service_info.GetServiceIdHash() != expected_service_id_hash) {
- NEARBY_LOGS(INFO)
- << "WifiLanServiceInfo doesn't match on expected service_id_hash; "
- "expected "
- << absl::BytesToHexString(expected_service_id_hash.data()) << ", found "
- << absl::BytesToHexString(
- wifi_lan_service_info.GetServiceIdHash().data());
- return false;
- }
-
- return true;
-}
-
-void P2pClusterPcpHandler::WifiLanServiceDiscoveredHandler(
- ClientProxy* client, NsdServiceInfo service_info,
- const std::string& service_id) {
- RunOnPcpHandlerThread(
- "p2p-wifi-service-discovered",
- [this, client, service_id, service_info]() RUN_ON_PCP_HANDLER_THREAD() {
- // Make sure we are still discovering before proceeding.
- if (!client->IsDiscovering()) {
- NEARBY_LOGS(WARNING) << "Skipping discovery of NsdServiceInfo "
- << service_info.GetServiceName()
- << " because we are no longer discovering.";
- return;
- }
-
- // Parse the WifiLanServiceInfo.
- WifiLanServiceInfo wifi_lan_service_info(service_info);
- // Make sure the WifiLan service name points to a valid
- // endpoint we're discovering.
- if (!IsRecognizedWifiLanEndpoint(service_id, wifi_lan_service_info)) {
- return;
- }
-
- // Report the discovered endpoint to the client.
- NEARBY_LOGS(INFO) << "Found NsdServiceInfo "
- << service_info.GetServiceName()
- << " (with endpoint_id="
- << wifi_lan_service_info.GetEndpointId()
- << "and endpoint_info="
- << absl::BytesToHexString(
- wifi_lan_service_info.GetEndpointInfo().data())
- << ").";
- OnEndpointFound(client,
- std::make_shared<WifiLanEndpoint>(WifiLanEndpoint{
- {
- wifi_lan_service_info.GetEndpointId(),
- wifi_lan_service_info.GetEndpointInfo(),
- service_id,
- proto::connections::Medium::WIFI_LAN,
- wifi_lan_service_info.GetWebRtcState(),
- },
- service_info,
- }));
- });
-}
-
-void P2pClusterPcpHandler::WifiLanServiceLostHandler(
- ClientProxy* client, NsdServiceInfo service_info,
- const std::string& service_id) {
- NEARBY_LOGS(INFO) << "WifiLan: [LOST, SCHED] service_info=" << &service_info
- << ", service_name=" << service_info.GetServiceName();
- RunOnPcpHandlerThread(
- "p2p-wifi-service-lost",
- [this, client, service_id, service_info]() RUN_ON_PCP_HANDLER_THREAD() {
- // Make sure we are still discovering before proceeding.
- if (!client->IsDiscovering()) {
- NEARBY_LOGS(WARNING) << "Ignoring lost NsdServiceInfo "
- << service_info.GetServiceName()
- << " because we are no longer "
- "discovering.";
- return;
- }
-
- // Parse the WifiLanServiceInfo.
- WifiLanServiceInfo wifi_lan_service_info(service_info);
-
- // Make sure the WifiLan service name points to a valid
- // endpoint we're discovering.
- if (!IsRecognizedWifiLanEndpoint(service_id, wifi_lan_service_info))
- return;
-
- // Report the lost endpoint to the client.
- NEARBY_LOGS(INFO) << "Lost NsdServiceInfo "
- << service_info.GetServiceName()
- << " (with endpoint_id="
- << wifi_lan_service_info.GetEndpointId()
- << " and endpoint_info="
- << absl::BytesToHexString(
- wifi_lan_service_info.GetEndpointInfo().data())
- << ").";
- OnEndpointLost(client, DiscoveredEndpoint{
- wifi_lan_service_info.GetEndpointId(),
- wifi_lan_service_info.GetEndpointInfo(),
- service_id,
- proto::connections::Medium::WIFI_LAN,
- WebRtcState::kUndefined,
- });
- });
-}
-
-BasePcpHandler::StartOperationResult P2pClusterPcpHandler::StartDiscoveryImpl(
- ClientProxy* client, const std::string& service_id,
- const ConnectionOptions& options) {
- // If this is an out-of-band connection, do not start actual discovery, since
- // this connection is intended to be completed via InjectEndpointImpl().
- if (options.is_out_of_band_connection) {
- return {.status = {Status::kSuccess},
- .mediums = options.allowed.GetMediums(true)};
- }
-
- std::vector<proto::connections::Medium> mediums_started_successfully;
-
- if (options.allowed.wifi_lan) {
- proto::connections::Medium wifi_lan_medium = StartWifiLanDiscovery(
- {
- .service_discovered_cb = absl::bind_front(
- &P2pClusterPcpHandler::WifiLanServiceDiscoveredHandler, this,
- client),
- .service_lost_cb = absl::bind_front(
- &P2pClusterPcpHandler::WifiLanServiceLostHandler, this, client),
- },
- client, service_id);
- if (wifi_lan_medium != proto::connections::UNKNOWN_MEDIUM) {
- NEARBY_LOGS(INFO)
- << "P2pClusterPcpHandler::StartDiscoveryImpl: WifiLan added";
- mediums_started_successfully.push_back(wifi_lan_medium);
- }
- }
-
- if (options.allowed.bluetooth) {
- proto::connections::Medium bluetooth_medium = StartBluetoothDiscovery(
- {
- .device_discovered_cb = absl::bind_front(
- &P2pClusterPcpHandler::BluetoothDeviceDiscoveredHandler, this,
- client, service_id),
- .device_name_changed_cb = absl::bind_front(
- &P2pClusterPcpHandler::BluetoothNameChangedHandler, this,
- client, service_id),
- .device_lost_cb = absl::bind_front(
- &P2pClusterPcpHandler::BluetoothDeviceLostHandler, this, client,
- service_id),
- },
- client, service_id);
- if (bluetooth_medium != proto::connections::UNKNOWN_MEDIUM) {
- NEARBY_LOG(INFO, "P2pClusterPcpHandler::StartDiscoveryImpl: BT added");
- mediums_started_successfully.push_back(bluetooth_medium);
- bluetooth_classic_discoverer_client_id_ = client->GetClientId();
- }
- }
-
- if (options.allowed.ble) {
- proto::connections::Medium ble_medium = StartBleScanning(
- {
- .peripheral_discovered_cb = absl::bind_front(
- &P2pClusterPcpHandler::BlePeripheralDiscoveredHandler, this,
- client),
- .peripheral_lost_cb = absl::bind_front(
- &P2pClusterPcpHandler::BlePeripheralLostHandler, this, client),
- },
- client, service_id, options.fast_advertisement_service_uuid);
- if (ble_medium != proto::connections::UNKNOWN_MEDIUM) {
- NEARBY_LOG(INFO, "P2pClusterPcpHandler::StartDiscoveryImpl: Ble added");
- mediums_started_successfully.push_back(ble_medium);
- }
- }
-
- if (mediums_started_successfully.empty()) {
- NEARBY_LOGS(ERROR)
- << "Failed StartDiscovery() for client=" << client->GetClientId()
- << " because we couldn't scan on Bluetooth, BLE, or WifiLan for "
- "service_id="
- << service_id;
- return {
- .status = {Status::kBluetoothError},
- };
- }
-
- return {
- .status = {Status::kSuccess},
- .mediums = std::move(mediums_started_successfully),
- };
-}
-
-Status P2pClusterPcpHandler::StopDiscoveryImpl(ClientProxy* client) {
- wifi_lan_medium_.StopDiscovery(client->GetDiscoveryServiceId());
- if (client->GetClientId() == bluetooth_classic_discoverer_client_id_) {
- bluetooth_medium_.StopDiscovery();
- bluetooth_classic_discoverer_client_id_ = 0;
- } else {
- NEARBY_LOGS(INFO) << "Skipped BT StopDiscovery for client="
- << client->GetClientId()
- << ", client that started discovery is "
- << bluetooth_classic_discoverer_client_id_;
- }
-
- ble_medium_.StopScanning(client->GetDiscoveryServiceId());
- return {Status::kSuccess};
-}
-
-Status P2pClusterPcpHandler::InjectEndpointImpl(
- ClientProxy* client, const std::string& service_id,
- const OutOfBandConnectionMetadata& metadata) {
- NEARBY_LOGS(INFO) << "InjectEndpoint.";
- // Bluetooth is the only supported out-of-band connection medium.
- if (metadata.medium != Medium::BLUETOOTH) {
- NEARBY_LOGS(WARNING) << "InjectEndpointImpl: Only Bluetooth is supported.";
- return {Status::kError};
- }
-
- BluetoothDevice remote_bluetooth_device =
- injected_bluetooth_device_store_.CreateInjectedBluetoothDevice(
- metadata.remote_bluetooth_mac_address, metadata.endpoint_id,
- metadata.endpoint_info,
- GenerateHash(service_id, BluetoothDeviceName::kServiceIdHashLength),
- GetPcp());
-
- if (!remote_bluetooth_device.IsValid()) {
- NEARBY_LOG(WARNING, "InjectEndpointImpl: Invalid parameters.");
- return {Status::kError};
- }
-
- BluetoothDeviceDiscoveredHandler(client, service_id, remote_bluetooth_device);
- return {Status::kSuccess};
-}
-
-BasePcpHandler::ConnectImplResult P2pClusterPcpHandler::ConnectImpl(
- ClientProxy* client, BasePcpHandler::DiscoveredEndpoint* endpoint) {
- if (!endpoint) {
- return BasePcpHandler::ConnectImplResult{
- .status = {Status::kError},
- };
- }
- switch (endpoint->medium) {
- case proto::connections::Medium::BLUETOOTH: {
- auto* bluetooth_endpoint = down_cast<BluetoothEndpoint*>(endpoint);
- if (bluetooth_endpoint) {
- return BluetoothConnectImpl(client, bluetooth_endpoint);
- }
- break;
- }
- case proto::connections::Medium::BLE: {
- auto* ble_endpoint = down_cast<BleEndpoint*>(endpoint);
- if (ble_endpoint) {
- return BleConnectImpl(client, ble_endpoint);
- }
- break;
- }
- case proto::connections::Medium::WIFI_LAN: {
- auto* wifi_lan_endpoint = down_cast<WifiLanEndpoint*>(endpoint);
- if (wifi_lan_endpoint) {
- return WifiLanConnectImpl(client, wifi_lan_endpoint);
- }
- break;
- }
- case proto::connections::Medium::WEB_RTC: {
- break;
- }
- default:
- break;
- }
-
- return BasePcpHandler::ConnectImplResult{
- .status = {Status::kError},
- };
-}
-
-proto::connections::Medium P2pClusterPcpHandler::StartBluetoothAdvertising(
- ClientProxy* client, const std::string& service_id,
- const ByteArray& service_id_hash, const std::string& local_endpoint_id,
- const ByteArray& local_endpoint_info, WebRtcState web_rtc_state) {
- // Start listening for connections before advertising in case a connection
- // request comes in very quickly.
- NEARBY_LOG(
- INFO,
- "P2pClusterPcpHandler::StartBluetoothAdvertising: service=%s: start",
- service_id.c_str());
- if (!bluetooth_medium_.IsAcceptingConnections(service_id)) {
- if (!bluetooth_radio_.Enable() ||
- !bluetooth_medium_.StartAcceptingConnections(
- service_id, {.accepted_cb = [this, client, local_endpoint_info](
- BluetoothSocket socket) {
- if (!socket.IsValid()) {
- NEARBY_LOGS(WARNING)
- << "Invalid socket in accept callback("
- << absl::BytesToHexString(local_endpoint_info.data())
- << "), client=" << client->GetClientId();
- return;
- }
- RunOnPcpHandlerThread(
- "p2p-bt-on-incoming-connection",
- [this, client, local_endpoint_info,
- socket = std::move(socket)]()
- RUN_ON_PCP_HANDLER_THREAD() mutable {
- std::string remote_device_name =
- socket.GetRemoteDevice().GetName();
- auto channel =
- absl::make_unique<BluetoothEndpointChannel>(
- remote_device_name, socket);
- ByteArray remote_device_info{remote_device_name};
-
- OnIncomingConnection(
- client, remote_device_info, std::move(channel),
- proto::connections::Medium::BLUETOOTH);
- });
- }})) {
- NEARBY_LOGS(WARNING)
- << "In StartBluetoothAdvertising("
- << absl::BytesToHexString(local_endpoint_info.data())
- << "), client=" << client->GetClientId()
- << " failed to start listening for incoming Bluetooth "
- "connections to service_id="
- << service_id;
- return proto::connections::UNKNOWN_MEDIUM;
- }
- NEARBY_LOGS(INFO)
- << "In StartBluetoothAdvertising("
- << absl::BytesToHexString(local_endpoint_info.data())
- << "), client=" << client->GetClientId()
- << " started listening for incoming Bluetooth connections to "
- "service_id="
- << service_id;
- }
-
- // Generate a BluetoothDeviceName with which to become Bluetooth discoverable.
- // TODO(b/169550050): Implement UWBAddress.
- std::string device_name(BluetoothDeviceName(
- kBluetoothDeviceNameVersion, GetPcp(), local_endpoint_id, service_id_hash,
- local_endpoint_info, ByteArray{}, web_rtc_state));
- if (device_name.empty()) {
- NEARBY_LOGS(WARNING) << "In StartBluetoothAdvertising("
- << absl::BytesToHexString(local_endpoint_info.data())
- << "), client=" << client->GetClientId()
- << " failed to generate BluetoothDeviceName {version="
- << static_cast<int>(kBluetoothDeviceNameVersion)
- << ", pcp=" << PcpToStrategy(GetPcp()).GetName()
- << ", endpoint_id=" << local_endpoint_id
- << ", service_id_hash="
- << absl::BytesToHexString(service_id_hash.data())
- << ", endpoint_info="
- << absl::BytesToHexString(local_endpoint_info.data())
- << "}.";
- bluetooth_medium_.StopAcceptingConnections(service_id);
- return proto::connections::UNKNOWN_MEDIUM;
- }
- NEARBY_LOGS(INFO) << "In StartBluetoothAdvertising("
- << absl::BytesToHexString(local_endpoint_info.data())
- << "), client=" << client->GetClientId()
- << " generated BluetoothDeviceName " << device_name
- << " with service_id=" << service_id;
-
- // Become Bluetooth discoverable.
- if (!bluetooth_medium_.TurnOnDiscoverability(device_name)) {
- NEARBY_LOGS(INFO)
- << "In StartBluetoothAdvertising("
- << absl::BytesToHexString(local_endpoint_info.data())
- << "), client=" << client->GetClientId()
- << " couldn't start Bluetooth advertising with BluetoothDeviceName "
- << device_name;
- bluetooth_medium_.StopAcceptingConnections(service_id);
- return proto::connections::UNKNOWN_MEDIUM;
- }
- NEARBY_LOGS(INFO)
- << "In StartBluetoothAdvertising("
- << absl::BytesToHexString(local_endpoint_info.data())
- << "), client=" << client->GetClientId()
- << " started Bluetooth advertising with BluetoothDeviceName "
- << device_name;
- return proto::connections::BLUETOOTH;
-}
-
-proto::connections::Medium P2pClusterPcpHandler::StartBluetoothDiscovery(
- BluetoothDiscoveredDeviceCallback callback, ClientProxy* client,
- const std::string& service_id) {
- if (bluetooth_radio_.Enable() &&
- bluetooth_medium_.StartDiscovery(std::move(callback))) {
- NEARBY_LOGS(INFO) << "In StartBluetoothDiscovery(), client="
- << client->GetClientId()
- << " started scanning for Bluetooth for service_id="
- << service_id;
- return proto::connections::BLUETOOTH;
- } else {
- NEARBY_LOGS(INFO) << "In StartBluetoothDiscovery(), client="
- << client->GetClientId()
- << " couldn't start scanning on Bluetooth for service_id="
- << service_id;
- return proto::connections::UNKNOWN_MEDIUM;
- }
-}
-
-BasePcpHandler::ConnectImplResult P2pClusterPcpHandler::BluetoothConnectImpl(
- ClientProxy* client, BluetoothEndpoint* endpoint) {
- NEARBY_LOGS(VERBOSE) << "Client " << client->GetClientId()
- << " is attempting to connect to endpoint(id="
- << endpoint->endpoint_id << ") over Bluetooth Classic.";
- BluetoothDevice& device = endpoint->bluetooth_device;
-
- BluetoothSocket bluetooth_socket = bluetooth_medium_.Connect(
- device, endpoint->service_id,
- client->GetCancellationFlag(endpoint->endpoint_id));
- if (!bluetooth_socket.IsValid()) {
- NEARBY_LOGS(ERROR)
- << "In BluetoothConnectImpl(), failed to connect to Bluetooth device "
- << device.GetName() << " for endpoint(id=" << endpoint->endpoint_id
- << ").";
- return BasePcpHandler::ConnectImplResult{
- .status = {Status::kBluetoothError},
- };
- }
-
- auto channel = absl::make_unique<BluetoothEndpointChannel>(
- endpoint->endpoint_id, bluetooth_socket);
- NEARBY_LOGS(VERBOSE) << "Client" << client->GetClientId()
- << " created Bluetooth endpoint channel to endpoint(id="
- << endpoint->endpoint_id << ").";
- return BasePcpHandler::ConnectImplResult{
- .medium = proto::connections::Medium::BLUETOOTH,
- .status = {Status::kSuccess},
- .endpoint_channel = std::move(channel),
- };
-}
-
-proto::connections::Medium P2pClusterPcpHandler::StartBleAdvertising(
- ClientProxy* client, const std::string& service_id,
- const std::string& local_endpoint_id, const ByteArray& local_endpoint_info,
- const ConnectionOptions& options, WebRtcState web_rtc_state) {
- bool fast_advertisement = !options.fast_advertisement_service_uuid.empty();
- PowerLevel power_level =
- options.low_power ? PowerLevel::kLowPower : PowerLevel::kHighPower;
-
- // Start listening for connections before advertising in case a connection
- // request comes in very quickly. BLE allows connecting over BLE itself, as
- // well as advertising the Bluetooth MAC address to allow connecting over
- // Bluetooth Classic.
- NEARBY_LOGS(INFO) << "P2pClusterPcpHandler::StartBleAdvertising: service_id="
- << service_id << " : start";
- if (!ble_medium_.IsAcceptingConnections(service_id)) {
- if (!bluetooth_radio_.Enable() ||
- !ble_medium_.StartAcceptingConnections(
- service_id, {.accepted_cb = [this, client, local_endpoint_info](
- BleSocket socket,
- const std::string& service_id) {
- if (!socket.IsValid()) {
- NEARBY_LOGS(WARNING)
- << "Invalid socket in accept callback("
- << absl::BytesToHexString(local_endpoint_info.data())
- << "), client=" << client->GetClientId();
- return;
- }
- RunOnPcpHandlerThread(
- "p2p-ble-on-incoming-connection",
- [this, client, local_endpoint_info, service_id,
- socket = std::move(socket)]()
- RUN_ON_PCP_HANDLER_THREAD() mutable {
- std::string remote_peripheral_name =
- socket.GetRemotePeripheral().GetName();
- auto channel = absl::make_unique<BleEndpointChannel>(
- remote_peripheral_name, socket);
- ByteArray remote_peripheral_info =
- socket.GetRemotePeripheral().GetAdvertisementBytes(
- service_id);
-
- OnIncomingConnection(client, remote_peripheral_info,
- std::move(channel),
- proto::connections::Medium::BLE);
- });
- }})) {
- NEARBY_LOGS(WARNING)
- << "In StartBleAdvertising("
- << absl::BytesToHexString(local_endpoint_info.data())
- << "), client=" << client->GetClientId()
- << " failed to start accepting for incoming BLE connections to "
- "service_id="
- << service_id;
- return proto::connections::UNKNOWN_MEDIUM;
- }
- NEARBY_LOGS(INFO)
- << "In StartBleAdvertising("
- << absl::BytesToHexString(local_endpoint_info.data())
- << "), client=" << client->GetClientId()
- << " started accepting for incoming BLE connections to service_id="
- << service_id;
- }
-
- if (ShouldAdvertiseBluetoothMacOverBle(power_level) ||
- ShouldAcceptBluetoothConnections(options)) {
- if (bluetooth_medium_.IsAvailable() &&
- !bluetooth_medium_.IsAcceptingConnections(service_id)) {
- if (!bluetooth_radio_.Enable() ||
- !bluetooth_medium_.StartAcceptingConnections(
- service_id, {.accepted_cb = [this, client, local_endpoint_info](
- BluetoothSocket socket) {
- if (!socket.IsValid()) {
- NEARBY_LOGS(WARNING)
- << "In BT StartAcceptingConnections.accepted_cb("
- << absl::BytesToHexString(local_endpoint_info.data())
- << "), client=" << client->GetClientId()
- << ": Invalid socket in accept callback.";
- return;
- }
- RunOnPcpHandlerThread(
- "p2p-bt-on-incoming-connection",
- [this, client, local_endpoint_info,
- socket = std::move(socket)]()
- RUN_ON_PCP_HANDLER_THREAD() mutable {
- std::string remote_device_name =
- socket.GetRemoteDevice().GetName();
- auto channel =
- absl::make_unique<BluetoothEndpointChannel>(
- remote_device_name, socket);
- ByteArray remote_device_info{remote_device_name};
-
- OnIncomingConnection(
- client, remote_device_info, std::move(channel),
- proto::connections::Medium::BLUETOOTH);
- });
- }})) {
- NEARBY_LOGS(WARNING)
- << "In BT StartBleAdvertising("
- << absl::BytesToHexString(local_endpoint_info.data())
- << "), client=" << client->GetClientId()
- << " failed to start accepting for incoming BLE connections to "
- "service_id="
- << service_id;
- ble_medium_.StopAcceptingConnections(service_id);
- return proto::connections::UNKNOWN_MEDIUM;
- }
- NEARBY_LOGS(INFO)
- << "In BT StartBleAdvertising("
- << absl::BytesToHexString(local_endpoint_info.data())
- << "), client=" << client->GetClientId()
- << " started accepting for incoming BLE connections to service_id="
- << service_id;
- }
- }
-
- NEARBY_LOGS(INFO) << "In StartBleAdvertising("
- << absl::BytesToHexString(local_endpoint_info.data())
- << "), client=" << client->GetClientId()
- << " start to generate BleAdvertisement with service_id="
- << service_id
- << ", local endpoint_id=" << local_endpoint_id;
- // Generate a BleAdvertisement. If a fast advertisement service UUID was
- // provided, create a fast BleAdvertisement.
- ByteArray advertisement_bytes;
- // TODO(b/169550050): Implement UWBAddress.
- if (fast_advertisement) {
- advertisement_bytes = ByteArray(
- BleAdvertisement(kBleAdvertisementVersion, GetPcp(), local_endpoint_id,
- local_endpoint_info, ByteArray{}));
- } else {
- const ByteArray service_id_hash =
- GenerateHash(service_id, BleAdvertisement::kServiceIdHashLength);
- std::string bluetooth_mac_address;
- if (bluetooth_medium_.IsAvailable() &&
- ShouldAdvertiseBluetoothMacOverBle(power_level))
- bluetooth_mac_address = bluetooth_medium_.GetMacAddress();
-
- advertisement_bytes = ByteArray(
- BleAdvertisement(kBleAdvertisementVersion, GetPcp(), service_id_hash,
- local_endpoint_id, local_endpoint_info,
- bluetooth_mac_address, ByteArray{}, web_rtc_state));
- }
- if (advertisement_bytes.Empty()) {
- NEARBY_LOGS(WARNING) << "In StartBleAdvertising("
- << absl::BytesToHexString(local_endpoint_info.data())
- << "), client=" << client->GetClientId()
- << " failed to create an advertisement.",
- ble_medium_.StopAcceptingConnections(service_id);
- return proto::connections::UNKNOWN_MEDIUM;
- }
-
- NEARBY_LOGS(INFO) << "In StartBleAdvertising("
- << absl::BytesToHexString(local_endpoint_info.data())
- << "), client=" << client->GetClientId()
- << " generated BleAdvertisement with service_id="
- << service_id;
-
- if (!ble_medium_.StartAdvertising(service_id, advertisement_bytes,
- options.fast_advertisement_service_uuid)) {
- NEARBY_LOGS(WARNING)
- << "In StartBleAdvertising("
- << absl::BytesToHexString(local_endpoint_info.data())
- << "), client=" << client->GetClientId()
- << " couldn't start BLE Advertising with BleAdvertisement "
- << absl::BytesToHexString(advertisement_bytes.data());
- ble_medium_.StopAcceptingConnections(service_id);
- return proto::connections::UNKNOWN_MEDIUM;
- }
- NEARBY_LOGS(INFO) << "In startBleAdvertising("
- << absl::BytesToHexString(local_endpoint_info.data())
- << "), client=" << client->GetClientId()
- << " started BLE Advertising with BleAdvertisement "
- << absl::BytesToHexString(advertisement_bytes.data());
- return proto::connections::BLE;
-}
-
-proto::connections::Medium P2pClusterPcpHandler::StartBleScanning(
- BleDiscoveredPeripheralCallback callback, ClientProxy* client,
- const std::string& service_id,
- const std::string& fast_advertisement_service_uuid) {
- if (bluetooth_radio_.Enable() &&
- ble_medium_.StartScanning(service_id, fast_advertisement_service_uuid,
- std::move(callback))) {
- NEARBY_LOGS(INFO)
- << "In StartBleScanning(), client=" << client->GetClientId()
- << " started scanning for BLE advertisements for service_id="
- << service_id;
- return proto::connections::BLE;
- } else {
- NEARBY_LOGS(INFO) << "In StartBleScanning(), client="
- << client->GetClientId()
- << " couldn't start scanning on BLE for service_id="
- << service_id;
- return proto::connections::UNKNOWN_MEDIUM;
- }
-}
-
-BasePcpHandler::ConnectImplResult P2pClusterPcpHandler::BleConnectImpl(
- ClientProxy* client, BleEndpoint* endpoint) {
- NEARBY_LOGS(VERBOSE) << "Client " << client->GetClientId()
- << " is attempting to connect to endpoint(id="
- << endpoint->endpoint_id << ") over BLE.";
-
- BlePeripheral& peripheral = endpoint->ble_peripheral;
-
- BleSocket ble_socket =
- ble_medium_.Connect(peripheral, endpoint->service_id,
- client->GetCancellationFlag(endpoint->endpoint_id));
- if (!ble_socket.IsValid()) {
- NEARBY_LOGS(ERROR)
- << "In BleConnectImpl(), failed to connect to BLE device "
- << peripheral.GetName() << " for endpoint(id=" << endpoint->endpoint_id
- << ").";
- return BasePcpHandler::ConnectImplResult{
- .status = {Status::kBleError},
- };
- }
-
- auto channel =
- absl::make_unique<BleEndpointChannel>(endpoint->endpoint_id, ble_socket);
-
- return BasePcpHandler::ConnectImplResult{
- .medium = proto::connections::Medium::BLE,
- .status = {Status::kSuccess},
- .endpoint_channel = std::move(channel),
- };
-}
-
-proto::connections::Medium P2pClusterPcpHandler::StartWifiLanAdvertising(
- ClientProxy* client, const std::string& service_id,
- const std::string& local_endpoint_id, const ByteArray& local_endpoint_info,
- WebRtcState web_rtc_state) {
- // Start listening for connections before advertising in case a connection
- // request comes in very quickly.
- NEARBY_LOGS(INFO) << "P2pClusterPcpHandler::StartWifiLanAdvertising: service="
- << service_id << ": start";
- if (!wifi_lan_medium_.IsAcceptingConnections(service_id)) {
- if (!wifi_lan_medium_.StartAcceptingConnections(
- service_id,
- {.accepted_cb = [this, client, local_endpoint_info,
- local_endpoint_id](WifiLanSocket socket) {
- if (!socket.IsValid()) {
- NEARBY_LOGS(WARNING)
- << "Invalid socket in accept callback("
- << absl::BytesToHexString(local_endpoint_info.data())
- << "), client=" << client->GetClientId();
- return;
- }
- RunOnPcpHandlerThread(
- "p2p-wifi-on-incoming-connection",
- [this, client, local_endpoint_id, local_endpoint_info,
- socket = std::move(
- socket)]() RUN_ON_PCP_HANDLER_THREAD() mutable {
- std::string remote_service_name = local_endpoint_id;
- auto channel = absl::make_unique<WifiLanEndpointChannel>(
- remote_service_name, socket);
- ByteArray remote_service_name_byte{remote_service_name};
-
- OnIncomingConnection(client, remote_service_name_byte,
- std::move(channel),
- proto::connections::Medium::WIFI_LAN);
- });
- }})) {
- NEARBY_LOGS(WARNING)
- << "In StartWifiLanAdvertising("
- << absl::BytesToHexString(local_endpoint_info.data())
- << "), client=" << client->GetClientId()
- << " failed to start listening for incoming WifiLan connections "
- "to service_id="
- << service_id;
- return proto::connections::UNKNOWN_MEDIUM;
- }
- NEARBY_LOGS(INFO) << "In StartWifiLanAdvertising("
- << absl::BytesToHexString(local_endpoint_info.data())
- << "), client=" << client->GetClientId()
- << " started listening for incoming WifiLan connections "
- "to service_id = "
- << service_id;
- }
-
- // Generate a WifiLanServiceInfo with which to become WifiLan discoverable.
- // TODO(b/169550050): Implement UWBAddress.
- const ByteArray service_id_hash =
- GenerateHash(service_id, WifiLanServiceInfo::kServiceIdHashLength);
- WifiLanServiceInfo service_info{kWifiLanServiceInfoVersion,
- GetPcp(),
- local_endpoint_id,
- service_id_hash,
- local_endpoint_info,
- ByteArray{},
- web_rtc_state};
- NsdServiceInfo nsd_service_info(service_info);
- if (!nsd_service_info.IsValid()) {
- NEARBY_LOGS(WARNING) << "In StartWifiLanAdvertising("
- << absl::BytesToHexString(local_endpoint_info.data())
- << "), client=" << client->GetClientId()
- << " failed to generate WifiLanServiceInfo {version="
- << static_cast<int>(kWifiLanServiceInfoVersion)
- << ", pcp=" << PcpToStrategy(GetPcp()).GetName()
- << ", endpoint_id=" << local_endpoint_id
- << ", service_id_hash="
- << absl::BytesToHexString(service_id_hash.data())
- << ", endpoint_info="
- << absl::BytesToHexString(local_endpoint_info.data())
- << "}.";
- wifi_lan_medium_.StopAcceptingConnections(service_id);
- return proto::connections::UNKNOWN_MEDIUM;
- }
- NEARBY_LOGS(INFO) << "In StartWifiLanAdvertising("
- << absl::BytesToHexString(local_endpoint_info.data())
- << "), client=" << client->GetClientId()
- << " generated WifiLanServiceInfo "
- << nsd_service_info.GetServiceName()
- << " with service_id=" << service_id;
-
- if (!wifi_lan_medium_.StartAdvertising(service_id, nsd_service_info)) {
- NEARBY_LOGS(INFO) << "In StartWifiLanAdvertising("
- << absl::BytesToHexString(local_endpoint_info.data())
- << "), client=" << client->GetClientId()
- << " couldn't advertise with WifiLanServiceInfo "
- << nsd_service_info.GetServiceName();
- wifi_lan_medium_.StopAcceptingConnections(service_id);
- return proto::connections::UNKNOWN_MEDIUM;
- }
- NEARBY_LOGS(INFO) << "In StartWifiLanAdvertising("
- << absl::BytesToHexString(local_endpoint_info.data())
- << "), client=" << client->GetClientId()
- << " advertised with WifiLanServiceInfo "
- << nsd_service_info.GetServiceName();
- return proto::connections::WIFI_LAN;
-}
-
-proto::connections::Medium P2pClusterPcpHandler::StartWifiLanDiscovery(
- WifiLanDiscoveredServiceCallback callback, ClientProxy* client,
- const std::string& service_id) {
- if (wifi_lan_medium_.StartDiscovery(service_id, std::move(callback))) {
- NEARBY_LOGS(INFO) << "In StartWifiLanDiscovery(), client="
- << client->GetClientId()
- << " started scanning for Wifi devices for service_id="
- << service_id;
- return proto::connections::WIFI_LAN;
- } else {
- NEARBY_LOGS(INFO) << "In StartWifiLanDiscovery(), client="
- << client->GetClientId()
- << " couldn't start scanning on Wifi for service_id="
- << service_id;
- return proto::connections::UNKNOWN_MEDIUM;
- }
-}
-
-BasePcpHandler::ConnectImplResult P2pClusterPcpHandler::WifiLanConnectImpl(
- ClientProxy* client, WifiLanEndpoint* endpoint) {
- NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
- << " is attempting to connect to endpoint(id="
- << endpoint->endpoint_id << ") over WifiLan.";
- WifiLanSocket socket = wifi_lan_medium_.Connect(
- endpoint->service_id, endpoint->service_info,
- client->GetCancellationFlag(endpoint->endpoint_id));
- NEARBY_LOGS(ERROR) << "In WifiLanConnectImpl(), connect to service "
- << " socket=" << &socket.GetImpl()
- << " for endpoint(id=" << endpoint->endpoint_id << ").";
- if (!socket.IsValid()) {
- NEARBY_LOGS(ERROR)
- << "In WifiLanConnectImpl(), failed to connect to service "
- << endpoint->service_info.GetServiceName()
- << " for endpoint(id=" << endpoint->endpoint_id << ").";
- return BasePcpHandler::ConnectImplResult{
- .status = {Status::kWifiLanError},
- };
- }
-
- auto channel =
- absl::make_unique<WifiLanEndpointChannel>(endpoint->endpoint_id, socket);
- NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
- << " created WifiLan endpoint channel to endpoint(id="
- << endpoint->endpoint_id << ").";
- return BasePcpHandler::ConnectImplResult{
- .medium = proto::connections::Medium::WIFI_LAN,
- .status = {Status::kSuccess},
- .endpoint_channel = std::move(channel),
- };
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/p2p_cluster_pcp_handler.h b/chromium/third_party/nearby/src/cpp/core/internal/p2p_cluster_pcp_handler.h
deleted file mode 100644
index 6fe0178ba81..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/p2p_cluster_pcp_handler.h
+++ /dev/null
@@ -1,205 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_P2P_CLUSTER_PCP_HANDLER_H_
-#define CORE_INTERNAL_P2P_CLUSTER_PCP_HANDLER_H_
-
-#include <memory>
-#include <vector>
-
-#include "core/internal/base_pcp_handler.h"
-#include "core/internal/ble_advertisement.h"
-#include "core/internal/bluetooth_device_name.h"
-#include "core/internal/bwu_manager.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/endpoint_channel_manager.h"
-#include "core/internal/endpoint_manager.h"
-#include "core/internal/injected_bluetooth_device_store.h"
-#include "core/internal/mediums/bluetooth_classic.h"
-#include "core/internal/mediums/mediums.h"
-#include "core/internal/mediums/webrtc.h"
-#include "core/internal/pcp.h"
-#include "core/internal/wifi_lan_service_info.h"
-#include "core/options.h"
-#include "core/strategy.h"
-#include "platform/base/byte_array.h"
-#include "platform/public/bluetooth_classic.h"
-#include "platform/public/wifi_lan.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Concrete implementation of the PCPHandler for the P2P_CLUSTER PCP. This PCP
-// is reserved for mediums that can connect to multiple devices simultaneously
-// and all devices are considered equal. For asymmetric mediums, where one
-// device is a server and the others are clients, use P2PStarPCPHandler instead.
-//
-// Currently, this implementation advertises/discovers over Bluetooth and
-// connects over Bluetooth.
-class P2pClusterPcpHandler : public BasePcpHandler {
- public:
- P2pClusterPcpHandler(
- Mediums* mediums, EndpointManager* endpoint_manager,
- EndpointChannelManager* channel_manager, BwuManager* bwu_manager,
- InjectedBluetoothDeviceStore& injected_bluetooth_device_store,
- Pcp pcp = Pcp::kP2pCluster);
- ~P2pClusterPcpHandler() override = default;
-
- protected:
- std::vector<proto::connections::Medium> GetConnectionMediumsByPriority()
- override;
- proto::connections::Medium GetDefaultUpgradeMedium() override;
-
- // @PCPHandlerThread
- BasePcpHandler::StartOperationResult StartAdvertisingImpl(
- ClientProxy* client, const std::string& service_id,
- const std::string& local_endpoint_id,
- const ByteArray& local_endpoint_info,
- const ConnectionOptions& options) override;
-
- // @PCPHandlerThread
- Status StopAdvertisingImpl(ClientProxy* client) override;
-
- // @PCPHandlerThread
- BasePcpHandler::StartOperationResult StartDiscoveryImpl(
- ClientProxy* client, const std::string& service_id,
- const ConnectionOptions& options) override;
-
- // @PCPHandlerThread
- Status StopDiscoveryImpl(ClientProxy* client) override;
-
- // @PCPHandlerThread
- Status InjectEndpointImpl(
- ClientProxy* client, const std::string& service_id,
- const OutOfBandConnectionMetadata& metadata) override;
-
- // @PCPHandlerThread
- BasePcpHandler::ConnectImplResult ConnectImpl(
- ClientProxy* client,
- BasePcpHandler::DiscoveredEndpoint* endpoint) override;
-
- private:
- // Holds the state required to re-create a BleEndpoint we see on a
- // BlePeripheral, so BlePeripheralLostHandler can call
- // BasePcpHandler::OnEndpointLost() with the same information as was passed
- // in to BasePCPHandler::onEndpointFound().
- struct BleEndpointState {
- public:
- BleEndpointState(const string& endpoint_id, const ByteArray& endpoint_info)
- : endpoint_id(endpoint_id), endpoint_info(endpoint_info) {}
-
- std::string endpoint_id;
- ByteArray endpoint_info;
- };
-
- using BluetoothDiscoveredDeviceCallback =
- BluetoothClassic::DiscoveredDeviceCallback;
- using BleDiscoveredPeripheralCallback = Ble::DiscoveredPeripheralCallback;
- using WifiLanDiscoveredServiceCallback = WifiLan::DiscoveredServiceCallback;
-
- static constexpr BluetoothDeviceName::Version kBluetoothDeviceNameVersion =
- BluetoothDeviceName::Version::kV1;
- static constexpr BleAdvertisement::Version kBleAdvertisementVersion =
- BleAdvertisement::Version::kV1;
- static constexpr WifiLanServiceInfo::Version kWifiLanServiceInfoVersion =
- WifiLanServiceInfo::Version::kV1;
-
- static ByteArray GenerateHash(const std::string& source, size_t size);
- static bool ShouldAdvertiseBluetoothMacOverBle(PowerLevel power_level);
- static bool ShouldAcceptBluetoothConnections(
- const ConnectionOptions& options);
-
- // Bluetooth
- bool IsRecognizedBluetoothEndpoint(const std::string& name_string,
- const std::string& service_id,
- const BluetoothDeviceName& name) const;
- void BluetoothDeviceDiscoveredHandler(ClientProxy* client,
- const std::string& service_id,
- BluetoothDevice device);
- void BluetoothNameChangedHandler(ClientProxy* client,
- const std::string& service_id,
- BluetoothDevice device);
- void BluetoothDeviceLostHandler(ClientProxy* client,
- const std::string& service_id,
- BluetoothDevice& device);
- proto::connections::Medium StartBluetoothAdvertising(
- ClientProxy* client, const std::string& service_id,
- const ByteArray& service_id_hash, const std::string& local_endpoint_id,
- const ByteArray& local_endpoint_info, WebRtcState web_rtc_state);
- proto::connections::Medium StartBluetoothDiscovery(
- BluetoothDiscoveredDeviceCallback callback, ClientProxy* client,
- const std::string& service_id);
- BasePcpHandler::ConnectImplResult BluetoothConnectImpl(
- ClientProxy* client, BluetoothEndpoint* endpoint);
-
- // Ble
- // Maps a BlePeripheral to its corresponding BleEndpointState.
- absl::flat_hash_map<std::string, BleEndpointState> found_ble_endpoints_;
- bool IsRecognizedBleEndpoint(const std::string& service_id,
- const BleAdvertisement& advertisement) const;
- void BlePeripheralDiscoveredHandler(ClientProxy* client,
- BlePeripheral& peripheral,
- const std::string& service_id,
- const ByteArray& advertisement_bytes,
- bool fast_advertisement);
- void BlePeripheralLostHandler(ClientProxy* client, BlePeripheral& peripheral,
- const std::string& service_id);
- proto::connections::Medium StartBleAdvertising(
- ClientProxy* client, const std::string& service_id,
- const std::string& local_endpoint_id,
- const ByteArray& local_endpoint_info, const ConnectionOptions& options,
- WebRtcState web_rtc_state);
- proto::connections::Medium StartBleScanning(
- BleDiscoveredPeripheralCallback callback, ClientProxy* client,
- const std::string& service_id,
- const std::string& fast_advertisement_service_uuid);
- BasePcpHandler::ConnectImplResult BleConnectImpl(ClientProxy* client,
- BleEndpoint* endpoint);
-
- // WifiLan
- bool IsRecognizedWifiLanEndpoint(
- const std::string& service_id,
- const WifiLanServiceInfo& wifi_lan_service_info) const;
- void WifiLanServiceDiscoveredHandler(ClientProxy* client,
- NsdServiceInfo service_info,
- const std::string& service_id);
- void WifiLanServiceLostHandler(ClientProxy* client,
- NsdServiceInfo service_info,
- const std::string& service_id);
- proto::connections::Medium StartWifiLanAdvertising(
- ClientProxy* client, const std::string& service_id,
- const std::string& local_endpoint_id,
- const ByteArray& local_endpoint_info, WebRtcState web_rtc_state);
- proto::connections::Medium StartWifiLanDiscovery(
- WifiLanDiscoveredServiceCallback callback, ClientProxy* client,
- const std::string& service_id);
- BasePcpHandler::ConnectImplResult WifiLanConnectImpl(
- ClientProxy* client, WifiLanEndpoint* endpoint);
-
- BluetoothRadio& bluetooth_radio_;
- BluetoothClassic& bluetooth_medium_;
- Ble& ble_medium_;
- WifiLan& wifi_lan_medium_;
- mediums::WebRtc& webrtc_medium_;
- InjectedBluetoothDeviceStore& injected_bluetooth_device_store_;
- std::int64_t bluetooth_classic_discoverer_client_id_{0};
- std::int64_t bluetooth_classic_advertiser_client_id_{0};
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_P2P_CLUSTER_PCP_HANDLER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/p2p_cluster_pcp_handler_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/p2p_cluster_pcp_handler_test.cc
deleted file mode 100644
index 526cee6648a..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/p2p_cluster_pcp_handler_test.cc
+++ /dev/null
@@ -1,259 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/p2p_cluster_pcp_handler.h"
-
-#include <memory>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/time/time.h"
-#include "core/internal/bwu_manager.h"
-#include "core/internal/injected_bluetooth_device_store.h"
-#include "core/options.h"
-#include "platform/base/medium_environment.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-
-constexpr BooleanMediumSelector kTestCases[] = {
- BooleanMediumSelector{
- .bluetooth = true,
- },
- BooleanMediumSelector{
- .wifi_lan = true,
- },
- BooleanMediumSelector{
- .bluetooth = true,
- .wifi_lan = true,
- },
-};
-
-class P2pClusterPcpHandlerTest
- : public ::testing::TestWithParam<BooleanMediumSelector> {
- protected:
- void SetUp() override {
- NEARBY_LOG(INFO, "SetUp: begin");
- env_.Stop();
- if (options_.allowed.bluetooth) {
- NEARBY_LOG(INFO, "SetUp: BT enabled");
- }
- if (options_.allowed.wifi_lan) {
- NEARBY_LOG(INFO, "SetUp: WifiLan enabled");
- }
- if (options_.allowed.web_rtc) {
- NEARBY_LOG(INFO, "SetUp: WebRTC enabled");
- }
- NEARBY_LOG(INFO, "SetUp: end");
- }
-
- ClientProxy client_a_;
- ClientProxy client_b_;
- std::string service_id_{"service"};
- ConnectionOptions options_{
- .strategy = Strategy::kP2pCluster,
- .allowed = GetParam(),
- };
- MediumEnvironment& env_{MediumEnvironment::Instance()};
-};
-
-TEST_P(P2pClusterPcpHandlerTest, CanConstructOne) {
- env_.Start();
- Mediums mediums;
- EndpointChannelManager ecm;
- EndpointManager em(&ecm);
- BwuManager bwu(mediums, em, ecm, {}, {});
- InjectedBluetoothDeviceStore ibds;
- P2pClusterPcpHandler handler(&mediums, &em, &ecm, &bwu, ibds);
- env_.Stop();
-}
-
-TEST_P(P2pClusterPcpHandlerTest, CanConstructMultiple) {
- env_.Start();
- Mediums mediums_a;
- Mediums mediums_b;
- EndpointChannelManager ecm_a;
- EndpointChannelManager ecm_b;
- EndpointManager em_a(&ecm_a);
- EndpointManager em_b(&ecm_b);
- BwuManager bwu_a(mediums_a, em_a, ecm_a, {}, {});
- BwuManager bwu_b(mediums_b, em_b, ecm_b, {}, {});
- InjectedBluetoothDeviceStore ibds_a;
- InjectedBluetoothDeviceStore ibds_b;
- P2pClusterPcpHandler handler_a(&mediums_a, &em_a, &ecm_a, &bwu_a, ibds_a);
- P2pClusterPcpHandler handler_b(&mediums_b, &em_b, &ecm_b, &bwu_b, ibds_b);
- env_.Stop();
-}
-
-TEST_P(P2pClusterPcpHandlerTest, CanAdvertise) {
- env_.Start();
- std::string endpoint_name{"endpoint_name"};
- Mediums mediums_a;
- EndpointChannelManager ecm_a;
- EndpointManager em_a(&ecm_a);
- BwuManager bwu_a(mediums_a, em_a, ecm_a, {}, {});
- InjectedBluetoothDeviceStore ibds_a;
- P2pClusterPcpHandler handler_a(&mediums_a, &em_a, &ecm_a, &bwu_a, ibds_a);
- EXPECT_EQ(
- handler_a.StartAdvertising(&client_a_, service_id_, options_,
- {.endpoint_info = ByteArray{endpoint_name}}),
- Status{Status::kSuccess});
- env_.Stop();
-}
-
-TEST_P(P2pClusterPcpHandlerTest, CanDiscover) {
- env_.Start();
- std::string endpoint_name{"endpoint_name"};
- Mediums mediums_a;
- Mediums mediums_b;
- EndpointChannelManager ecm_a;
- EndpointChannelManager ecm_b;
- EndpointManager em_a(&ecm_a);
- EndpointManager em_b(&ecm_b);
- BwuManager bwu_a(mediums_a, em_a, ecm_a, {}, {});
- BwuManager bwu_b(mediums_b, em_b, ecm_b, {}, {});
- InjectedBluetoothDeviceStore ibds_a;
- InjectedBluetoothDeviceStore ibds_b;
- P2pClusterPcpHandler handler_a(&mediums_a, &em_a, &ecm_a, &bwu_a, ibds_a);
- P2pClusterPcpHandler handler_b(&mediums_b, &em_b, &ecm_b, &bwu_b, ibds_b);
- CountDownLatch latch(1);
- EXPECT_EQ(
- handler_a.StartAdvertising(&client_a_, service_id_, options_,
- {.endpoint_info = ByteArray{endpoint_name}}),
- Status{Status::kSuccess});
- EXPECT_EQ(handler_b.StartDiscovery(
- &client_b_, service_id_, options_,
- {
- .endpoint_found_cb =
- [&latch](const std::string& endpoint_id,
- const ByteArray& endpoint_info,
- const std::string& service_id) {
- NEARBY_LOG(INFO, "Device discovered: id=%s",
- endpoint_id.c_str());
- latch.CountDown();
- },
- }),
- Status{Status::kSuccess});
- EXPECT_TRUE(latch.Await(absl::Milliseconds(1000)).result());
- // We discovered endpoint over one medium. Before we finish the test, we have
- // to stop discovery for other mediums that may be still ongoing.
- handler_b.StopDiscovery(&client_b_);
- env_.Stop();
-}
-
-TEST_P(P2pClusterPcpHandlerTest, CanConnect) {
- env_.Start();
- std::string endpoint_name_a{"endpoint_name"};
- Mediums mediums_a;
- Mediums mediums_b;
- BluetoothRadio& radio_a = mediums_a.GetBluetoothRadio();
- BluetoothRadio& radio_b = mediums_b.GetBluetoothRadio();
- radio_a.GetBluetoothAdapter().SetName("BT Device A");
- radio_b.GetBluetoothAdapter().SetName("BT Device B");
- EndpointChannelManager ecm_a;
- EndpointChannelManager ecm_b;
- EndpointManager em_a(&ecm_a);
- EndpointManager em_b(&ecm_b);
- BwuManager bwu_a(mediums_a, em_a, ecm_a, {},
- {.allow_upgrade_to = {.bluetooth = true}});
- BwuManager bwu_b(mediums_b, em_b, ecm_b, {},
- {.allow_upgrade_to = {.bluetooth = true}});
- InjectedBluetoothDeviceStore ibds_a;
- InjectedBluetoothDeviceStore ibds_b;
- P2pClusterPcpHandler handler_a(&mediums_a, &em_a, &ecm_a, &bwu_a, ibds_a);
- P2pClusterPcpHandler handler_b(&mediums_b, &em_b, &ecm_b, &bwu_b, ibds_b);
- CountDownLatch discover_latch(1);
- CountDownLatch connect_latch(2);
- struct DiscoveredInfo {
- std::string endpoint_id;
- ByteArray endpoint_info;
- std::string service_id;
- } discovered;
- EXPECT_EQ(
- handler_a.StartAdvertising(
- &client_a_, service_id_, options_,
- {
- .endpoint_info = ByteArray{endpoint_name_a},
- .listener =
- {
- .initiated_cb =
- [&connect_latch](const std::string& endpoint_id,
- const ConnectionResponseInfo& info) {
- NEARBY_LOG(INFO,
- "StartAdvertising: initiated_cb called");
- connect_latch.CountDown();
- },
- },
- }),
- Status{Status::kSuccess});
- EXPECT_EQ(handler_b.StartDiscovery(
- &client_b_, service_id_, options_,
- {
- .endpoint_found_cb =
- [&discover_latch, &discovered](
- const std::string& endpoint_id,
- const ByteArray& endpoint_info,
- const std::string& service_id) {
- NEARBY_LOG(
- INFO,
- "Device discovered: id=%s, endpoint_info=%s",
- endpoint_id.c_str(),
- std::string{endpoint_info}.c_str());
- discovered = {
- .endpoint_id = endpoint_id,
- .endpoint_info = endpoint_info,
- .service_id = service_id,
- };
- discover_latch.CountDown();
- },
- }),
- Status{Status::kSuccess});
-
- EXPECT_TRUE(discover_latch.Await(absl::Milliseconds(1000)).result());
- EXPECT_EQ(endpoint_name_a, std::string{discovered.endpoint_info});
-
- client_b_.AddCancellationFlag(discovered.endpoint_id);
- handler_b.RequestConnection(
- &client_b_, discovered.endpoint_id,
- {
- .endpoint_info = discovered.endpoint_info,
- .listener =
- {
- .initiated_cb =
- [&connect_latch](const std::string& endpoint_id,
- const ConnectionResponseInfo& info) {
- NEARBY_LOG(INFO,
- "RequestConnection: initiated_cb called");
- connect_latch.CountDown();
- },
- },
- },
- options_);
- EXPECT_TRUE(connect_latch.Await(absl::Milliseconds(1000)).result());
- bwu_a.Shutdown();
- bwu_b.Shutdown();
- env_.Stop();
-}
-
-INSTANTIATE_TEST_SUITE_P(ParametrisedPcpHandlerTest, P2pClusterPcpHandlerTest,
- ::testing::ValuesIn(kTestCases));
-
-} // namespace
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/p2p_point_to_point_pcp_handler.cc b/chromium/third_party/nearby/src/cpp/core/internal/p2p_point_to_point_pcp_handler.cc
deleted file mode 100644
index 2ac80e78226..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/p2p_point_to_point_pcp_handler.cc
+++ /dev/null
@@ -1,64 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/p2p_point_to_point_pcp_handler.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-P2pPointToPointPcpHandler::P2pPointToPointPcpHandler(
- Mediums& mediums, EndpointManager& endpoint_manager,
- EndpointChannelManager& channel_manager, BwuManager& bwu_manager,
- InjectedBluetoothDeviceStore& injected_bluetooth_device_store, Pcp pcp)
- : P2pStarPcpHandler(mediums, endpoint_manager, channel_manager, bwu_manager,
- injected_bluetooth_device_store, pcp) {}
-
-std::vector<proto::connections::Medium>
-P2pPointToPointPcpHandler::GetConnectionMediumsByPriority() {
- std::vector<proto::connections::Medium> mediums;
- if (mediums_->GetWifiLan().IsAvailable()) {
- mediums.push_back(proto::connections::WIFI_LAN);
- }
- if (mediums_->GetWebRtc().IsAvailable()) {
- mediums.push_back(proto::connections::WEB_RTC);
- }
- if (mediums_->GetBluetoothClassic().IsAvailable()) {
- mediums.push_back(proto::connections::BLUETOOTH);
- }
- if (mediums_->GetBle().IsAvailable()) {
- mediums.push_back(proto::connections::BLE);
- }
- return mediums;
-}
-
-bool P2pPointToPointPcpHandler::CanSendOutgoingConnection(
- ClientProxy* client) const {
- // For point to point, we can only send an outgoing connection while we have
- // no other connections.
- return !this->HasOutgoingConnections(client) &&
- !this->HasIncomingConnections(client);
-}
-
-bool P2pPointToPointPcpHandler::CanReceiveIncomingConnection(
- ClientProxy* client) const {
- // For point to point, we can only receive an incoming connection while we
- // have no other connections.
- return !this->HasOutgoingConnections(client) &&
- !this->HasIncomingConnections(client);
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/p2p_point_to_point_pcp_handler.h b/chromium/third_party/nearby/src/cpp/core/internal/p2p_point_to_point_pcp_handler.h
deleted file mode 100644
index fa6ac46c218..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/p2p_point_to_point_pcp_handler.h
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_P2P_POINT_TO_POINT_PCP_HANDLER_H_
-#define CORE_INTERNAL_P2P_POINT_TO_POINT_PCP_HANDLER_H_
-
-#include "core/internal/endpoint_channel_manager.h"
-#include "core/internal/endpoint_manager.h"
-#include "core/internal/p2p_star_pcp_handler.h"
-#include "core/internal/pcp.h"
-#include "core/strategy.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Concrete implementation of the PCPHandler for the P2P_POINT_TO_POINT. This
-// PCP is for mediums that have limitations on the number of simultaneous
-// connections; all mediums in P2P_STAR are valid for P2P_POINT_TO_POINT, but
-// not all mediums in P2P_POINT_TO_POINT are valid for P2P_STAR.
-//
-// Currently, this implementation advertises/discovers over Bluetooth
-// and connects over Bluetooth.
-class P2pPointToPointPcpHandler : public P2pStarPcpHandler {
- public:
- P2pPointToPointPcpHandler(
- Mediums& mediums, EndpointManager& endpoint_manager,
- EndpointChannelManager& channel_manager, BwuManager& bwu_manager,
- InjectedBluetoothDeviceStore& injected_bluetooth_device_store,
- Pcp pcp = Pcp::kP2pPointToPoint);
-
- protected:
- std::vector<proto::connections::Medium> GetConnectionMediumsByPriority()
- override;
-
- bool CanSendOutgoingConnection(ClientProxy* client) const override;
- bool CanReceiveIncomingConnection(ClientProxy* client) const override;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_P2P_POINT_TO_POINT_PCP_HANDLER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/p2p_star_pcp_handler.cc b/chromium/third_party/nearby/src/cpp/core/internal/p2p_star_pcp_handler.cc
deleted file mode 100644
index c870ffa0228..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/p2p_star_pcp_handler.cc
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/p2p_star_pcp_handler.h"
-
-#include <vector>
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-P2pStarPcpHandler::P2pStarPcpHandler(
- Mediums& mediums, EndpointManager& endpoint_manager,
- EndpointChannelManager& channel_manager, BwuManager& bwu_manager,
- InjectedBluetoothDeviceStore& injected_bluetooth_device_store, Pcp pcp)
- : P2pClusterPcpHandler(&mediums, &endpoint_manager, &channel_manager,
- &bwu_manager, injected_bluetooth_device_store, pcp) {
-}
-
-std::vector<proto::connections::Medium>
-P2pStarPcpHandler::GetConnectionMediumsByPriority() {
- std::vector<proto::connections::Medium> mediums;
- if (mediums_->GetWifiLan().IsAvailable()) {
- mediums.push_back(proto::connections::WIFI_LAN);
- }
- if (mediums_->GetWebRtc().IsAvailable()) {
- mediums.push_back(proto::connections::WEB_RTC);
- }
- if (mediums_->GetBluetoothClassic().IsAvailable()) {
- mediums.push_back(proto::connections::BLUETOOTH);
- }
- if (mediums_->GetBle().IsAvailable()) {
- mediums.push_back(proto::connections::BLE);
- }
- return mediums;
-}
-
-proto::connections::Medium P2pStarPcpHandler::GetDefaultUpgradeMedium() {
- return proto::connections::Medium::WIFI_HOTSPOT;
-}
-
-bool P2pStarPcpHandler::CanSendOutgoingConnection(ClientProxy* client) const {
- // For star, we can only send an outgoing connection while we have no other
- // connections.
- return !this->HasOutgoingConnections(client) &&
- !this->HasIncomingConnections(client);
-}
-
-bool P2pStarPcpHandler::CanReceiveIncomingConnection(
- ClientProxy* client) const {
- // For star, we can only receive an incoming connection if we've sent no
- // outgoing connections.
- return !this->HasOutgoingConnections(client);
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/p2p_star_pcp_handler.h b/chromium/third_party/nearby/src/cpp/core/internal/p2p_star_pcp_handler.h
deleted file mode 100644
index cc01c717c12..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/p2p_star_pcp_handler.h
+++ /dev/null
@@ -1,59 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_P2P_STAR_PCP_HANDLER_H_
-#define CORE_INTERNAL_P2P_STAR_PCP_HANDLER_H_
-
-#include <vector>
-
-#include "core/internal/client_proxy.h"
-#include "core/internal/endpoint_channel_manager.h"
-#include "core/internal/endpoint_manager.h"
-#include "core/internal/p2p_cluster_pcp_handler.h"
-#include "core/internal/pcp.h"
-#include "core/strategy.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Concrete implementation of the PcpHandler for the P2P_STAR PCP. This Pcp is
-// for mediums that have one server with (potentially) many clients; all mediums
-// in P2P_CLUSTER are valid for P2P_STAR, but not all mediums in P2P_STAR are
-// valid for P2P_CLUSTER.
-//
-// Currently, this implementation advertises/discovers over Bluetooth
-// and connects over Bluetooth.
-class P2pStarPcpHandler : public P2pClusterPcpHandler {
- public:
- P2pStarPcpHandler(
- Mediums& mediums, EndpointManager& endpoint_manager,
- EndpointChannelManager& channel_manager, BwuManager& bwu_manager,
- InjectedBluetoothDeviceStore& injected_bluetooth_device_store,
- Pcp pcp = Pcp::kP2pStar);
-
- protected:
- std::vector<proto::connections::Medium> GetConnectionMediumsByPriority()
- override;
- proto::connections::Medium GetDefaultUpgradeMedium() override;
-
- bool CanSendOutgoingConnection(ClientProxy* client) const override;
- bool CanReceiveIncomingConnection(ClientProxy* client) const override;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_P2P_STAR_PCP_HANDLER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/payload_manager.cc b/chromium/third_party/nearby/src/cpp/core/internal/payload_manager.cc
deleted file mode 100644
index 403be7e0445..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/payload_manager.cc
+++ /dev/null
@@ -1,1318 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/payload_manager.h"
-
-#include <algorithm>
-#include <limits>
-#include <memory>
-#include <string>
-#include <utility>
-
-#include "absl/memory/memory.h"
-#include "absl/strings/str_cat.h"
-#include "absl/time/time.h"
-#include "core/internal/internal_payload_factory.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/mutex_lock.h"
-#include "platform/public/single_thread_executor.h"
-#include "platform/public/system_clock.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// C++14 requires to declare this.
-// TODO(apolyudov): remove when migration to c++17 is possible.
-constexpr const absl::Duration PayloadManager::kWaitCloseTimeout;
-
-bool PayloadManager::SendPayloadLoop(
- ClientProxy* client, PendingPayload& pending_payload,
- PayloadTransferFrame::PayloadHeader& payload_header,
- std::int64_t& next_chunk_offset, size_t resume_offset) {
- // in lieu of structured binding:
- auto pair = GetAvailableAndUnavailableEndpoints(pending_payload);
- const EndpointIds& available_endpoint_ids =
- EndpointsToEndpointIds(pair.first);
- const Endpoints& unavailable_endpoints = pair.second;
-
- // First, handle any non-available endpoints.
- for (const auto& endpoint : unavailable_endpoints) {
- HandleFinishedOutgoingPayload(
- client, {endpoint->id}, payload_header, next_chunk_offset,
- EndpointInfoStatusToPayloadStatus(endpoint->status.Get()));
- }
-
- // Update the still-active recipients of this payload.
- if (available_endpoint_ids.empty()) {
- NEARBY_LOGS(INFO)
- << "PayloadManager short-circuiting payload_id="
- << pending_payload.GetInternalPayload()->GetId() << " after sending "
- << next_chunk_offset
- << " bytes because none of the endpoints are available anymore.";
- return false;
- }
-
- // Check if the payload has been cancelled by the client and, if so,
- // notify the remaining recipients.
- if (pending_payload.IsLocallyCanceled()) {
- NEARBY_LOGS(INFO) << "Aborting send of payload_id="
- << pending_payload.GetInternalPayload()->GetId()
- << " at offset " << next_chunk_offset
- << " since it is marked canceled.";
- HandleFinishedOutgoingPayload(
- client, available_endpoint_ids, payload_header, next_chunk_offset,
- proto::connections::PayloadStatus::LOCAL_CANCELLATION);
- return false;
- }
-
- // Update the current offsets for all endpoints still active for this
- // payload. For the sake of accuracy, we update the pending payload here
- // because it's after all payload terminating events are handled, but
- // right before we actually start detaching the next chunk.
- if (next_chunk_offset == 0 && resume_offset > 0) {
- ExceptionOr<size_t> real_offset =
- pending_payload.GetInternalPayload()->SkipToOffset(resume_offset);
- if (!real_offset.ok()) {
- // Stop sending since it may cause remote file merging failed.
- NEARBY_LOGS(WARNING) << "PayloadManager failed to skip offset "
- << resume_offset << " on payload_id "
- << pending_payload.GetInternalPayload()->GetId();
- HandleFinishedOutgoingPayload(
- client, available_endpoint_ids, payload_header, next_chunk_offset,
- proto::connections::PayloadStatus::LOCAL_ERROR);
- return false;
- }
- NEARBY_LOGS(VERBOSE) << "PayloadManager successfully skipped "
- << real_offset.GetResult() << " bytes on payload_id "
- << pending_payload.GetInternalPayload()->GetId();
- next_chunk_offset = real_offset.GetResult();
- }
- for (const auto& endpoint_id : available_endpoint_ids) {
- pending_payload.SetOffsetForEndpoint(endpoint_id, next_chunk_offset);
- }
-
- // This will block if there is no data to transfer.
- // It will resume when new data arrives, or if Close() is called.
- int chunk_size = GetOptimalChunkSize(available_endpoint_ids);
- ByteArray next_chunk =
- pending_payload.GetInternalPayload()->DetachNextChunk(chunk_size);
- if (shutdown_.Get()) return false;
- // Save chunk size. We'll need it after we move next_chunk.
- auto next_chunk_size = next_chunk.size();
- if (!next_chunk_size &&
- pending_payload.GetInternalPayload()->GetTotalSize() > 0 &&
- pending_payload.GetInternalPayload()->GetTotalSize() <
- next_chunk_offset) {
- NEARBY_LOGS(INFO) << "Payload xfer failed: payload_id="
- << pending_payload.GetInternalPayload()->GetId();
- HandleFinishedOutgoingPayload(
- client, available_endpoint_ids, payload_header, next_chunk_offset,
- proto::connections::PayloadStatus::LOCAL_ERROR);
- return false;
- }
-
- // Only need to handle outgoing data chunk offset, because the offset will be
- // used to decide if the received chunk is the initial payload chunk.
- // In other cases, the offset should only be used in both side logs when error
- // happened.
- PayloadTransferFrame::PayloadChunk payload_chunk(CreatePayloadChunk(
- next_chunk_offset - resume_offset, std::move(next_chunk)));
- const EndpointIds& failed_endpoint_ids = endpoint_manager_->SendPayloadChunk(
- payload_header, payload_chunk, available_endpoint_ids);
- // Check whether at least one endpoint failed.
- if (!failed_endpoint_ids.empty()) {
- NEARBY_LOGS(INFO) << "Payload xfer: endpoints failed: payload_id="
- << payload_header.id() << "; endpoint_ids={"
- << ToString(failed_endpoint_ids) << "}",
- HandleFinishedOutgoingPayload(
- client, failed_endpoint_ids, payload_header, next_chunk_offset,
- proto::connections::PayloadStatus::ENDPOINT_IO_ERROR);
- }
-
- // Check whether at least one endpoint succeeded -- if they all failed,
- // we'll just go right back to the top of the loop and break out when
- // availableEndpointIds is re-synced and found to be empty at that point.
- if (failed_endpoint_ids.size() < available_endpoint_ids.size()) {
- for (const auto& endpoint_id : available_endpoint_ids) {
- if (std::find(failed_endpoint_ids.begin(), failed_endpoint_ids.end(),
- endpoint_id) == failed_endpoint_ids.end()) {
- HandleSuccessfulOutgoingChunk(
- client, endpoint_id, payload_header, payload_chunk.flags(),
- payload_chunk.offset(), payload_chunk.body().size());
- }
- }
- NEARBY_LOGS(VERBOSE) << "PayloadManager done sending chunk at offset "
- << next_chunk_offset << " of payload_id="
- << pending_payload.GetInternalPayload()->GetId();
- next_chunk_offset += next_chunk_size;
-
- if (!next_chunk_size) {
- // That was the last chunk, we're outta here.
- NEARBY_LOGS(INFO) << "Payload xfer done: payload_id="
- << pending_payload.GetInternalPayload()->GetId()
- << "; size=" << next_chunk_offset;
- return false;
- }
- }
-
- return true;
-}
-
-std::pair<PayloadManager::Endpoints, PayloadManager::Endpoints>
-PayloadManager::GetAvailableAndUnavailableEndpoints(
- const PendingPayload& pending_payload) {
- Endpoints available;
- Endpoints unavailable;
- for (auto* endpoint_info : pending_payload.GetEndpoints()) {
- if (endpoint_info->status.Get() ==
- PayloadManager::EndpointInfo::Status::kAvailable) {
- available.push_back(endpoint_info);
- } else {
- unavailable.push_back(endpoint_info);
- }
- }
- return std::make_pair(std::move(available), std::move(unavailable));
-}
-
-PayloadManager::EndpointIds PayloadManager::EndpointsToEndpointIds(
- const Endpoints& endpoints) {
- EndpointIds endpoint_ids;
- endpoint_ids.reserve(endpoints.size());
- for (const auto& item : endpoints) {
- if (item) {
- endpoint_ids.emplace_back(item->id);
- }
- }
- return endpoint_ids;
-}
-
-std::string PayloadManager::ToString(const Endpoints& endpoints) {
- std::string endpoints_string = absl::StrCat(endpoints.size(), ": ");
- bool first = true;
- for (const auto& item : endpoints) {
- if (first) {
- absl::StrAppend(&endpoints_string, item->id);
- first = false;
- } else {
- absl::StrAppend(&endpoints_string, ", ", item->id);
- }
- }
- return endpoints_string;
-}
-
-std::string PayloadManager::ToString(const EndpointIds& endpoint_ids) {
- std::string endpoints_string = absl::StrCat(endpoint_ids.size(), ": ");
- bool first = true;
- for (const auto& id : endpoint_ids) {
- if (first) {
- absl::StrAppend(&endpoints_string, id);
- first = false;
- } else {
- absl::StrAppend(&endpoints_string, ", ", id);
- }
- }
- return endpoints_string;
-}
-
-std::string PayloadManager::ToString(Payload::Type type) {
- switch (type) {
- case Payload::Type::kBytes:
- return std::string("Bytes");
- case Payload::Type::kStream:
- return std::string("Stream");
- case Payload::Type::kFile:
- return std::string("File");
- case Payload::Type::kUnknown:
- return std::string("Unknown");
- }
-}
-
-std::string PayloadManager::ToString(EndpointInfo::Status status) {
- switch (status) {
- case EndpointInfo::Status::kAvailable:
- return std::string("Available");
- case EndpointInfo::Status::kCanceled:
- return std::string("Cancelled");
- case EndpointInfo::Status::kError:
- return std::string("Error");
- case EndpointInfo::Status::kUnknown:
- return std::string("Unknown");
- }
-}
-
-// Creates and starts tracking a PendingPayload for this Payload.
-Payload::Id PayloadManager::CreateOutgoingPayload(
- Payload payload, const EndpointIds& endpoint_ids) {
- auto internal_payload{CreateOutgoingInternalPayload(std::move(payload))};
- Payload::Id payload_id = internal_payload->GetId();
- NEARBY_LOGS(INFO) << "CreateOutgoingPayload: payload_id=" << payload_id;
- MutexLock lock(&mutex_);
- pending_payloads_.StartTrackingPayload(
- payload_id, absl::make_unique<PendingPayload>(std::move(internal_payload),
- endpoint_ids,
- /*is_incoming=*/false));
-
- return payload_id;
-}
-
-PayloadManager::PayloadManager(EndpointManager& endpoint_manager)
- : endpoint_manager_(&endpoint_manager) {
- endpoint_manager_->RegisterFrameProcessor(V1Frame::PAYLOAD_TRANSFER, this);
-}
-
-void PayloadManager::CancelAllPayloads() {
- NEARBY_LOG(INFO, "PayloadManager: canceling payloads; self=%p", this);
- {
- MutexLock lock(&mutex_);
- int pending_outgoing_payloads = 0;
- for (const auto& pending_id : pending_payloads_.GetAllPayloads()) {
- auto* pending = pending_payloads_.GetPayload(pending_id);
- if (!pending->IsIncoming()) pending_outgoing_payloads++;
- pending->MarkLocallyCanceled();
- pending->Close(); // To unblock the sender thread, if there is no data.
- }
- if (pending_outgoing_payloads) {
- shutdown_barrier_ =
- absl::make_unique<CountDownLatch>(pending_outgoing_payloads);
- }
- }
-
- if (shutdown_barrier_) {
- NEARBY_LOG(INFO,
- "PayloadManager: waiting for pending outgoing payloads; self=%p",
- this);
- shutdown_barrier_->Await();
- }
-}
-
-void PayloadManager::DisconnectFromEndpointManager() {
- if (shutdown_.Set(true)) return;
- // Unregister ourselves from the FrameProcessors.
- endpoint_manager_->UnregisterFrameProcessor(V1Frame::PAYLOAD_TRANSFER, this);
-}
-
-PayloadManager::~PayloadManager() {
- NEARBY_LOG(INFO, "PayloadManager: going down; self=%p", this);
- DisconnectFromEndpointManager();
- CancelAllPayloads();
- NEARBY_LOG(INFO, "PayloadManager: turn down payload executors; self=%p",
- this);
- bytes_payload_executor_.Shutdown();
- stream_payload_executor_.Shutdown();
- file_payload_executor_.Shutdown();
-
- CountDownLatch stop_latch(1);
- // Clear our tracked pending payloads.
- RunOnStatusUpdateThread(
- "~payload-manager",
- [this, &stop_latch]() RUN_ON_PAYLOAD_STATUS_UPDATE_THREAD() {
- NEARBY_LOG(INFO, "PayloadManager: stop tracking payloads; self=%p",
- this);
- MutexLock lock(&mutex_);
- for (const auto& pending_id : pending_payloads_.GetAllPayloads()) {
- pending_payloads_.StopTrackingPayload(pending_id);
- }
- stop_latch.CountDown();
- });
- stop_latch.Await();
-
- NEARBY_LOG(INFO, "PayloadManager: turn down notification executor; self=%p",
- this);
- // Stop all the ongoing Runnables (as gracefully as possible).
- payload_status_update_executor_.Shutdown();
-
- NEARBY_LOG(INFO, "PayloadManager: down; self=%p", this);
-}
-
-bool PayloadManager::NotifyShutdown() {
- MutexLock lock(&mutex_);
- if (!shutdown_.Get()) return false;
- if (!shutdown_barrier_) return false;
- NEARBY_LOG(INFO, "PayloadManager [shutdown mode]");
- shutdown_barrier_->CountDown();
- return true;
-}
-
-void PayloadManager::SendPayload(ClientProxy* client,
- const EndpointIds& endpoint_ids,
- Payload payload) {
- if (shutdown_.Get()) return;
- NEARBY_LOG(INFO, "SendPayload: endpoint_ids={%s}",
- ToString(endpoint_ids).c_str());
- // Before transfer to internal payload, retrieves the Payload size for
- // analytics.
- std::int64_t payload_total_size;
- switch (payload.GetType()) {
- case connections::Payload::Type::kBytes:
- payload_total_size = payload.AsBytes().size();
- break;
- case connections::Payload::Type::kFile:
- payload_total_size = payload.AsFile()->GetTotalSize();
- break;
- case connections::Payload::Type::kStream:
- case connections::Payload::Type::kUnknown:
- payload_total_size = -1;
- break;
- }
-
- auto executor = GetOutgoingPayloadExecutor(payload.GetType());
- // The |executor| will be null if the payload is of a type we cannot work
- // with. This should never be reached since the ServiceControllerRouter has
- // already checked whether or not we can work with this Payload type.
- if (!executor) {
- RecordInvalidPayloadAnalytics(client, endpoint_ids, payload.GetId(),
- payload.GetType(), payload.GetOffset(),
- payload_total_size);
- NEARBY_LOGS(INFO)
- << "PayloadManager failed to determine the right executor for "
- "outgoing payload_id="
- << payload.GetId() << ", payload_type=" << ToString(payload.GetType());
- return;
- }
-
- // Each payload is sent in FCFS order within each Payload type, blocking any
- // other payload of the same type from even starting until this one is
- // completely done with. If we ever want to provide isolation across
- // ClientProxy objects this will need to be significantly re-architected.
- Payload::Type payload_type = payload.GetType();
- size_t resume_offset =
- FeatureFlags::GetInstance().GetFlags().enable_send_payload_offset
- ? payload.GetOffset()
- : 0;
-
- Payload::Id payload_id =
- CreateOutgoingPayload(std::move(payload), endpoint_ids);
- executor->Execute(
- "send-payload", [this, client, endpoint_ids, payload_id, payload_type,
- resume_offset, payload_total_size]() {
- if (shutdown_.Get()) return;
- PendingPayload* pending_payload = GetPayload(payload_id);
- if (!pending_payload) {
- RecordInvalidPayloadAnalytics(client, endpoint_ids, payload_id,
- payload_type, resume_offset,
- payload_total_size);
- NEARBY_LOGS(INFO)
- << "PayloadManager failed to create InternalPayload for outgoing "
- "payload_id="
- << payload_id << ", payload_type=" << ToString(payload_type)
- << ", aborting sendPayload().";
- return;
- }
- auto* internal_payload = pending_payload->GetInternalPayload();
- if (!internal_payload) return;
-
- RecordPayloadStartedAnalytics(client, endpoint_ids, payload_id,
- payload_type, resume_offset,
- internal_payload->GetTotalSize());
-
- PayloadTransferFrame::PayloadHeader payload_header{
- CreatePayloadHeader(*internal_payload, resume_offset)};
- bool should_continue = true;
- std::int64_t next_chunk_offset = 0;
- while (should_continue && !shutdown_.Get()) {
- should_continue =
- SendPayloadLoop(client, *pending_payload, payload_header,
- next_chunk_offset, resume_offset);
- }
- RunOnStatusUpdateThread("destroy-payload",
- [this, payload_id]()
- RUN_ON_PAYLOAD_STATUS_UPDATE_THREAD() {
- DestroyPendingPayload(payload_id);
- });
- });
- NEARBY_LOGS(INFO) << "PayloadManager: xfer scheduled: self=" << this
- << "; payload_id=" << payload_id
- << ", payload_type=" << ToString(payload_type);
-}
-
-PayloadManager::PendingPayload* PayloadManager::GetPayload(
- Payload::Id payload_id) const {
- MutexLock lock(&mutex_);
- return pending_payloads_.GetPayload(payload_id);
-}
-
-Status PayloadManager::CancelPayload(ClientProxy* client,
- Payload::Id payload_id) {
- PendingPayload* canceled_payload = GetPayload(payload_id);
- if (!canceled_payload) {
- NEARBY_LOGS(INFO) << "Client requested cancel for unknown payload_id="
- << payload_id << ", ignoring.";
- return {Status::kPayloadUnknown};
- }
-
- // Mark the payload as canceled.
- canceled_payload->MarkLocallyCanceled();
- NEARBY_LOGS(INFO) << "Cancelling "
- << (canceled_payload->IsIncoming() ? "incoming"
- : "outgoing")
- << " payload_id=" << payload_id << " at request of client.";
-
- // Return SUCCESS immediately. Remaining cleanup and updates will be sent
- // in SendPayload() or OnIncomingFrame()
- return {Status::kSuccess};
-}
-
-// @EndpointManagerDataPool
-void PayloadManager::OnIncomingFrame(
- OfflineFrame& offline_frame, const std::string& from_endpoint_id,
- ClientProxy* to_client, proto::connections::Medium current_medium) {
- PayloadTransferFrame& frame =
- *offline_frame.mutable_v1()->mutable_payload_transfer();
-
- switch (frame.packet_type()) {
- case PayloadTransferFrame::CONTROL:
- NEARBY_LOGS(INFO) << "PayloadManager::OnIncomingFrame [CONTROL]: self="
- << this << "; endpoint_id=" << from_endpoint_id;
- ProcessControlPacket(to_client, from_endpoint_id, frame);
- break;
- case PayloadTransferFrame::DATA:
- ProcessDataPacket(to_client, from_endpoint_id, frame);
- break;
- default:
- NEARBY_LOGS(WARNING)
- << "PayloadManager: invalid frame; remote endpoint: self=" << this
- << "; endpoint_id=" << from_endpoint_id;
- break;
- }
-}
-
-void PayloadManager::OnEndpointDisconnect(ClientProxy* client,
- const std::string& endpoint_id,
- CountDownLatch barrier) {
- if (shutdown_.Get()) {
- barrier.CountDown();
- return;
- }
- RunOnStatusUpdateThread(
- "payload-manager-on-disconnect",
- [this, client, endpoint_id, barrier]()
- RUN_ON_PAYLOAD_STATUS_UPDATE_THREAD() mutable {
- // Iterate through all our payloads and look for payloads associated
- // with this endpoint.
- MutexLock lock(&mutex_);
- for (const auto& payload_id : pending_payloads_.GetAllPayloads()) {
- auto* pending_payload = pending_payloads_.GetPayload(payload_id);
- if (!pending_payload) continue;
- auto endpoint_info = pending_payload->GetEndpoint(endpoint_id);
- if (!endpoint_info) continue;
- std::int64_t endpoint_offset = endpoint_info->offset;
- // Stop tracking the endpoint for this payload.
- pending_payload->RemoveEndpoints({endpoint_id});
- // |endpoint_info| is longer valid after calling RemoveEndpoints.
- endpoint_info = nullptr;
-
- std::int64_t payload_total_size =
- pending_payload->GetInternalPayload()->GetTotalSize();
-
- // If no endpoints are left for this payload, close it.
- if (pending_payload->GetEndpoints().empty()) {
- pending_payload->Close();
- }
-
- // Create the payload transfer update.
- PayloadProgressInfo update{payload_id,
- PayloadProgressInfo::Status::kFailure,
- payload_total_size, endpoint_offset};
-
- // Send a client notification of a payload transfer failure.
- client->OnPayloadProgress(endpoint_id, update);
-
- if (pending_payload->IsIncoming()) {
- client->GetAnalyticsRecorder().OnIncomingPayloadDone(
- endpoint_id, pending_payload->GetId(),
- proto::connections::ENDPOINT_IO_ERROR);
- } else {
- client->GetAnalyticsRecorder().OnOutgoingPayloadDone(
- endpoint_id, pending_payload->GetId(),
- proto::connections::ENDPOINT_IO_ERROR);
- }
- }
-
- barrier.CountDown();
- });
-}
-
-proto::connections::PayloadStatus
-PayloadManager::EndpointInfoStatusToPayloadStatus(EndpointInfo::Status status) {
- switch (status) {
- case EndpointInfo::Status::kCanceled:
- return proto::connections::PayloadStatus::REMOTE_CANCELLATION;
- case EndpointInfo::Status::kError:
- return proto::connections::PayloadStatus::REMOTE_ERROR;
- case EndpointInfo::Status::kAvailable:
- return proto::connections::PayloadStatus::SUCCESS;
- default:
- NEARBY_LOGS(INFO) << "PayloadManager: Unknown PayloadStatus";
- return proto::connections::PayloadStatus::UNKNOWN_PAYLOAD_STATUS;
- }
-}
-
-proto::connections::PayloadStatus
-PayloadManager::ControlMessageEventToPayloadStatus(
- PayloadTransferFrame::ControlMessage::EventType event) {
- switch (event) {
- case PayloadTransferFrame::ControlMessage::PAYLOAD_ERROR:
- return proto::connections::PayloadStatus::REMOTE_ERROR;
- case PayloadTransferFrame::ControlMessage::PAYLOAD_CANCELED:
- return proto::connections::PayloadStatus::REMOTE_CANCELLATION;
- default:
- NEARBY_LOG(INFO, "PayloadManager: unknown event=%d", event);
- return proto::connections::PayloadStatus::UNKNOWN_PAYLOAD_STATUS;
- }
-}
-
-PayloadProgressInfo::Status PayloadManager::PayloadStatusToTransferUpdateStatus(
- proto::connections::PayloadStatus status) {
- switch (status) {
- case proto::connections::LOCAL_CANCELLATION:
- case proto::connections::REMOTE_CANCELLATION:
- return PayloadProgressInfo::Status::kCanceled;
- case proto::connections::SUCCESS:
- return PayloadProgressInfo::Status::kSuccess;
- default:
- return PayloadProgressInfo::Status::kFailure;
- }
-}
-
-SingleThreadExecutor* PayloadManager::GetOutgoingPayloadExecutor(
- Payload::Type payload_type) {
- switch (payload_type) {
- case Payload::Type::kBytes:
- return &bytes_payload_executor_;
- case Payload::Type::kFile:
- return &file_payload_executor_;
- case Payload::Type::kStream:
- return &stream_payload_executor_;
- default:
- return nullptr;
- }
-}
-
-int PayloadManager::GetOptimalChunkSize(EndpointIds endpoint_ids) {
- int minChunkSize = std::numeric_limits<int>::max();
- for (const auto& endpoint_id : endpoint_ids) {
- minChunkSize = std::min(
- minChunkSize, endpoint_manager_->GetMaxTransmitPacketSize(endpoint_id));
- }
- return minChunkSize;
-}
-
-PayloadTransferFrame::PayloadHeader PayloadManager::CreatePayloadHeader(
- const InternalPayload& internal_payload, size_t offset) {
- PayloadTransferFrame::PayloadHeader payload_header;
- size_t payload_size = internal_payload.GetTotalSize();
-
- payload_header.set_id(internal_payload.GetId());
- payload_header.set_type(internal_payload.GetType());
- payload_header.set_total_size(payload_size ==
- InternalPayload::kIndeterminateSize
- ? InternalPayload::kIndeterminateSize
- : payload_size - offset);
-
- return payload_header;
-}
-
-PayloadTransferFrame::PayloadChunk PayloadManager::CreatePayloadChunk(
- std::int64_t payload_chunk_offset, ByteArray payload_chunk_body) {
- PayloadTransferFrame::PayloadChunk payload_chunk;
-
- payload_chunk.set_offset(payload_chunk_offset);
- payload_chunk.set_flags(0);
- if (!payload_chunk_body.Empty()) {
- payload_chunk.set_body(std::string(std::move(payload_chunk_body)));
- } else {
- payload_chunk.set_flags(payload_chunk.flags() |
- PayloadTransferFrame::PayloadChunk::LAST_CHUNK);
- }
-
- return payload_chunk;
-}
-
-PayloadManager::PendingPayload* PayloadManager::CreateIncomingPayload(
- const PayloadTransferFrame& frame, const std::string& endpoint_id) {
- auto internal_payload = CreateIncomingInternalPayload(frame);
- if (!internal_payload) {
- return nullptr;
- }
-
- Payload::Id payload_id = internal_payload->GetId();
- NEARBY_LOGS(INFO) << "CreateIncomingPayload: payload_id=" << payload_id;
- MutexLock lock(&mutex_);
- pending_payloads_.StartTrackingPayload(
- payload_id,
- absl::make_unique<PendingPayload>(std::move(internal_payload),
- EndpointIds{endpoint_id}, true));
-
- return pending_payloads_.GetPayload(payload_id);
-}
-
-void PayloadManager::SendClientCallbacksForFinishedOutgoingPayload(
- ClientProxy* client, const EndpointIds& finished_endpoint_ids,
- const PayloadTransferFrame::PayloadHeader& payload_header,
- std::int64_t num_bytes_successfully_transferred,
- proto::connections::PayloadStatus status) {
- RunOnStatusUpdateThread(
- "outgoing-payload-callbacks",
- [this, client, finished_endpoint_ids, payload_header,
- num_bytes_successfully_transferred,
- status]() RUN_ON_PAYLOAD_STATUS_UPDATE_THREAD() {
- // Make sure we're still tracking this payload.
- PendingPayload* pending_payload = GetPayload(payload_header.id());
- if (!pending_payload) {
- return;
- }
-
- PayloadProgressInfo update{
- payload_header.id(),
- PayloadManager::PayloadStatusToTransferUpdateStatus(status),
- payload_header.total_size(), num_bytes_successfully_transferred};
- for (const auto& endpoint_id : finished_endpoint_ids) {
- // Skip sending notifications if we have stopped tracking this
- // endpoint.
- if (!pending_payload->GetEndpoint(endpoint_id)) {
- continue;
- }
-
- // Notify the client.
- client->OnPayloadProgress(endpoint_id, update);
-
- // Mark this payload as done for analytics.
- client->GetAnalyticsRecorder().OnOutgoingPayloadDone(
- endpoint_id, payload_header.id(), status);
- }
-
- // Remove these endpoints from our tracking list for this payload.
- pending_payload->RemoveEndpoints(finished_endpoint_ids);
-
- // Close the payload if no endpoints remain.
- if (pending_payload->GetEndpoints().empty()) {
- pending_payload->Close();
- }
- });
-}
-
-void PayloadManager::SendClientCallbacksForFinishedIncomingPayload(
- ClientProxy* client, const std::string& endpoint_id,
- const PayloadTransferFrame::PayloadHeader& payload_header,
- std::int64_t offset_bytes, proto::connections::PayloadStatus status) {
- RunOnStatusUpdateThread(
- "incoming-payload-callbacks",
- [this, client, endpoint_id, payload_header, offset_bytes,
- status]() RUN_ON_PAYLOAD_STATUS_UPDATE_THREAD() {
- // Make sure we're still tracking this payload.
- PendingPayload* pending_payload = GetPayload(payload_header.id());
- if (!pending_payload) {
- return;
- }
-
- // Unless we never started tracking this payload (meaning we failed to
- // even create the InternalPayload), notify the client (and close it).
- PayloadProgressInfo update{
- payload_header.id(),
- PayloadManager::PayloadStatusToTransferUpdateStatus(status),
- payload_header.total_size(), offset_bytes};
- NotifyClientOfIncomingPayloadProgressInfo(client, endpoint_id, update);
- DestroyPendingPayload(payload_header.id());
-
- // Analyze
- client->GetAnalyticsRecorder().OnIncomingPayloadDone(
- endpoint_id, payload_header.id(), status);
- });
-}
-
-void PayloadManager::SendControlMessage(
- const EndpointIds& endpoint_ids,
- const PayloadTransferFrame::PayloadHeader& payload_header,
- std::int64_t num_bytes_successfully_transferred,
- PayloadTransferFrame::ControlMessage::EventType event_type) {
- PayloadTransferFrame::ControlMessage control_message;
- control_message.set_event(event_type);
- control_message.set_offset(num_bytes_successfully_transferred);
-
- endpoint_manager_->SendControlMessage(payload_header, control_message,
- endpoint_ids);
-}
-
-void PayloadManager::HandleFinishedOutgoingPayload(
- ClientProxy* client, const EndpointIds& finished_endpoint_ids,
- const PayloadTransferFrame::PayloadHeader& payload_header,
- std::int64_t num_bytes_successfully_transferred,
- proto::connections::PayloadStatus status) {
- // This call will destroy a pending payload.
- SendClientCallbacksForFinishedOutgoingPayload(
- client, finished_endpoint_ids, payload_header,
- num_bytes_successfully_transferred, status);
-
- switch (status) {
- case proto::connections::PayloadStatus::LOCAL_ERROR:
- SendControlMessage(finished_endpoint_ids, payload_header,
- num_bytes_successfully_transferred,
- PayloadTransferFrame::ControlMessage::PAYLOAD_ERROR);
- break;
- case proto::connections::PayloadStatus::LOCAL_CANCELLATION:
- NEARBY_LOGS(INFO)
- << "Sending PAYLOAD_CANCEL to receiver side; payload_id="
- << payload_header.id();
- SendControlMessage(
- finished_endpoint_ids, payload_header,
- num_bytes_successfully_transferred,
- PayloadTransferFrame::ControlMessage::PAYLOAD_CANCELED);
- break;
- case proto::connections::PayloadStatus::ENDPOINT_IO_ERROR:
- // Unregister these endpoints, since we had an IO error on the physical
- // connection.
- for (const auto& endpoint_id : finished_endpoint_ids) {
- endpoint_manager_->DiscardEndpoint(client, endpoint_id);
- }
- break;
- case proto::connections::PayloadStatus::REMOTE_ERROR:
- case proto::connections::PayloadStatus::REMOTE_CANCELLATION:
- // No special handling needed for these.
- break;
- default:
- NEARBY_LOGS(INFO)
- << "PayloadManager: Unhandled finished outgoing payload with "
- "payload_status="
- << status;
- break;
- }
-}
-
-void PayloadManager::HandleFinishedIncomingPayload(
- ClientProxy* client, const std::string& endpoint_id,
- const PayloadTransferFrame::PayloadHeader& payload_header,
- std::int64_t offset_bytes, proto::connections::PayloadStatus status) {
- SendClientCallbacksForFinishedIncomingPayload(
- client, endpoint_id, payload_header, offset_bytes, status);
-
- switch (status) {
- case proto::connections::PayloadStatus::LOCAL_ERROR:
- SendControlMessage({endpoint_id}, payload_header, offset_bytes,
- PayloadTransferFrame::ControlMessage::PAYLOAD_ERROR);
- break;
- case proto::connections::PayloadStatus::LOCAL_CANCELLATION:
- SendControlMessage(
- {endpoint_id}, payload_header, offset_bytes,
- PayloadTransferFrame::ControlMessage::PAYLOAD_CANCELED);
- break;
- default:
- NEARBY_LOGS(INFO) << "Unhandled finished incoming payload_id="
- << payload_header.id()
- << " with payload_status=" << status;
- break;
- }
-}
-
-void PayloadManager::HandleSuccessfulOutgoingChunk(
- ClientProxy* client, const std::string& endpoint_id,
- const PayloadTransferFrame::PayloadHeader& payload_header,
- std::int32_t payload_chunk_flags, std::int64_t payload_chunk_offset,
- std::int64_t payload_chunk_body_size) {
- RunOnStatusUpdateThread(
- "outgoing-chunk-success",
- [this, client, endpoint_id, payload_header, payload_chunk_flags,
- payload_chunk_offset,
- payload_chunk_body_size]() RUN_ON_PAYLOAD_STATUS_UPDATE_THREAD() {
- // Make sure we're still tracking this payload and its associated
- // endpoint.
- PendingPayload* pending_payload = GetPayload(payload_header.id());
- if (!pending_payload || !pending_payload->GetEndpoint(endpoint_id)) {
- NEARBY_LOGS(INFO)
- << "HandleSuccessfulOutgoingChunk: endpoint not found: "
- "endpoint_id="
- << endpoint_id;
- return;
- }
-
- bool is_last_chunk =
- (payload_chunk_flags &
- PayloadTransferFrame::PayloadChunk::LAST_CHUNK) != 0;
- PayloadProgressInfo update{
- payload_header.id(),
- is_last_chunk ? PayloadProgressInfo::Status::kSuccess
- : PayloadProgressInfo::Status::kInProgress,
- payload_header.total_size(),
- is_last_chunk ? payload_chunk_offset
- : payload_chunk_offset + payload_chunk_body_size};
-
- // Notify the client.
- client->OnPayloadProgress(endpoint_id, update);
-
- if (is_last_chunk) {
- client->GetAnalyticsRecorder().OnOutgoingPayloadDone(
- endpoint_id, payload_header.id(), proto::connections::SUCCESS);
-
- // Stop tracking this endpoint.
- pending_payload->RemoveEndpoints({endpoint_id});
-
- // Close the payload if no endpoints remain.
- if (pending_payload->GetEndpoints().empty()) {
- pending_payload->Close();
- }
- } else {
- client->GetAnalyticsRecorder().OnPayloadChunkSent(
- endpoint_id, payload_header.id(), payload_chunk_body_size);
- }
- });
-}
-
-// @PayloadManagerStatusUpdateThread
-void PayloadManager::DestroyPendingPayload(Payload::Id payload_id) {
- bool is_incoming = false;
- {
- MutexLock lock(&mutex_);
- auto pending = pending_payloads_.StopTrackingPayload(payload_id);
- if (!pending) return;
- is_incoming = pending->IsIncoming();
- const char* direction = is_incoming ? "incoming" : "outgoing";
- NEARBY_LOGS(INFO) << "PayloadManager: destroying " << direction
- << " pending payload: self=" << this
- << "; payload_id=" << payload_id;
- pending->Close();
- pending.reset();
- }
- if (!is_incoming) NotifyShutdown();
-}
-
-void PayloadManager::HandleSuccessfulIncomingChunk(
- ClientProxy* client, const std::string& endpoint_id,
- const PayloadTransferFrame::PayloadHeader& payload_header,
- std::int32_t payload_chunk_flags, std::int64_t payload_chunk_offset,
- std::int64_t payload_chunk_body_size) {
- RunOnStatusUpdateThread(
- "incoming-chunk-success",
- [this, client, endpoint_id, payload_header, payload_chunk_flags,
- payload_chunk_offset,
- payload_chunk_body_size]() RUN_ON_PAYLOAD_STATUS_UPDATE_THREAD() {
- // Make sure we're still tracking this payload.
- PendingPayload* pending_payload = GetPayload(payload_header.id());
- if (!pending_payload) {
- return;
- }
-
- bool is_last_chunk =
- (payload_chunk_flags &
- PayloadTransferFrame::PayloadChunk::LAST_CHUNK) != 0;
- PayloadProgressInfo update{
- payload_header.id(),
- is_last_chunk ? PayloadProgressInfo::Status::kSuccess
- : PayloadProgressInfo::Status::kInProgress,
- payload_header.total_size(),
- is_last_chunk ? payload_chunk_offset
- : payload_chunk_offset + payload_chunk_body_size};
-
- // Notify the client of this update.
- NotifyClientOfIncomingPayloadProgressInfo(client, endpoint_id, update);
-
- // Analyze the success.
- if (is_last_chunk) {
- client->GetAnalyticsRecorder().OnIncomingPayloadDone(
- endpoint_id, payload_header.id(), proto::connections::SUCCESS);
- } else {
- client->GetAnalyticsRecorder().OnPayloadChunkReceived(
- endpoint_id, payload_header.id(), payload_chunk_body_size);
- }
- });
-}
-
-// @EndpointManagerDataPool
-void PayloadManager::ProcessDataPacket(
- ClientProxy* to_client, const std::string& from_endpoint_id,
- PayloadTransferFrame& payload_transfer_frame) {
- PayloadTransferFrame::PayloadHeader& payload_header =
- *payload_transfer_frame.mutable_payload_header();
- PayloadTransferFrame::PayloadChunk& payload_chunk =
- *payload_transfer_frame.mutable_payload_chunk();
- NEARBY_LOGS(VERBOSE) << "PayloadManager got data OfflineFrame for payload_id="
- << payload_header.id()
- << " from endpoint_id=" << from_endpoint_id
- << " at offset " << payload_chunk.offset();
-
- PendingPayload* pending_payload;
- if (payload_chunk.offset() == 0) {
- RunOnStatusUpdateThread(
- "process-data-packet", [to_client, from_endpoint_id, payload_header,
- this]() RUN_ON_PAYLOAD_STATUS_UPDATE_THREAD() {
- // This is the first chunk of a new incoming
- // payload. Start the analysis.
- to_client->GetAnalyticsRecorder().OnIncomingPayloadStarted(
- from_endpoint_id, payload_header.id(),
- FramePayloadTypeToPayloadType(payload_header.type()),
- payload_header.total_size());
- });
-
- pending_payload =
- CreateIncomingPayload(payload_transfer_frame, from_endpoint_id);
- if (!pending_payload) {
- NEARBY_LOGS(WARNING)
- << "PayloadManager failed to create InternalPayload from "
- "PayloadTransferFrame with payload_id="
- << payload_header.id() << " and type " << payload_header.type()
- << ", aborting receipt.";
- // Send the error to the remote endpoint.
- SendControlMessage({from_endpoint_id}, payload_header,
- payload_chunk.offset(),
- PayloadTransferFrame::ControlMessage::PAYLOAD_ERROR);
- return;
- }
-
- // Also, let the client know of this new incoming payload.
- RunOnStatusUpdateThread(
- "process-data-packet",
- [to_client, from_endpoint_id, pending_payload]()
- RUN_ON_PAYLOAD_STATUS_UPDATE_THREAD() {
- NEARBY_LOGS(INFO)
- << "PayloadManager received new payload_id="
- << pending_payload->GetInternalPayload()->GetId()
- << " from endpoint_id=" << from_endpoint_id;
- to_client->OnPayload(
- from_endpoint_id,
- pending_payload->GetInternalPayload()->ReleasePayload());
- });
- } else {
- pending_payload = GetPayload(payload_header.id());
- if (!pending_payload) {
- NEARBY_LOGS(WARNING) << "ProcessDataPacket: [missing] endpoint_id="
- << from_endpoint_id
- << "; payload_id=" << payload_header.id();
- return;
- }
- }
-
- if (pending_payload->IsLocallyCanceled()) {
- // This incoming payload was canceled by the client. Drop this frame and do
- // all the cleanup. See go/nc-cancel-payload
- NEARBY_LOGS(INFO) << "ProcessDataPacket: [cancel] endpoint_id="
- << from_endpoint_id
- << "; payload_id=" << pending_payload->GetId();
- HandleFinishedIncomingPayload(
- to_client, from_endpoint_id, payload_header, payload_chunk.offset(),
- proto::connections::PayloadStatus::LOCAL_CANCELLATION);
- return;
- }
-
- // Update the offset for this payload. An endpoint disconnection might occur
- // from another thread and we would need to know the current offset to report
- // back to the client. For the sake of accuracy, we update the pending payload
- // here because it's after all payload terminating events are handled, but
- // right before we actually start attaching the next chunk.
- pending_payload->SetOffsetForEndpoint(from_endpoint_id,
- payload_chunk.offset());
-
- // Save size of packet before we move it.
- std::int64_t payload_body_size = payload_chunk.body().size();
- if (pending_payload->GetInternalPayload()
- ->AttachNextChunk(ByteArray(std::move(*payload_chunk.mutable_body())))
- .Raised()) {
- NEARBY_LOGS(ERROR) << "ProcessDataPacket: [data: error] endpoint_id="
- << from_endpoint_id
- << "; payload_id=" << pending_payload->GetId();
- HandleFinishedIncomingPayload(
- to_client, from_endpoint_id, payload_header, payload_chunk.offset(),
- proto::connections::PayloadStatus::LOCAL_ERROR);
- return;
- }
-
- HandleSuccessfulIncomingChunk(to_client, from_endpoint_id, payload_header,
- payload_chunk.flags(), payload_chunk.offset(),
- payload_body_size);
-}
-
-// @EndpointManagerDataPool
-void PayloadManager::ProcessControlPacket(
- ClientProxy* to_client, const std::string& from_endpoint_id,
- PayloadTransferFrame& payload_transfer_frame) {
- const PayloadTransferFrame::PayloadHeader& payload_header =
- payload_transfer_frame.payload_header();
- const PayloadTransferFrame::ControlMessage& control_message =
- payload_transfer_frame.control_message();
- PendingPayload* pending_payload = GetPayload(payload_header.id());
- if (!pending_payload) {
- NEARBY_LOGS(INFO) << "Got ControlMessage for unknown payload_id="
- << payload_header.id()
- << ", ignoring: " << control_message.event();
- return;
- }
-
- switch (control_message.event()) {
- case PayloadTransferFrame::ControlMessage::PAYLOAD_CANCELED:
- if (pending_payload->IsIncoming()) {
- NEARBY_LOGS(INFO) << "Incoming PAYLOAD_CANCELED: from endpoint_id="
- << from_endpoint_id << "; self=" << this;
- // No need to mark the pending payload as cancelled, since this is a
- // remote cancellation for an incoming payload -- we handle everything
- // inline here.
- HandleFinishedIncomingPayload(
- to_client, from_endpoint_id, payload_header,
- control_message.offset(),
- ControlMessageEventToPayloadStatus(control_message.event()));
- } else {
- NEARBY_LOGS(INFO) << "Outgoing PAYLOAD_CANCELED: from endpoint_id="
- << from_endpoint_id << "; self=" << this;
- // Mark the payload as canceled *for this endpoint*.
- pending_payload->SetEndpointStatusFromControlMessage(from_endpoint_id,
- control_message);
- }
- NEARBY_LOGS(VERBOSE)
- << "Marked "
- << (pending_payload->IsIncoming() ? "incoming" : "outgoing")
- << " payload_id=" << pending_payload->GetInternalPayload()->GetId()
- << " as canceled at request of endpoint_id=" << from_endpoint_id;
- break;
- case PayloadTransferFrame::ControlMessage::PAYLOAD_ERROR:
- if (pending_payload->IsIncoming()) {
- HandleFinishedIncomingPayload(
- to_client, from_endpoint_id, payload_header,
- control_message.offset(),
- ControlMessageEventToPayloadStatus(control_message.event()));
- } else {
- pending_payload->SetEndpointStatusFromControlMessage(from_endpoint_id,
- control_message);
- }
- break;
- default:
- NEARBY_LOGS(INFO) << "Unhandled control message "
- << control_message.event() << " for payload_id="
- << pending_payload->GetInternalPayload()->GetId();
- break;
- }
-}
-
-// @PayloadManagerStatusUpdateThread
-void PayloadManager::NotifyClientOfIncomingPayloadProgressInfo(
- ClientProxy* client, const std::string& endpoint_id,
- const PayloadProgressInfo& payload_transfer_update) {
- client->OnPayloadProgress(endpoint_id, payload_transfer_update);
-}
-
-void PayloadManager::RecordPayloadStartedAnalytics(
- ClientProxy* client, const EndpointIds& endpoint_ids,
- std::int64_t payload_id, Payload::Type payload_type, std::int64_t offset,
- std::int64_t total_size) {
- client->GetAnalyticsRecorder().OnOutgoingPayloadStarted(
- endpoint_ids, payload_id, payload_type,
- total_size == -1 ? -1 : total_size - offset);
-}
-
-void PayloadManager::RecordInvalidPayloadAnalytics(
- ClientProxy* client, const EndpointIds& endpoint_ids,
- std::int64_t payload_id, Payload::Type payload_type, std::int64_t offset,
- std::int64_t total_size) {
- RecordPayloadStartedAnalytics(client, endpoint_ids, payload_id, payload_type,
- offset, total_size);
-
- for (const auto& endpoint_id : endpoint_ids) {
- client->GetAnalyticsRecorder().OnOutgoingPayloadDone(
- endpoint_id, payload_id, proto::connections::LOCAL_ERROR);
- }
-}
-
-Payload::Type PayloadManager::FramePayloadTypeToPayloadType(
- PayloadTransferFrame::PayloadHeader::PayloadType type) {
- switch (type) {
- case PayloadTransferFrame_PayloadHeader_PayloadType_BYTES:
- return connections::Payload::Type::kBytes;
- case PayloadTransferFrame_PayloadHeader_PayloadType_FILE:
- return connections::Payload::Type::kFile;
- case PayloadTransferFrame_PayloadHeader_PayloadType_STREAM:
- return connections::Payload::Type::kStream;
- default:
- return connections::Payload::Type::kUnknown;
- }
-}
-
-///////////////////////////////// EndpointInfo /////////////////////////////////
-
-PayloadManager::EndpointInfo::Status
-PayloadManager::EndpointInfo::ControlMessageEventToEndpointInfoStatus(
- PayloadTransferFrame::ControlMessage::EventType event) {
- switch (event) {
- case PayloadTransferFrame::ControlMessage::PAYLOAD_ERROR:
- return Status::kError;
- case PayloadTransferFrame::ControlMessage::PAYLOAD_CANCELED:
- return Status::kCanceled;
- default:
- NEARBY_LOGS(INFO)
- << "Unknown EndpointInfo.Status for ControlMessage.EventType "
- << event;
- return Status::kUnknown;
- }
-}
-
-void PayloadManager::EndpointInfo::SetStatusFromControlMessage(
- const PayloadTransferFrame::ControlMessage& control_message) {
- status.Set(ControlMessageEventToEndpointInfoStatus(control_message.event()));
- NEARBY_LOGS(VERBOSE) << "Marked endpoint " << id << " with status "
- << ToString(status.Get())
- << " based on OOB ControlMessage";
-}
-
-//////////////////////////////// PendingPayload ////////////////////////////////
-
-PayloadManager::PendingPayload::PendingPayload(
- std::unique_ptr<InternalPayload> internal_payload,
- const EndpointIds& endpoint_ids, bool is_incoming)
- : is_incoming_(is_incoming),
- internal_payload_(std::move(internal_payload)) {
- // Initially we mark all endpoints as available.
- // Later on some may become canceled, some may experience data transfer
- // failures. Any of these situations will cause endpoint to be marked as
- // unavailable.
- for (const auto& id : endpoint_ids) {
- EndpointInfo endpoint_info{};
- endpoint_info.id = id;
- endpoint_info.status.Set(EndpointInfo::Status::kAvailable);
-
- endpoints_.emplace(id, std::move(endpoint_info));
- }
-}
-
-Payload::Id PayloadManager::PendingPayload::GetId() const {
- return internal_payload_->GetId();
-}
-
-InternalPayload* PayloadManager::PendingPayload::GetInternalPayload() {
- return internal_payload_.get();
-}
-
-bool PayloadManager::PendingPayload::IsLocallyCanceled() const {
- return is_locally_canceled_.Get();
-}
-
-void PayloadManager::PendingPayload::MarkLocallyCanceled() {
- is_locally_canceled_.Set(true);
-}
-
-bool PayloadManager::PendingPayload::IsIncoming() const { return is_incoming_; }
-
-std::vector<const PayloadManager::EndpointInfo*>
-PayloadManager::PendingPayload::GetEndpoints() const {
- MutexLock lock(&mutex_);
-
- std::vector<const EndpointInfo*> result;
- for (const auto& item : endpoints_) {
- result.push_back(&item.second);
- }
- return result;
-}
-
-PayloadManager::EndpointInfo* PayloadManager::PendingPayload::GetEndpoint(
- const std::string& endpoint_id) {
- MutexLock lock(&mutex_);
-
- auto it = endpoints_.find(endpoint_id);
- if (it == endpoints_.end()) {
- return {};
- }
-
- return &it->second;
-}
-
-void PayloadManager::PendingPayload::RemoveEndpoints(
- const EndpointIds& endpoint_ids) {
- MutexLock lock(&mutex_);
-
- for (const auto& id : endpoint_ids) {
- endpoints_.erase(id);
- }
-}
-
-void PayloadManager::PendingPayload::SetEndpointStatusFromControlMessage(
- const std::string& endpoint_id,
- const PayloadTransferFrame::ControlMessage& control_message) {
- MutexLock lock(&mutex_);
-
- auto item = endpoints_.find(endpoint_id);
- if (item != endpoints_.end()) {
- item->second.SetStatusFromControlMessage(control_message);
- }
-}
-
-void PayloadManager::PendingPayload::SetOffsetForEndpoint(
- const std::string& endpoint_id, std::int64_t offset) {
- MutexLock lock(&mutex_);
-
- auto item = endpoints_.find(endpoint_id);
- if (item != endpoints_.end()) {
- item->second.offset = offset;
- }
-}
-
-void PayloadManager::PendingPayload::Close() {
- if (internal_payload_) internal_payload_->Close();
- close_event_.CountDown();
-}
-
-bool PayloadManager::PendingPayload::WaitForClose() {
- return close_event_.Await(kWaitCloseTimeout).result();
-}
-
-bool PayloadManager::PendingPayload::IsClosed() {
- return close_event_.Await(absl::ZeroDuration()).result();
-}
-
-void PayloadManager::RunOnStatusUpdateThread(const std::string& name,
- std::function<void()> runnable) {
- payload_status_update_executor_.Execute(name, std::move(runnable));
-}
-
-/////////////////////////////// PendingPayloads ///////////////////////////////
-
-void PayloadManager::PendingPayloads::StartTrackingPayload(
- Payload::Id payload_id, std::unique_ptr<PendingPayload> pending_payload) {
- MutexLock lock(&mutex_);
-
- // If the |payload_id| is being re-used, always prefer the newer payload.
- auto it = pending_payloads_.find(payload_id);
- if (it != pending_payloads_.end()) {
- pending_payloads_.erase(payload_id);
- }
- auto pair = pending_payloads_.emplace(payload_id, std::move(pending_payload));
- NEARBY_LOGS(INFO) << "StartTrackingPayload: payload_id=" << payload_id
- << "; inserted=" << pair.second;
-}
-
-std::unique_ptr<PayloadManager::PendingPayload>
-PayloadManager::PendingPayloads::StopTrackingPayload(Payload::Id payload_id) {
- MutexLock lock(&mutex_);
-
- auto it = pending_payloads_.find(payload_id);
- if (it == pending_payloads_.end()) return {};
-
- auto item = pending_payloads_.extract(it);
- return std::move(item.mapped());
-}
-
-PayloadManager::PendingPayload* PayloadManager::PendingPayloads::GetPayload(
- Payload::Id payload_id) const {
- MutexLock lock(&mutex_);
-
- auto item = pending_payloads_.find(payload_id);
- return item != pending_payloads_.end() ? item->second.get() : nullptr;
-}
-
-std::vector<Payload::Id> PayloadManager::PendingPayloads::GetAllPayloads() {
- MutexLock lock(&mutex_);
-
- std::vector<Payload::Id> result;
- for (const auto& item : pending_payloads_) {
- result.push_back(item.first);
- }
- return result;
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/payload_manager.h b/chromium/third_party/nearby/src/cpp/core/internal/payload_manager.h
deleted file mode 100644
index 4e605ab864f..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/payload_manager.h
+++ /dev/null
@@ -1,322 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_PAYLOAD_MANAGER_H_
-#define CORE_INTERNAL_PAYLOAD_MANAGER_H_
-
-#include <cstdint>
-#include <memory>
-#include <string>
-#include <vector>
-
-#include "absl/container/flat_hash_map.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/endpoint_manager.h"
-#include "core/internal/internal_payload.h"
-#include "core/listeners.h"
-#include "core/payload.h"
-#include "core/status.h"
-#include "platform/base/byte_array.h"
-#include "platform/public/atomic_boolean.h"
-#include "platform/public/atomic_reference.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/mutex.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Annotations for methods that need to run on PayloadStatusUpdateThread.
-// Use only in PayloadManager
-#define RUN_ON_PAYLOAD_STATUS_UPDATE_THREAD() \
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(payload_status_update_executor_)
-
-class PayloadManager : public EndpointManager::FrameProcessor {
- public:
- using EndpointIds = std::vector<std::string>;
- constexpr static const absl::Duration kWaitCloseTimeout =
- absl::Milliseconds(5000);
-
- explicit PayloadManager(EndpointManager& endpoint_manager);
- ~PayloadManager() override;
-
- void SendPayload(ClientProxy* client, const EndpointIds& endpoint_ids,
- Payload payload);
- Status CancelPayload(ClientProxy* client, Payload::Id payload_id);
-
- // @EndpointManagerReaderThread
- void OnIncomingFrame(OfflineFrame& offline_frame,
- const std::string& from_endpoint_id,
- ClientProxy* to_client,
- proto::connections::Medium current_medium) override;
-
- // @EndpointManagerThread
- void OnEndpointDisconnect(ClientProxy* client, const std::string& endpoint_id,
- CountDownLatch barrier) override;
-
- void DisconnectFromEndpointManager();
-
- private:
- // Information about an endpoint for a particular payload.
- struct EndpointInfo {
- // Status set for the endpoint out-of-band via a ControlMessage.
- enum class Status {
- kUnknown,
- kAvailable,
- kCanceled,
- kError,
- };
-
- void SetStatusFromControlMessage(
- const PayloadTransferFrame::ControlMessage& control_message);
-
- static Status ControlMessageEventToEndpointInfoStatus(
- PayloadTransferFrame::ControlMessage::EventType event);
-
- std::string id;
- AtomicReference<Status> status{Status::kUnknown};
- std::int64_t offset = 0;
- };
-
- // Tracks state for an InternalPayload and the endpoints associated with it.
- class PendingPayload {
- public:
- PendingPayload(std::unique_ptr<InternalPayload> internal_payload,
- const EndpointIds& endpoint_ids, bool is_incoming);
- PendingPayload(PendingPayload&&) = default;
- PendingPayload& operator=(PendingPayload&&) = default;
-
- ~PendingPayload() { Close(); }
-
- Payload::Id GetId() const;
-
- InternalPayload* GetInternalPayload();
-
- bool IsLocallyCanceled() const;
- void MarkLocallyCanceled();
- bool IsIncoming() const;
-
- // Gets the EndpointInfo objects for the endpoints (still) associated with
- // this payload.
- std::vector<const EndpointInfo*> GetEndpoints() const
- ABSL_LOCKS_EXCLUDED(mutex_);
- // Returns the EndpointInfo for a given endpoint ID. Returns null if the
- // endpoint is not associated with this payload.
- EndpointInfo* GetEndpoint(const std::string& endpoint_id)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Removes the given endpoints, e.g. on error.
- void RemoveEndpoints(const EndpointIds& endpoint_ids_to_remove)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Sets the status for a particular endpoint.
- void SetEndpointStatusFromControlMessage(
- const std::string& endpoint_id,
- const PayloadTransferFrame::ControlMessage& control_message)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Sets the offset for a particular endpoint.
- void SetOffsetForEndpoint(const std::string& endpoint_id,
- std::int64_t offset) ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Closes internal_payload_ and triggers close_event_.
- // Close is called when a pending peyload does not have associated
- // endpoints.
- void Close();
-
- // Waits for close_event_ or for timeout to happen.
- // Returns true, if event happened, false otherwise.
- bool WaitForClose();
- bool IsClosed();
-
- private:
- mutable Mutex mutex_;
- bool is_incoming_;
- AtomicBoolean is_locally_canceled_{false};
- CountDownLatch close_event_{1};
- std::unique_ptr<InternalPayload> internal_payload_;
- absl::flat_hash_map<std::string, EndpointInfo> endpoints_
- ABSL_GUARDED_BY(mutex_);
- };
-
- // Tracks and manages PendingPayload objects in a synchronized manner.
- class PendingPayloads {
- public:
- PendingPayloads() = default;
- ~PendingPayloads() = default;
-
- void StartTrackingPayload(Payload::Id payload_id,
- std::unique_ptr<PendingPayload> pending_payload)
- ABSL_LOCKS_EXCLUDED(mutex_);
- std::unique_ptr<PendingPayload> StopTrackingPayload(Payload::Id payload_id)
- ABSL_LOCKS_EXCLUDED(mutex_);
- PendingPayload* GetPayload(Payload::Id payload_id) const
- ABSL_LOCKS_EXCLUDED(mutex_);
- std::vector<Payload::Id> GetAllPayloads() ABSL_LOCKS_EXCLUDED(mutex_);
-
- private:
- mutable Mutex mutex_;
- absl::flat_hash_map<Payload::Id, std::unique_ptr<PendingPayload>>
- pending_payloads_ ABSL_GUARDED_BY(mutex_);
- };
-
- using Endpoints = std::vector<const EndpointInfo*>;
- static std::string ToString(const EndpointIds& endpoint_ids);
- static std::string ToString(const Endpoints& endpoints);
- static std::string ToString(Payload::Type type);
- static std::string ToString(EndpointInfo::Status status);
-
- // Splits the endpoints for this payload by availability.
- // Returns a pair of lists of EndpointInfo*, with the first being the list of
- // still-available endpoints, and the second for unavailable endpoints.
- static std::pair<Endpoints, Endpoints> GetAvailableAndUnavailableEndpoints(
- const PendingPayload& pending_payload);
-
- // Converts list of EndpointInfo to list of Endpoint ids.
- // Returns list of endpoint ids.
- static EndpointIds EndpointsToEndpointIds(const Endpoints& endpoints);
-
- bool SendPayloadLoop(ClientProxy* client, PendingPayload& pending_payload,
- PayloadTransferFrame::PayloadHeader& payload_header,
- std::int64_t& next_chunk_offset, size_t resume_offset);
- void SendClientCallbacksForFinishedIncomingPayloadRunnable(
- ClientProxy* client, const std::string& endpoint_id,
- const PayloadTransferFrame::PayloadHeader& payload_header,
- std::int64_t offset_bytes, proto::connections::PayloadStatus status);
-
- // Converts the status of an endpoint that's been set out-of-band via a remote
- // ControlMessage to the PayloadStatus for handling of that endpoint-payload
- // pair.
- static proto::connections::PayloadStatus EndpointInfoStatusToPayloadStatus(
- EndpointInfo::Status status);
- // Converts a ControlMessage::EventType for a particular payload to a
- // PayloadStatus. Called when we've received a ControlMessage with this event
- // from a remote endpoint; thus the PayloadStatuses are REMOTE_*.
- static proto::connections::PayloadStatus ControlMessageEventToPayloadStatus(
- PayloadTransferFrame::ControlMessage::EventType event);
- static PayloadProgressInfo::Status PayloadStatusToTransferUpdateStatus(
- proto::connections::PayloadStatus status);
-
- int GetOptimalChunkSize(EndpointIds endpoint_ids);
-
- PayloadTransferFrame::PayloadHeader CreatePayloadHeader(
- const InternalPayload& payload, size_t offset);
- PayloadTransferFrame::PayloadChunk CreatePayloadChunk(std::int64_t offset,
- ByteArray body);
-
- PendingPayload* CreateIncomingPayload(const PayloadTransferFrame& frame,
- const std::string& endpoint_id)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- Payload::Id CreateOutgoingPayload(Payload payload,
- const EndpointIds& endpoint_ids)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- void SendClientCallbacksForFinishedOutgoingPayload(
- ClientProxy* client, const EndpointIds& finished_endpoint_ids,
- const PayloadTransferFrame::PayloadHeader& payload_header,
- std::int64_t num_bytes_successfully_transferred,
- proto::connections::PayloadStatus status);
- void SendClientCallbacksForFinishedIncomingPayload(
- ClientProxy* client, const std::string& endpoint_id,
- const PayloadTransferFrame::PayloadHeader& payload_header,
- std::int64_t offset_bytes, proto::connections::PayloadStatus status);
-
- void SendControlMessage(
- const EndpointIds& endpoint_ids,
- const PayloadTransferFrame::PayloadHeader& payload_header,
- std::int64_t num_bytes_successfully_transferred,
- PayloadTransferFrame::ControlMessage::EventType event_type);
-
- // Handles a finished outgoing payload for the given endpointIds. All statuses
- // except for SUCCESS are handled here.
- void HandleFinishedOutgoingPayload(
- ClientProxy* client, const EndpointIds& finished_endpoint_ids,
- const PayloadTransferFrame::PayloadHeader& payload_header,
- std::int64_t num_bytes_successfully_transferred,
- proto::connections::PayloadStatus status =
- proto::connections::PayloadStatus::UNKNOWN_PAYLOAD_STATUS);
- void HandleFinishedIncomingPayload(
- ClientProxy* client, const std::string& endpoint_id,
- const PayloadTransferFrame::PayloadHeader& payload_header,
- std::int64_t offset_bytes, proto::connections::PayloadStatus status);
-
- void HandleSuccessfulOutgoingChunk(
- ClientProxy* client, const std::string& endpoint_id,
- const PayloadTransferFrame::PayloadHeader& payload_header,
- std::int32_t payload_chunk_flags, std::int64_t payload_chunk_offset,
- std::int64_t payload_chunk_body_size);
- void HandleSuccessfulIncomingChunk(
- ClientProxy* client, const std::string& endpoint_id,
- const PayloadTransferFrame::PayloadHeader& payload_header,
- std::int32_t payload_chunk_flags, std::int64_t payload_chunk_offset,
- std::int64_t payload_chunk_body_size);
-
- void ProcessDataPacket(ClientProxy* to_client,
- const std::string& from_endpoint_id,
- PayloadTransferFrame& payload_transfer_frame);
- void ProcessControlPacket(ClientProxy* to_client,
- const std::string& from_endpoint_id,
- PayloadTransferFrame& payload_transfer_frame);
-
- void NotifyClientOfIncomingPayloadProgressInfo(
- ClientProxy* client, const std::string& endpoint_id,
- const PayloadProgressInfo& payload_transfer_update)
- RUN_ON_PAYLOAD_STATUS_UPDATE_THREAD();
-
- SingleThreadExecutor* GetOutgoingPayloadExecutor(Payload::Type payload_type);
-
- void RunOnStatusUpdateThread(const std::string& name,
- std::function<void()> runnable);
- bool NotifyShutdown() ABSL_LOCKS_EXCLUDED(mutex_);
- void DestroyPendingPayload(Payload::Id payload_id)
- ABSL_LOCKS_EXCLUDED(mutex_);
- PendingPayload* GetPayload(Payload::Id payload_id) const
- ABSL_LOCKS_EXCLUDED(mutex_);
- void CancelAllPayloads() ABSL_LOCKS_EXCLUDED(mutex_);
-
- void RecordPayloadStartedAnalytics(ClientProxy* client,
- const EndpointIds& endpoint_ids,
- std::int64_t payload_id,
- Payload::Type payload_type,
- std::int64_t offset,
- std::int64_t total_size);
- void RecordInvalidPayloadAnalytics(ClientProxy* client,
- const EndpointIds& endpoint_ids,
- std::int64_t payload_id,
- Payload::Type payload_type,
- std::int64_t offset,
- std::int64_t total_size);
-
- Payload::Type FramePayloadTypeToPayloadType(
- PayloadTransferFrame::PayloadHeader::PayloadType type);
-
- mutable Mutex mutex_;
- AtomicBoolean shutdown_{false};
- std::unique_ptr<CountDownLatch> shutdown_barrier_;
- int send_payload_count_ = 0;
- PendingPayloads pending_payloads_ ABSL_GUARDED_BY(mutex_);
- SingleThreadExecutor bytes_payload_executor_;
- SingleThreadExecutor file_payload_executor_;
- SingleThreadExecutor stream_payload_executor_;
- SingleThreadExecutor payload_status_update_executor_;
-
- EndpointManager* endpoint_manager_;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_PAYLOAD_MANAGER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/payload_manager_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/payload_manager_test.cc
deleted file mode 100644
index 372642d3926..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/payload_manager_test.cc
+++ /dev/null
@@ -1,373 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/payload_manager.h"
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/strings/string_view.h"
-#include "core/internal/simulation_user.h"
-#include "platform/base/byte_array.h"
-#include "platform/public/pipe.h"
-#include "platform/public/system_clock.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-
-constexpr absl::string_view kServiceId = "service-id";
-constexpr absl::string_view kDeviceA = "device-a";
-constexpr absl::string_view kDeviceB = "device-b";
-constexpr absl::string_view kMessage = "message";
-constexpr absl::Duration kProgressTimeout = absl::Milliseconds(1000);
-constexpr absl::Duration kDefaultTimeout = absl::Milliseconds(1000);
-
-constexpr BooleanMediumSelector kTestCases[] = {
- BooleanMediumSelector{
- .bluetooth = true,
- },
- BooleanMediumSelector{
- .wifi_lan = true,
- },
- BooleanMediumSelector{
- .bluetooth = true,
- .wifi_lan = true,
- },
-};
-
-class PayloadSimulationUser : public SimulationUser {
- public:
- explicit PayloadSimulationUser(
- absl::string_view name,
- BooleanMediumSelector allowed = BooleanMediumSelector())
- : SimulationUser(std::string(name), allowed) {}
- ~PayloadSimulationUser() override {
- NEARBY_LOGS(INFO) << "PayloadSimulationUser: [down] name=" << info_.data();
- // SystemClock::Sleep(kDefaultTimeout);
- }
-
- Payload& GetPayload() { return payload_; }
- void SendPayload(Payload payload) {
- sender_payload_id_ = payload.GetId();
- pm_.SendPayload(&client_, {discovered_.endpoint_id}, std::move(payload));
- }
-
- Status CancelPayload() {
- if (sender_payload_id_) {
- return pm_.CancelPayload(&client_, sender_payload_id_);
- } else {
- return pm_.CancelPayload(&client_, payload_.GetId());
- }
- }
-
- bool IsConnected() const {
- return client_.IsConnectedToEndpoint(discovered_.endpoint_id);
- }
-
- protected:
- Payload::Id sender_payload_id_ = 0;
-};
-
-class PayloadManagerTest
- : public ::testing::TestWithParam<BooleanMediumSelector> {
- protected:
- PayloadManagerTest() { env_.Stop(); }
-
- bool SetupConnection(PayloadSimulationUser& user_a,
- PayloadSimulationUser& user_b) {
- user_a.StartAdvertising(std::string(kServiceId), &connection_latch_);
- user_b.StartDiscovery(std::string(kServiceId), &discovery_latch_);
- EXPECT_TRUE(discovery_latch_.Await(kDefaultTimeout).result());
- EXPECT_EQ(user_b.GetDiscovered().service_id, kServiceId);
- EXPECT_EQ(user_b.GetDiscovered().endpoint_info, user_a.GetInfo());
- EXPECT_FALSE(user_b.GetDiscovered().endpoint_id.empty());
- NEARBY_LOG(INFO, "EP-B: [discovered] %s",
- user_b.GetDiscovered().endpoint_id.c_str());
- user_b.RequestConnection(&connection_latch_);
- EXPECT_TRUE(connection_latch_.Await(kDefaultTimeout).result());
- EXPECT_FALSE(user_a.GetDiscovered().endpoint_id.empty());
- NEARBY_LOG(INFO, "EP-A: [discovered] %s",
- user_a.GetDiscovered().endpoint_id.c_str());
- NEARBY_LOG(INFO, "Both users discovered their peers.");
- user_a.AcceptConnection(&accept_latch_);
- user_b.AcceptConnection(&accept_latch_);
- EXPECT_TRUE(accept_latch_.Await(kDefaultTimeout).result());
- NEARBY_LOG(INFO, "Both users reached connected state.");
- return user_a.IsConnected() && user_b.IsConnected();
- }
-
- CountDownLatch discovery_latch_{1};
- CountDownLatch connection_latch_{2};
- CountDownLatch accept_latch_{2};
- CountDownLatch payload_latch_{1};
- MediumEnvironment& env_{MediumEnvironment::Instance()};
-};
-
-TEST_P(PayloadManagerTest, CanCreateOne) {
- env_.Start();
- PayloadSimulationUser user_a(kDeviceA, GetParam());
- env_.Stop();
-}
-
-TEST_P(PayloadManagerTest, CanCreateMultiple) {
- env_.Start();
- PayloadSimulationUser user_a(kDeviceA, GetParam());
- PayloadSimulationUser user_b(kDeviceB, GetParam());
- env_.Stop();
-}
-
-TEST_P(PayloadManagerTest, CanSendBytePayload) {
- env_.Start();
- PayloadSimulationUser user_a(kDeviceA, GetParam());
- PayloadSimulationUser user_b(kDeviceB, GetParam());
- ASSERT_TRUE(SetupConnection(user_a, user_b));
-
- user_a.ExpectPayload(payload_latch_);
- user_b.SendPayload(Payload(ByteArray{std::string(kMessage)}));
- EXPECT_TRUE(payload_latch_.Await(kDefaultTimeout).result());
- EXPECT_EQ(user_a.GetPayload().AsBytes(), ByteArray(std::string(kMessage)));
- NEARBY_LOG(INFO, "Test completed.");
-
- user_a.Stop();
- user_b.Stop();
- env_.Stop();
-}
-
-TEST_P(PayloadManagerTest, CanSendStreamPayload) {
- env_.Start();
- PayloadSimulationUser user_a(kDeviceA, GetParam());
- PayloadSimulationUser user_b(kDeviceB, GetParam());
- ASSERT_TRUE(SetupConnection(user_a, user_b));
-
- auto pipe = std::make_shared<Pipe>();
- OutputStream& tx = pipe->GetOutputStream();
-
- user_a.ExpectPayload(payload_latch_);
- const ByteArray message{std::string(kMessage)};
- // The first write to the output stream will send the first PAYLOAD_TRANSFER
- // packet with payload info and message data.
- tx.Write(message);
-
- user_b.SendPayload(Payload([pipe]() -> InputStream& {
- return pipe->GetInputStream(); // NOLINT
- }));
- ASSERT_TRUE(payload_latch_.Await(kDefaultTimeout).result());
- ASSERT_NE(user_a.GetPayload().AsStream(), nullptr);
- InputStream& rx = *user_a.GetPayload().AsStream();
- NEARBY_LOG(INFO, "Stream extracted.");
-
- EXPECT_TRUE(user_a.WaitForProgress(
- [&message](const PayloadProgressInfo& info) {
- return info.bytes_transferred >= message.size();
- },
- kProgressTimeout));
- ByteArray result = rx.Read(Pipe::kChunkSize).result();
- EXPECT_EQ(result, message);
- NEARBY_LOG(INFO, "Packet 1 handled.");
-
- tx.Write(message);
- EXPECT_TRUE(user_a.WaitForProgress(
- [&message](const PayloadProgressInfo& info) {
- return info.bytes_transferred >= 2 * message.size();
- },
- kProgressTimeout));
- ByteArray result2 = rx.Read(Pipe::kChunkSize).result();
- EXPECT_EQ(result2, message);
- NEARBY_LOG(INFO, "Packet 2 handled.");
-
- rx.Close();
- tx.Close();
- NEARBY_LOG(INFO, "Test completed.");
- user_a.Stop();
- user_b.Stop();
- env_.Stop();
-}
-
-TEST_P(PayloadManagerTest, CanCancelPayloadOnReceiverSide) {
- env_.Start();
- PayloadSimulationUser user_a(kDeviceA, GetParam());
- PayloadSimulationUser user_b(kDeviceB, GetParam());
- ASSERT_TRUE(SetupConnection(user_a, user_b));
-
- auto pipe = std::make_shared<Pipe>();
- OutputStream& tx = pipe->GetOutputStream();
-
- user_a.ExpectPayload(payload_latch_);
- const ByteArray message{std::string(kMessage)};
- tx.Write(message);
-
- user_b.SendPayload(Payload([pipe]() -> InputStream& {
- return pipe->GetInputStream(); // NOLINT
- }));
- ASSERT_TRUE(payload_latch_.Await(kDefaultTimeout).result());
- ASSERT_NE(user_a.GetPayload().AsStream(), nullptr);
- InputStream& rx = *user_a.GetPayload().AsStream();
- NEARBY_LOG(INFO, "Stream extracted.");
-
- EXPECT_TRUE(user_a.WaitForProgress(
- [&message](const PayloadProgressInfo& info) {
- return info.bytes_transferred >= message.size();
- },
- kProgressTimeout));
- ByteArray result = rx.Read(Pipe::kChunkSize).result();
- EXPECT_EQ(result, message);
- NEARBY_LOG(INFO, "Packet 1 handled.");
-
- EXPECT_EQ(user_a.CancelPayload(), Status{Status::kSuccess});
- NEARBY_LOG(INFO, "Stream canceled on receiver side.");
-
- // Sender will only handle cancel event if it is sending.
- // Once cancel is handled, write will fail.
- int count = 0;
- while (true) {
- if (!tx.Write(message).Ok()) break;
- SystemClock::Sleep(kDefaultTimeout);
- count++;
- }
- ASSERT_LE(count, 10);
-
- EXPECT_TRUE(user_a.WaitForProgress(
- [status = PayloadProgressInfo::Status::kCanceled](
- const PayloadProgressInfo& info) { return info.status == status; },
- kProgressTimeout));
- NEARBY_LOG(INFO, "Stream cancelation received.");
-
- tx.Close();
- rx.Close();
-
- NEARBY_LOG(INFO, "Test completed.");
- user_a.Stop();
- user_b.Stop();
- env_.Stop();
-}
-
-TEST_P(PayloadManagerTest, CanCancelPayloadOnSenderSide) {
- env_.Start();
- PayloadSimulationUser user_a(kDeviceA, GetParam());
- PayloadSimulationUser user_b(kDeviceB, GetParam());
- ASSERT_TRUE(SetupConnection(user_a, user_b));
-
- auto pipe = std::make_shared<Pipe>();
- OutputStream& tx = pipe->GetOutputStream();
-
- user_a.ExpectPayload(payload_latch_);
- const ByteArray message{std::string(kMessage)};
- tx.Write(message);
-
- user_b.SendPayload(Payload([pipe]() -> InputStream& {
- return pipe->GetInputStream(); // NOLINT
- }));
- ASSERT_TRUE(payload_latch_.Await(kDefaultTimeout).result());
- ASSERT_NE(user_a.GetPayload().AsStream(), nullptr);
- InputStream& rx = *user_a.GetPayload().AsStream();
- NEARBY_LOG(INFO, "Stream extracted.");
-
- EXPECT_TRUE(user_a.WaitForProgress(
- [&message](const PayloadProgressInfo& info) {
- return info.bytes_transferred >= message.size();
- },
- kProgressTimeout));
- ByteArray result = rx.Read(Pipe::kChunkSize).result();
- EXPECT_EQ(result, message);
- NEARBY_LOG(INFO, "Packet 1 handled.");
-
- EXPECT_EQ(user_b.CancelPayload(), Status{Status::kSuccess});
- NEARBY_LOG(INFO, "Stream canceled on sender side.");
-
- // Sender will only handle cancel event if it is sending.
- // Once cancel is handled, write will fail.
- int count = 0;
- while (true) {
- if (!tx.Write(message).Ok()) break;
- SystemClock::Sleep(kDefaultTimeout);
- count++;
- }
- ASSERT_LE(count, 10);
-
- EXPECT_TRUE(user_a.WaitForProgress(
- [status = PayloadProgressInfo::Status::kCanceled](
- const PayloadProgressInfo& info) { return info.status == status; },
- kProgressTimeout));
- NEARBY_LOG(INFO, "Stream cancelation received.");
-
- tx.Close();
- rx.Close();
-
- NEARBY_LOG(INFO, "Test completed.");
- user_a.Stop();
- user_b.Stop();
- env_.Stop();
-}
-
-TEST_P(PayloadManagerTest, SendPayloadWithSkip_StreamPayload) {
- constexpr size_t kOffset = 3;
- env_.Start();
- PayloadSimulationUser user_a(kDeviceA, GetParam());
- PayloadSimulationUser user_b(kDeviceB, GetParam());
- ASSERT_TRUE(SetupConnection(user_a, user_b));
-
- auto pipe = std::make_shared<Pipe>();
- OutputStream& tx = pipe->GetOutputStream();
-
- user_a.ExpectPayload(payload_latch_);
- const ByteArray message{std::string(kMessage)};
- // The first write to the output stream will send the first PAYLOAD_TRANSFER
- // packet with payload info and message data.
- tx.Write(message);
-
- Payload payload([pipe]() -> InputStream& {
- return pipe->GetInputStream(); // NOLINT
- });
- payload.SetOffset(kOffset);
- user_b.SendPayload(std::move(payload));
- ASSERT_TRUE(payload_latch_.Await(kDefaultTimeout).result());
- ASSERT_NE(user_a.GetPayload().AsStream(), nullptr);
- InputStream& rx = *user_a.GetPayload().AsStream();
- NEARBY_LOG(INFO, "Stream extracted.");
-
- EXPECT_TRUE(user_a.WaitForProgress(
- [&message](const PayloadProgressInfo& info) {
- return info.bytes_transferred >= message.size() - kOffset;
- },
- kProgressTimeout));
- ByteArray result = rx.Read(Pipe::kChunkSize).result();
- EXPECT_EQ(result, ByteArray("sage"));
- NEARBY_LOG(INFO, "Packet 1 handled.");
-
- tx.Write(message);
- EXPECT_TRUE(user_a.WaitForProgress(
- [&message](const PayloadProgressInfo& info) {
- return info.bytes_transferred >= 2 * message.size() - kOffset;
- },
- kProgressTimeout));
- ByteArray result2 = rx.Read(Pipe::kChunkSize).result();
- EXPECT_EQ(result2, message);
- NEARBY_LOG(INFO, "Packet 2 handled.");
-
- rx.Close();
- tx.Close();
- NEARBY_LOG(INFO, "Test completed.");
- user_a.Stop();
- user_b.Stop();
- env_.Stop();
-}
-
-INSTANTIATE_TEST_SUITE_P(ParametrisedPayloadManagerTest, PayloadManagerTest,
- ::testing::ValuesIn(kTestCases));
-
-} // namespace
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/pcp_handler.h b/chromium/third_party/nearby/src/cpp/core/internal/pcp_handler.h
deleted file mode 100644
index b7ad50c0295..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/pcp_handler.h
+++ /dev/null
@@ -1,122 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_PCP_HANDLER_H_
-#define CORE_INTERNAL_PCP_HANDLER_H_
-
-#include <vector>
-
-#include "core/internal/client_proxy.h"
-#include "core/internal/pcp.h"
-#include "core/listeners.h"
-#include "core/options.h"
-#include "core/params.h"
-#include "core/status.h"
-#include "core/strategy.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-inline Pcp StrategyToPcp(Strategy strategy) {
- if (strategy == Strategy::kP2pCluster) return Pcp::kP2pCluster;
- if (strategy == Strategy::kP2pStar) return Pcp::kP2pStar;
- if (strategy == Strategy::kP2pPointToPoint) return Pcp::kP2pPointToPoint;
- return Pcp::kUnknown;
-}
-
-inline Strategy PcpToStrategy(Pcp pcp) {
- if (pcp == Pcp::kP2pCluster) return Strategy::kP2pCluster;
- if (pcp == Pcp::kP2pStar) return Strategy::kP2pStar;
- if (pcp == Pcp::kP2pPointToPoint) return Strategy::kP2pPointToPoint;
- return Strategy::kNone;
-}
-
-// Defines the set of methods that need to be implemented to handle the
-// per-PCP-specific operations in the OfflineServiceController.
-//
-// These methods are all meant to be synchronous, and should return only after
-// knowing they've done what they were supposed to do (or unequivocally failed
-// to do so).
-//
-// See details here:
-// cpp/core/core.h
-class PcpHandler {
- public:
- virtual ~PcpHandler() = default;
-
- // Return strategy supported by this protocol.
- virtual Strategy GetStrategy() const = 0;
-
- // Return concrete variant of protocol.
- virtual Pcp GetPcp() const = 0;
-
- // We have been asked by the client to start advertising. Once we successfully
- // start advertising, we'll change the ClientProxy's state.
- // ConnectionListener (info.listener) will be notified in case of any event.
- // See
- // cpp/core/listeners.h
- virtual Status StartAdvertising(ClientProxy* client,
- const std::string& service_id,
- const ConnectionOptions& options,
- const ConnectionRequestInfo& info) = 0;
-
- // If Advertising is active, stop it, and change CLientProxy state,
- // otherwise do nothing.
- virtual void StopAdvertising(ClientProxy* client) = 0;
-
- // Start discovery of endpoints that may be advertising.
- // Update ClientProxy state once discovery started.
- // DiscoveryListener will get called in case of any event.
- virtual Status StartDiscovery(ClientProxy* client,
- const std::string& service_id,
- const ConnectionOptions& options,
- const DiscoveryListener& listener) = 0;
-
- // If Discovery is active, stop it, and change CLientProxy state,
- // otherwise do nothing.
- virtual void StopDiscovery(ClientProxy* client) = 0;
-
- // If Discovery is active with is_out_of_band_connection == true, invoke the
- // callback with the provided endpoint info.
- virtual void InjectEndpoint(ClientProxy* client,
- const std::string& service_id,
- const OutOfBandConnectionMetadata& metadata) = 0;
-
- // If remote endpoint has been successfully discovered, request it to form a
- // connection, update state on ClientProxy.
- virtual Status RequestConnection(ClientProxy* client,
- const std::string& endpoint_id,
- const ConnectionRequestInfo& info,
- const ConnectionOptions& options) = 0;
-
- // Either party may call this to accept connection on their part.
- // Until both parties call it, connection will not reach a data phase.
- // Update state in ClientProxy.
- virtual Status AcceptConnection(ClientProxy* client,
- const std::string& endpoint_id,
- const PayloadListener& payload_listener) = 0;
-
- // Either party may call this to reject connection on their part before
- // connection reaches data phase. If either party does call it, connection
- // will terminate. Update state in ClientProxy.
- virtual Status RejectConnection(ClientProxy* client,
- const std::string& endpoint_id) = 0;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_PCP_HANDLER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/pcp_manager.cc b/chromium/third_party/nearby/src/cpp/core/internal/pcp_manager.cc
deleted file mode 100644
index 98de1acfa0d..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/pcp_manager.cc
+++ /dev/null
@@ -1,146 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/pcp_manager.h"
-
-#include "core/internal/p2p_cluster_pcp_handler.h"
-#include "core/internal/p2p_point_to_point_pcp_handler.h"
-#include "core/internal/p2p_star_pcp_handler.h"
-#include "core/internal/pcp_handler.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-PcpManager::PcpManager(
- Mediums& mediums, EndpointChannelManager& channel_manager,
- EndpointManager& endpoint_manager, BwuManager& bwu_manager,
- InjectedBluetoothDeviceStore& injected_bluetooth_device_store) {
- handlers_[Pcp::kP2pCluster] = std::make_unique<P2pClusterPcpHandler>(
- &mediums, &endpoint_manager, &channel_manager, &bwu_manager,
- injected_bluetooth_device_store);
- handlers_[Pcp::kP2pStar] = std::make_unique<P2pStarPcpHandler>(
- mediums, endpoint_manager, channel_manager, bwu_manager,
- injected_bluetooth_device_store);
- handlers_[Pcp::kP2pPointToPoint] =
- std::make_unique<P2pPointToPointPcpHandler>(
- mediums, endpoint_manager, channel_manager, bwu_manager,
- injected_bluetooth_device_store);
-}
-
-void PcpManager::DisconnectFromEndpointManager() {
- if (shutdown_.Set(true)) return;
- for (auto& item : handlers_) {
- if (!item.second) continue;
- item.second->DisconnectFromEndpointManager();
- }
-}
-
-PcpManager::~PcpManager() {
- NEARBY_LOGS(INFO) << "Initiating shutdown of PcpManager.";
- DisconnectFromEndpointManager();
- NEARBY_LOGS(INFO) << "PcpManager has shut down.";
-}
-
-Status PcpManager::StartAdvertising(ClientProxy* client,
- const string& service_id,
- const ConnectionOptions& options,
- const ConnectionRequestInfo& info) {
- if (!SetCurrentPcpHandler(options.strategy)) {
- return {Status::kError};
- }
-
- return current_->StartAdvertising(client, service_id, options, info);
-}
-
-void PcpManager::StopAdvertising(ClientProxy* client) {
- if (current_) {
- current_->StopAdvertising(client);
- }
-}
-
-Status PcpManager::StartDiscovery(ClientProxy* client, const string& service_id,
- const ConnectionOptions& options,
- DiscoveryListener listener) {
- if (!SetCurrentPcpHandler(options.strategy)) {
- return {Status::kError};
- }
-
- return current_->StartDiscovery(client, service_id, options,
- std::move(listener));
-}
-
-void PcpManager::StopDiscovery(ClientProxy* client) {
- if (current_) {
- current_->StopDiscovery(client);
- }
-}
-
-void PcpManager::InjectEndpoint(ClientProxy* client,
- const std::string& service_id,
- const OutOfBandConnectionMetadata& metadata) {
- if (current_) {
- current_->InjectEndpoint(client, service_id, metadata);
- }
-}
-
-Status PcpManager::RequestConnection(ClientProxy* client,
- const string& endpoint_id,
- const ConnectionRequestInfo& info,
- const ConnectionOptions& options) {
- if (!current_) {
- return {Status::kOutOfOrderApiCall};
- }
-
- return current_->RequestConnection(client, endpoint_id, info, options);
-}
-
-Status PcpManager::AcceptConnection(ClientProxy* client,
- const string& endpoint_id,
- const PayloadListener& payload_listener) {
- if (!current_) {
- return {Status::kOutOfOrderApiCall};
- }
-
- return current_->AcceptConnection(client, endpoint_id, payload_listener);
-}
-
-Status PcpManager::RejectConnection(ClientProxy* client,
- const string& endpoint_id) {
- if (!current_) {
- return {Status::kOutOfOrderApiCall};
- }
-
- return current_->RejectConnection(client, endpoint_id);
-}
-
-bool PcpManager::SetCurrentPcpHandler(Strategy strategy) {
- current_ = GetPcpHandler(StrategyToPcp(strategy));
-
- if (!current_) {
- NEARBY_LOG(ERROR, "Failed to set current PCP handler: strategy=%s",
- strategy.GetName().c_str());
- }
-
- return current_;
-}
-
-PcpHandler* PcpManager::GetPcpHandler(Pcp pcp) const {
- auto item = handlers_.find(pcp);
- return item != handlers_.end() ? item->second.get() : nullptr;
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/pcp_manager.h b/chromium/third_party/nearby/src/cpp/core/internal/pcp_manager.h
deleted file mode 100644
index 5c8dd8a99ec..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/pcp_manager.h
+++ /dev/null
@@ -1,88 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_PCP_MANAGER_H_
-#define CORE_INTERNAL_PCP_MANAGER_H_
-
-#include <string>
-
-#include "absl/container/flat_hash_map.h"
-#include "core/internal/base_pcp_handler.h"
-#include "core/internal/bwu_manager.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/endpoint_channel_manager.h"
-#include "core/internal/endpoint_manager.h"
-#include "core/internal/injected_bluetooth_device_store.h"
-#include "core/internal/mediums/mediums.h"
-#include "core/listeners.h"
-#include "core/options.h"
-#include "core/status.h"
-#include "core/strategy.h"
-#include "platform/public/atomic_boolean.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Manages all known PcpHandler implementations, delegating operations to the
-// appropriate one as per the parameters passed in.
-//
-// This will only ever be used by the OfflineServiceController, which has all
-// of its entrypoints invoked serially, so there's no synchronization needed.
-// Public method semantics matches definition in the
-// cpp/core/internal/service_controller.h
-class PcpManager {
- public:
- PcpManager(Mediums& mediums, EndpointChannelManager& channel_manager,
- EndpointManager& endpoint_manager, BwuManager& bwu_manager,
- InjectedBluetoothDeviceStore& injected_bluetooth_device_store);
- ~PcpManager();
-
- Status StartAdvertising(ClientProxy* client, const string& service_id,
- const ConnectionOptions& options,
- const ConnectionRequestInfo& info);
- void StopAdvertising(ClientProxy* client);
-
- Status StartDiscovery(ClientProxy* client, const string& service_id,
- const ConnectionOptions& options,
- DiscoveryListener listener);
- void StopDiscovery(ClientProxy* client);
-
- void InjectEndpoint(ClientProxy* client, const std::string& service_id,
- const OutOfBandConnectionMetadata& metadata);
-
- Status RequestConnection(ClientProxy* client, const string& endpoint_id,
- const ConnectionRequestInfo& info,
- const ConnectionOptions& options);
- Status AcceptConnection(ClientProxy* client, const string& endpoint_id,
- const PayloadListener& payload_listener);
- Status RejectConnection(ClientProxy* client, const string& endpoint_id);
-
- proto::connections::Medium GetBandwidthUpgradeMedium();
- void DisconnectFromEndpointManager();
-
- private:
- bool SetCurrentPcpHandler(Strategy strategy);
- PcpHandler* GetPcpHandler(Pcp pcp) const;
-
- AtomicBoolean shutdown_{false};
- absl::flat_hash_map<Pcp, std::unique_ptr<BasePcpHandler>> handlers_;
- PcpHandler* current_ = nullptr;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_PCP_MANAGER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/pcp_manager_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/pcp_manager_test.cc
deleted file mode 100644
index fd703d1662a..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/pcp_manager_test.cc
+++ /dev/null
@@ -1,177 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/pcp_manager.h"
-
-#include <array>
-#include <string>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/time/time.h"
-#include "core/internal/endpoint_channel_manager.h"
-#include "core/internal/simulation_user.h"
-#include "core/options.h"
-#include "platform/base/medium_environment.h"
-#include "platform/public/count_down_latch.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-
-constexpr std::array<char, 6> kFakeMacAddress = {'a', 'b', 'c', 'd', 'e', 'f'};
-constexpr char kServiceId[] = "service-id";
-constexpr char kDeviceA[] = "device-A";
-constexpr char kDeviceB[] = "device-B";
-
-constexpr BooleanMediumSelector kTestCases[] = {
- BooleanMediumSelector{
- .bluetooth = true,
- },
- BooleanMediumSelector{
- .wifi_lan = true,
- },
- BooleanMediumSelector{
- .bluetooth = true,
- .wifi_lan = true,
- },
-};
-
-class PcpManagerTest : public ::testing::TestWithParam<BooleanMediumSelector> {
- protected:
- PcpManagerTest() { env_.Stop(); }
-
- MediumEnvironment& env_{MediumEnvironment::Instance()};
-};
-
-TEST_P(PcpManagerTest, CanCreateOne) {
- env_.Start();
- SimulationUser user(kDeviceA, GetParam());
- env_.Stop();
-}
-
-TEST_P(PcpManagerTest, CanCreateMany) {
- env_.Start();
- SimulationUser user_a(kDeviceA, GetParam());
- SimulationUser user_b(kDeviceB, GetParam());
- env_.Stop();
-}
-
-TEST_P(PcpManagerTest, CanAdvertise) {
- env_.Start();
- SimulationUser user_a(kDeviceA, GetParam());
- SimulationUser user_b(kDeviceB, GetParam());
- user_a.StartAdvertising(kServiceId, nullptr);
- env_.Stop();
-}
-
-TEST_P(PcpManagerTest, CanDiscover) {
- env_.Start();
- SimulationUser user_a("device-a", GetParam());
- SimulationUser user_b("device-b", GetParam());
- user_a.StartAdvertising(kServiceId, nullptr);
- CountDownLatch latch(1);
- user_b.StartDiscovery(kServiceId, &latch);
- EXPECT_TRUE(latch.Await(absl::Milliseconds(1000)).result());
- EXPECT_EQ(user_b.GetDiscovered().service_id, kServiceId);
- EXPECT_EQ(user_b.GetDiscovered().endpoint_info, user_a.GetInfo());
- env_.Stop();
-}
-
-TEST_P(PcpManagerTest, CanConnect) {
- env_.Start();
- SimulationUser user_a("device-a", GetParam());
- SimulationUser user_b("device-b", GetParam());
- CountDownLatch discovery_latch(1);
- CountDownLatch connection_latch(2);
- user_a.StartAdvertising(kServiceId, &connection_latch);
- user_b.StartDiscovery(kServiceId, &discovery_latch);
- EXPECT_TRUE(discovery_latch.Await(absl::Milliseconds(1000)).result());
- EXPECT_EQ(user_b.GetDiscovered().service_id, kServiceId);
- EXPECT_EQ(user_b.GetDiscovered().endpoint_info, user_a.GetInfo());
- user_b.RequestConnection(&connection_latch);
- EXPECT_TRUE(connection_latch.Await(absl::Milliseconds(1000)).result());
- user_a.Stop();
- user_b.Stop();
- env_.Stop();
-}
-
-TEST_P(PcpManagerTest, CanAccept) {
- env_.Start();
- SimulationUser user_a("device-a", GetParam());
- SimulationUser user_b("device-b", GetParam());
- CountDownLatch discovery_latch(1);
- CountDownLatch connection_latch(2);
- CountDownLatch accept_latch(2);
- user_a.StartAdvertising(kServiceId, &connection_latch);
- user_b.StartDiscovery(kServiceId, &discovery_latch);
- EXPECT_TRUE(discovery_latch.Await(absl::Milliseconds(1000)).result());
- EXPECT_EQ(user_b.GetDiscovered().service_id, kServiceId);
- EXPECT_EQ(user_b.GetDiscovered().endpoint_info, user_a.GetInfo());
- user_b.RequestConnection(&connection_latch);
- EXPECT_TRUE(connection_latch.Await(absl::Milliseconds(1000)).result());
- user_a.AcceptConnection(&accept_latch);
- user_b.AcceptConnection(&accept_latch);
- EXPECT_TRUE(accept_latch.Await(absl::Milliseconds(1000)).result());
- user_a.Stop();
- user_b.Stop();
- env_.Stop();
-}
-
-TEST_P(PcpManagerTest, CanReject) {
- env_.Start();
- SimulationUser user_a("device-a", GetParam());
- SimulationUser user_b("device-b", GetParam());
- CountDownLatch discovery_latch(1);
- CountDownLatch connection_latch(2);
- CountDownLatch reject_latch(1);
- user_a.StartAdvertising(kServiceId, &connection_latch);
- user_b.StartDiscovery(kServiceId, &discovery_latch);
- EXPECT_TRUE(discovery_latch.Await(absl::Milliseconds(1000)).result());
- EXPECT_EQ(user_b.GetDiscovered().service_id, kServiceId);
- EXPECT_EQ(user_b.GetDiscovered().endpoint_info, user_a.GetInfo());
- user_b.RequestConnection(&connection_latch);
- EXPECT_TRUE(connection_latch.Await(absl::Milliseconds(1000)).result());
- user_b.ExpectRejectedConnection(reject_latch);
- user_a.RejectConnection(nullptr);
- EXPECT_TRUE(reject_latch.Await(absl::Milliseconds(1000)).result());
- user_a.Stop();
- user_b.Stop();
- env_.Stop();
-}
-
-INSTANTIATE_TEST_SUITE_P(ParametrisedPcpManagerTest, PcpManagerTest,
- ::testing::ValuesIn(kTestCases));
-
-// Verifies that InjectEndpoint() can be run successfully; does not test the
-// full connection flow given that normal discovery/advertisement is skipped.
-// Note: Not parameterized because InjectEndpoint only works over Bluetooth.
-TEST_F(PcpManagerTest, InjectEndpoint) {
- env_.Start();
- SimulationUser user_a(kDeviceA, BooleanMediumSelector{.bluetooth = true});
- user_a.StartDiscovery(kServiceId, /*latch=*/nullptr);
- user_a.InjectEndpoint(kServiceId, OutOfBandConnectionMetadata{
- .medium = Medium::BLUETOOTH,
- .remote_bluetooth_mac_address =
- ByteArray(kFakeMacAddress),
- });
- user_a.Stop();
- env_.Stop();
-}
-
-} // namespace
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/service_controller.h b/chromium/third_party/nearby/src/cpp/core/internal/service_controller.h
deleted file mode 100644
index 1fa3f6466be..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/service_controller.h
+++ /dev/null
@@ -1,102 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_SERVICE_CONTROLLER_H_
-#define CORE_INTERNAL_SERVICE_CONTROLLER_H_
-
-#include <cstdint>
-#include <string>
-#include <vector>
-
-#include "core/internal/client_proxy.h"
-#include "core/listeners.h"
-#include "core/options.h"
-#include "core/params.h"
-#include "core/payload.h"
-#include "core/status.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Interface defines the core functionality of Nearby Connections Service.
-//
-// In every method, ClientProxy* represents the client app which receives
-// notifications from Nearby Connections service and forwards them to the app.
-// ResultCallback arguments are not provided for this class, because all methods
-// are called synchronously.
-// The rest of arguments have the same meaning as the corresponding
-// methods in the definition of location::nearby::Core API.
-//
-// See details here:
-// cpp/core/core.h
-class ServiceController {
- public:
- virtual ~ServiceController() = default;
- ServiceController() = default;
- ServiceController(const ServiceController&) = delete;
- ServiceController& operator=(const ServiceController&) = delete;
-
- // Stops and disables service controller.
- //
- // When service controller is stopped all API call fail early.
- // Note that all Core, ClientProxy objects referencing this service
- // controller are affected.
- virtual void Stop() = 0;
-
- // Starts advertising an endpoint for a local app.
- virtual Status StartAdvertising(ClientProxy* client,
- const std::string& service_id,
- const ConnectionOptions& options,
- const ConnectionRequestInfo& info) = 0;
- virtual void StopAdvertising(ClientProxy* client) = 0;
-
- virtual Status StartDiscovery(ClientProxy* client,
- const std::string& service_id,
- const ConnectionOptions& options,
- const DiscoveryListener& listener) = 0;
- virtual void StopDiscovery(ClientProxy* client) = 0;
-
- virtual void InjectEndpoint(ClientProxy* client,
- const std::string& service_id,
- const OutOfBandConnectionMetadata& metadata) = 0;
-
- virtual Status RequestConnection(ClientProxy* client,
- const std::string& endpoint_id,
- const ConnectionRequestInfo& info,
- const ConnectionOptions& options) = 0;
- virtual Status AcceptConnection(ClientProxy* client,
- const std::string& endpoint_id,
- const PayloadListener& listener) = 0;
- virtual Status RejectConnection(ClientProxy* client,
- const std::string& endpoint_id) = 0;
-
- virtual void InitiateBandwidthUpgrade(ClientProxy* client,
- const std::string& endpoint_id) = 0;
-
- virtual void SendPayload(ClientProxy* client,
- const std::vector<std::string>& endpoint_ids,
- Payload payload) = 0;
-
- virtual Status CancelPayload(ClientProxy* client, Payload::Id payload_id) = 0;
-
- virtual void DisconnectFromEndpoint(ClientProxy* client,
- const std::string& endpoint_id) = 0;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_SERVICE_CONTROLLER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/service_controller_router.cc b/chromium/third_party/nearby/src/cpp/core/internal/service_controller_router.cc
deleted file mode 100644
index 7c5eaffd0ac..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/service_controller_router.cc
+++ /dev/null
@@ -1,384 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/service_controller_router.h"
-
-#include <cstddef>
-#include <memory>
-#include <string>
-#include <utility>
-
-#include "absl/memory/memory.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/offline_service_controller.h"
-#include "core/listeners.h"
-#include "core/options.h"
-#include "core/params.h"
-#include "core/payload.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-// Length of a MAC address, which consists of 6 bytes uniquely identifying a
-// hardware interface.
-const std::size_t kMacAddressLength = 6u;
-
-// Length used for an endpoint ID, which identifies a device discovery and
-// associated connection request.
-const std::size_t kEndpointIdLength = 4u;
-
-// Maximum length for information describing an endpoint; this information is
-// advertised by one device and can be used by the other device to identify the
-// advertiser.
-const std::size_t kMaxEndpointInfoLength = 131u;
-
-bool ClientHasConnectionToAtLeastOneEndpoint(
- ClientProxy* client, const std::vector<std::string>& remote_endpoint_ids) {
- for (auto& endpoint_id : remote_endpoint_ids) {
- if (client->IsConnectedToEndpoint(endpoint_id)) {
- return true;
- }
- }
- return false;
-}
-} // namespace
-
-ServiceControllerRouter::ServiceControllerRouter() {
- NEARBY_LOGS(INFO) << "ServiceControllerRouter going up.";
-}
-
-ServiceControllerRouter::~ServiceControllerRouter() {
- NEARBY_LOGS(INFO) << "ServiceControllerRouter going down.";
-
- if (service_controller_) {
- service_controller_->Stop();
- }
- // And make sure that cleanup is the last thing we do.
- serializer_.Shutdown();
-}
-
-void ServiceControllerRouter::StartAdvertising(
- ClientProxy* client, absl::string_view service_id,
- const ConnectionOptions& options, const ConnectionRequestInfo& info,
- const ResultCallback& callback) {
- RouteToServiceController(
- "scr-start-advertising",
- [this, client, service_id = std::string(service_id), options, info,
- callback]() {
- if (client->IsAdvertising()) {
- callback.result_cb({Status::kAlreadyAdvertising});
- return;
- }
-
- callback.result_cb(GetServiceController()->StartAdvertising(
- client, service_id, options, info));
- });
-}
-
-void ServiceControllerRouter::StopAdvertising(ClientProxy* client,
- const ResultCallback& callback) {
- RouteToServiceController("scr-stop-advertising", [this, client, callback]() {
- if (client->IsAdvertising()) {
- GetServiceController()->StopAdvertising(client);
- }
- callback.result_cb({Status::kSuccess});
- });
-}
-
-void ServiceControllerRouter::StartDiscovery(ClientProxy* client,
- absl::string_view service_id,
- const ConnectionOptions& options,
- const DiscoveryListener& listener,
- const ResultCallback& callback) {
- RouteToServiceController(
- "scr-start-discovery",
- [this, client, service_id = std::string(service_id), options, listener,
- callback]() {
- if (client->IsDiscovering()) {
- callback.result_cb({Status::kAlreadyDiscovering});
- return;
- }
-
- callback.result_cb(GetServiceController()->StartDiscovery(
- client, service_id, options, listener));
- });
-}
-
-void ServiceControllerRouter::StopDiscovery(ClientProxy* client,
- const ResultCallback& callback) {
- RouteToServiceController("scr-stop-discovery", [this, client, callback]() {
- if (client->IsDiscovering()) {
- GetServiceController()->StopDiscovery(client);
- }
- callback.result_cb({Status::kSuccess});
- });
-}
-
-void ServiceControllerRouter::InjectEndpoint(
- ClientProxy* client, absl::string_view service_id,
- const OutOfBandConnectionMetadata& metadata,
- const ResultCallback& callback) {
- RouteToServiceController(
- "scr-inject-endpoint",
- [this, client, service_id = std::string(service_id), metadata,
- callback]() {
- // Currently, Bluetooth is the only supported medium for endpoint
- // injection.
- if (metadata.medium != Medium::BLUETOOTH ||
- metadata.remote_bluetooth_mac_address.size() != kMacAddressLength) {
- callback.result_cb({Status::kError});
- return;
- }
-
- if (metadata.endpoint_id.size() != kEndpointIdLength) {
- callback.result_cb({Status::kError});
- return;
- }
-
- if (metadata.endpoint_info.Empty() ||
- metadata.endpoint_info.size() > kMaxEndpointInfoLength) {
- callback.result_cb({Status::kError});
- return;
- }
-
- if (!client->IsDiscovering()) {
- callback.result_cb({Status::kOutOfOrderApiCall});
- return;
- }
-
- GetServiceController()->InjectEndpoint(client, service_id, metadata);
- callback.result_cb({Status::kSuccess});
- });
-}
-
-void ServiceControllerRouter::RequestConnection(
- ClientProxy* client, absl::string_view endpoint_id,
- const ConnectionRequestInfo& info, const ConnectionOptions& options,
- const ResultCallback& callback) {
- // Cancellations can be fired from clients anytime, need to add the
- // CancellationListener as soon as possible.
- client->AddCancellationFlag(std::string(endpoint_id));
-
- RouteToServiceController(
- "scr-request-connection",
- [this, client, endpoint_id = std::string(endpoint_id), info, options,
- callback]() {
- if (client->HasPendingConnectionToEndpoint(endpoint_id) ||
- client->IsConnectedToEndpoint(endpoint_id)) {
- callback.result_cb({Status::kAlreadyConnectedToEndpoint});
- return;
- }
-
- Status status = GetServiceController()->RequestConnection(
- client, endpoint_id, info, options);
- if (!status.Ok()) {
- client->CancelEndpoint(endpoint_id);
- }
- callback.result_cb(status);
- });
-}
-
-void ServiceControllerRouter::AcceptConnection(ClientProxy* client,
- absl::string_view endpoint_id,
- const PayloadListener& listener,
- const ResultCallback& callback) {
- RouteToServiceController(
- "scr-accept-connection",
- [this, client, endpoint_id = std::string(endpoint_id), listener,
- callback]() {
- if (client->IsConnectedToEndpoint(endpoint_id)) {
- callback.result_cb({Status::kAlreadyConnectedToEndpoint});
- return;
- }
-
- if (client->HasLocalEndpointResponded(endpoint_id)) {
- NEARBY_LOGS(WARNING)
- << "Client " << client->GetClientId()
- << " invoked acceptConnectionRequest() after having already "
- "accepted/rejected the connection to endpoint(id="
- << endpoint_id << ")";
- callback.result_cb({Status::kOutOfOrderApiCall});
- return;
- }
-
- callback.result_cb(GetServiceController()->AcceptConnection(
- client, endpoint_id, listener));
- });
-}
-
-void ServiceControllerRouter::RejectConnection(ClientProxy* client,
- absl::string_view endpoint_id,
- const ResultCallback& callback) {
- client->CancelEndpoint(std::string(endpoint_id));
-
- RouteToServiceController(
- "scr-reject-connection",
- [this, client, endpoint_id = std::string(endpoint_id), callback]() {
- if (client->IsConnectedToEndpoint(endpoint_id)) {
- callback.result_cb({Status::kAlreadyConnectedToEndpoint});
- return;
- }
-
- if (client->HasLocalEndpointResponded(endpoint_id)) {
- NEARBY_LOGS(WARNING)
- << "Client " << client->GetClientId()
- << " invoked rejectConnectionRequest() after having already "
- "accepted/rejected the connection to endpoint(id="
- << endpoint_id << ")";
- callback.result_cb({Status::kOutOfOrderApiCall});
- return;
- }
-
- callback.result_cb(
- GetServiceController()->RejectConnection(client, endpoint_id));
- });
-}
-
-void ServiceControllerRouter::InitiateBandwidthUpgrade(
- ClientProxy* client, absl::string_view endpoint_id,
- const ResultCallback& callback) {
- RouteToServiceController(
- "scr-init-bwu",
- [this, client, endpoint_id = std::string(endpoint_id), callback]() {
- if (!client->IsConnectedToEndpoint(endpoint_id)) {
- callback.result_cb({Status::kOutOfOrderApiCall});
- return;
- }
-
- GetServiceController()->InitiateBandwidthUpgrade(client, endpoint_id);
-
- // Operation is triggered; the caller can listen to
- // ConnectionListener::OnBandwidthChanged() to determine its success.
- callback.result_cb({Status::kSuccess});
- });
-}
-
-void ServiceControllerRouter::SendPayload(
- ClientProxy* client, absl::Span<const std::string> endpoint_ids,
- Payload payload, const ResultCallback& callback) {
- // Payload is a move-only type.
- // We have to capture it by value inside the lambda, and pass it over to
- // the executor as an std::function<void()> instance.
- // Lambda must be copyable, in order ot satisfy std::function<> requirements.
- // To make it so, we need Payload wrapped by a copyable wrapper.
- // std::shared_ptr<> is used, because it is copyable.
- auto shared_payload = std::make_shared<Payload>(std::move(payload));
- const std::vector<std::string> endpoints =
- std::vector<std::string>(endpoint_ids.begin(), endpoint_ids.end());
-
- RouteToServiceController("scr-send-payload", [this, client, shared_payload,
- endpoints, callback]() {
- if (!ClientHasConnectionToAtLeastOneEndpoint(client, endpoints)) {
- callback.result_cb({Status::kEndpointUnknown});
- return;
- }
-
- GetServiceController()->SendPayload(client, endpoints,
- std::move(*shared_payload));
-
- // At this point, we've queued up the send Payload request with the
- // ServiceController; any further failures (e.g. one of the endpoints is
- // unknown, goes away, or otherwise fails) will be returned to the
- // client as a PayloadTransferUpdate.
- callback.result_cb({Status::kSuccess});
- });
-}
-
-void ServiceControllerRouter::CancelPayload(ClientProxy* client,
- std::uint64_t payload_id,
- const ResultCallback& callback) {
- RouteToServiceController(
- "scr-cancel-payload", [this, client, payload_id, callback]() {
- callback.result_cb(
- GetServiceController()->CancelPayload(client, payload_id));
- });
-}
-
-void ServiceControllerRouter::DisconnectFromEndpoint(
- ClientProxy* client, absl::string_view endpoint_id,
- const ResultCallback& callback) {
- // Client can emit the cancellation at anytime, we need to execute the request
- // without further posting it.
- client->CancelEndpoint(std::string(endpoint_id));
-
- RouteToServiceController(
- "scr-disconnect-endpoint",
- [this, client, endpoint_id = std::string(endpoint_id), callback]() {
- if (!client->IsConnectedToEndpoint(endpoint_id) &&
- !client->HasPendingConnectionToEndpoint(endpoint_id)) {
- callback.result_cb({Status::kOutOfOrderApiCall});
- return;
- }
-
- GetServiceController()->DisconnectFromEndpoint(client, endpoint_id);
- callback.result_cb({Status::kSuccess});
- });
-}
-
-void ServiceControllerRouter::StopAllEndpoints(ClientProxy* client,
- const ResultCallback& callback) {
- // Client can emit the cancellation at anytime, we need to execute the request
- // without further posting it.
- client->CancelAllEndpoints();
-
- RouteToServiceController(
- "scr-stop-all-endpoints", [this, client, callback]() {
- NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
- << " has requested us to stop all endpoints. We will "
- "now reset the client.";
- FinishClientSession(client);
- callback.result_cb({Status::kSuccess});
- });
-}
-
-void ServiceControllerRouter::SetServiceControllerForTesting(
- std::unique_ptr<ServiceController> service_controller) {
- service_controller_ = std::move(service_controller);
-}
-
-ServiceController* ServiceControllerRouter::GetServiceController() {
- if (!service_controller_) {
- service_controller_ = std::make_unique<OfflineServiceController>();
- }
- return service_controller_.get();
-}
-
-void ServiceControllerRouter::FinishClientSession(ClientProxy* client) {
- // Disconnect from all the connected endpoints tied to this clientProxy.
- for (auto& endpoint_id : client->GetPendingConnectedEndpoints()) {
- GetServiceController()->DisconnectFromEndpoint(client, endpoint_id);
- }
-
- for (auto& endpoint_id : client->GetConnectedEndpoints()) {
- GetServiceController()->DisconnectFromEndpoint(client, endpoint_id);
- }
-
- // Stop any advertising and discovery that may be underway due to this client.
- GetServiceController()->StopAdvertising(client);
- GetServiceController()->StopDiscovery(client);
-
- // Finally, clear all state maintained by this client.
- client->Reset();
-}
-
-void ServiceControllerRouter::RouteToServiceController(const std::string& name,
- Runnable runnable) {
- serializer_.Execute(name, std::move(runnable));
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/service_controller_router.h b/chromium/third_party/nearby/src/cpp/core/internal/service_controller_router.h
deleted file mode 100644
index 54520ac2807..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/service_controller_router.h
+++ /dev/null
@@ -1,130 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_SERVICE_CONTROLLER_ROUTER_H_
-#define CORE_INTERNAL_SERVICE_CONTROLLER_ROUTER_H_
-
-#include <memory>
-#include <string>
-#include <vector>
-
-#include "absl/container/flat_hash_set.h"
-#include "absl/strings/string_view.h"
-#include "absl/types/span.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/service_controller.h"
-#include "core/options.h"
-#include "core/params.h"
-#include "platform/base/runnable.h"
-#include "platform/public/single_thread_executor.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// ServiceControllerRouter: this class is an implementation detail of a
-// location::nearby::Core class. The latter delegates all of its activities to
-// the former.
-//
-// All the activities are documented in the public API class:
-// cpp/core_v2/core.h
-//
-// In every method, ClientProxy* represents the client app which receives
-// notifications from Nearby Connections service and forwards them to the app.
-// The rest of arguments have the same meaning as the corresponding
-// methods in the definition of location::nearby::Core API.
-//
-// Every activity is handled the same way:
-// 1) all the arguments to the call are captured by value;
-// 2) the actual processing is scheduled on a private single-threaded executor,
-// which makes locking unnecessary, when internal data is being manipulated.
-// 3) activity handlers are delegating much of their work to an implementation
-// of a ServiceController interface, which does the actual job.
-class ServiceControllerRouter {
- public:
- ServiceControllerRouter();
- virtual ~ServiceControllerRouter();
- // Not copyable or movable
- ServiceControllerRouter(const ServiceControllerRouter&) = delete;
- ServiceControllerRouter& operator=(const ServiceControllerRouter&) = delete;
- ServiceControllerRouter(ServiceControllerRouter&&) = delete;
- ServiceControllerRouter& operator=(ServiceControllerRouter&&) = delete;
-
- virtual void StartAdvertising(ClientProxy* client,
- absl::string_view service_id,
- const ConnectionOptions& options,
- const ConnectionRequestInfo& info,
- const ResultCallback& callback);
- virtual void StopAdvertising(ClientProxy* client,
- const ResultCallback& callback);
-
- virtual void StartDiscovery(ClientProxy* client, absl::string_view service_id,
- const ConnectionOptions& options,
- const DiscoveryListener& listener,
- const ResultCallback& callback);
- virtual void StopDiscovery(ClientProxy* client,
- const ResultCallback& callback);
-
- virtual void InjectEndpoint(ClientProxy* client, absl::string_view service_id,
- const OutOfBandConnectionMetadata& metadata,
- const ResultCallback& callback);
-
- virtual void RequestConnection(ClientProxy* client,
- absl::string_view endpoint_id,
- const ConnectionRequestInfo& info,
- const ConnectionOptions& options,
- const ResultCallback& callback);
- virtual void AcceptConnection(ClientProxy* client,
- absl::string_view endpoint_id,
- const PayloadListener& listener,
- const ResultCallback& callback);
- virtual void RejectConnection(ClientProxy* client,
- absl::string_view endpoint_id,
- const ResultCallback& callback);
-
- virtual void InitiateBandwidthUpgrade(ClientProxy* client,
- absl::string_view endpoint_id,
- const ResultCallback& callback);
-
- virtual void SendPayload(ClientProxy* client,
- absl::Span<const std::string> endpoint_ids,
- Payload payload, const ResultCallback& callback);
- virtual void CancelPayload(ClientProxy* client, std::uint64_t payload_id,
- const ResultCallback& callback);
-
- virtual void DisconnectFromEndpoint(ClientProxy* client,
- absl::string_view endpoint_id,
- const ResultCallback& callback);
- virtual void StopAllEndpoints(ClientProxy* client,
- const ResultCallback& callback);
-
- void SetServiceControllerForTesting(
- std::unique_ptr<ServiceController> service_controller);
-
- private:
- // Lazily create ServiceController.
- ServiceController* GetServiceController();
-
- void RouteToServiceController(const std::string& name, Runnable runnable);
- void FinishClientSession(ClientProxy* client);
-
- std::unique_ptr<ServiceController> service_controller_;
- SingleThreadExecutor serializer_;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_SERVICE_CONTROLLER_ROUTER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/service_controller_router_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/service_controller_router_test.cc
deleted file mode 100644
index 74ed7c2c010..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/service_controller_router_test.cc
+++ /dev/null
@@ -1,421 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/service_controller_router.h"
-
-#include <array>
-#include <cinttypes>
-#include <memory>
-#include <string>
-#include <utility>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/container/flat_hash_set.h"
-#include "absl/time/clock.h"
-#include "absl/types/span.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/mock_service_controller.h"
-#include "core/internal/service_controller.h"
-#include "core/listeners.h"
-#include "core/options.h"
-#include "core/params.h"
-#include "platform/base/byte_array.h"
-#include "platform/public/condition_variable.h"
-#include "platform/public/mutex.h"
-#include "platform/public/mutex_lock.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-namespace {
-using ::testing::Return;
-constexpr std::array<char, 6> kFakeMacAddress = {'a', 'b', 'c', 'd', 'e', 'f'};
-constexpr std::array<char, 6> kFakeInjectedEndpointInfo = {'g', 'h', 'i'};
-const char kFakeInejctedEndpointId[] = "abcd";
-} // namespace
-
-// This class must be in the same namespace as ServiceControllerRouter for
-// friend class to work.
-class ServiceControllerRouterTest : public testing::Test {
- public:
- void SetUp() override {
- auto mock = std::make_unique<MockServiceController>();
- mock_ = mock.get();
- router_.SetServiceControllerForTesting(std::move(mock));
- }
-
- void StartAdvertising(ClientProxy* client, std::string service_id,
- ConnectionOptions options, ConnectionRequestInfo info,
- ResultCallback callback) {
- EXPECT_CALL(*mock_, StartAdvertising)
- .WillOnce(Return(Status{Status::kSuccess}));
- {
- MutexLock lock(&mutex_);
- complete_ = false;
- router_.StartAdvertising(client, service_id, options, info, callback);
- while (!complete_) cond_.Wait();
- EXPECT_EQ(result_, Status{Status::kSuccess});
- }
- client->StartedAdvertising(kServiceId, options.strategy, info.listener,
- absl::MakeSpan(mediums_));
- EXPECT_TRUE(client->IsAdvertising());
- }
-
- void StopAdvertising(ClientProxy* client, ResultCallback callback) {
- EXPECT_CALL(*mock_, StopAdvertising).Times(1);
- {
- MutexLock lock(&mutex_);
- complete_ = false;
- router_.StopAdvertising(client, callback);
- while (!complete_) cond_.Wait();
- }
- client->StoppedAdvertising();
- EXPECT_FALSE(client->IsAdvertising());
- }
-
- void StartDiscovery(ClientProxy* client, std::string service_id,
- ConnectionOptions options,
- const DiscoveryListener& listener,
- const ResultCallback& callback) {
- EXPECT_CALL(*mock_, StartDiscovery)
- .WillOnce(Return(Status{Status::kSuccess}));
- {
- MutexLock lock(&mutex_);
- complete_ = false;
- router_.StartDiscovery(client, kServiceId, options, listener, callback);
- while (!complete_) cond_.Wait();
- EXPECT_EQ(result_, Status{Status::kSuccess});
- }
- client->StartedDiscovery(service_id, options.strategy, listener,
- absl::MakeSpan(mediums_));
- EXPECT_TRUE(client->IsDiscovering());
- }
-
- void StopDiscovery(ClientProxy* client, ResultCallback callback) {
- EXPECT_CALL(*mock_, StopDiscovery).Times(1);
- {
- MutexLock lock(&mutex_);
- complete_ = false;
- router_.StopDiscovery(client, callback);
- while (!complete_) cond_.Wait();
- }
- client->StoppedDiscovery();
- EXPECT_FALSE(client->IsDiscovering());
- }
-
- void InjectEndpoint(ClientProxy* client, std::string service_id,
- const OutOfBandConnectionMetadata& metadata,
- ResultCallback callback) {
- EXPECT_CALL(*mock_, InjectEndpoint).Times(1);
- {
- MutexLock lock(&mutex_);
- complete_ = false;
- router_.InjectEndpoint(client, service_id, metadata, callback);
- while (!complete_) cond_.Wait();
- }
- }
-
- void RequestConnection(ClientProxy* client, const std::string& endpoint_id,
- const ConnectionRequestInfo& request_info,
- ResultCallback callback) {
- EXPECT_CALL(*mock_, RequestConnection)
- .WillOnce(Return(Status{Status::kSuccess}));
- ConnectionOptions options;
- {
- MutexLock lock(&mutex_);
- complete_ = false;
- router_.RequestConnection(client, endpoint_id, request_info, options,
- callback);
- while (!complete_) cond_.Wait();
- EXPECT_EQ(result_, Status{Status::kSuccess});
- }
- ConnectionResponseInfo response_info{
- .remote_endpoint_info = ByteArray{"endpoint_name"},
- .authentication_token = "auth_token",
- .raw_authentication_token = ByteArray{"auth_token"},
- .is_incoming_connection = true,
- };
- std::string connection_token{"conntokn"};
- client->OnConnectionInitiated(endpoint_id, response_info, options,
- request_info.listener, connection_token);
- EXPECT_TRUE(client->HasPendingConnectionToEndpoint(endpoint_id));
- }
-
- void AcceptConnection(ClientProxy* client, const std::string endpoint_id,
- const PayloadListener& listener,
- const ResultCallback& callback) {
- EXPECT_CALL(*mock_, AcceptConnection)
- .WillOnce(Return(Status{Status::kSuccess}));
- // Pre-condition for successful Accept is: connection must exist.
- EXPECT_TRUE(client->HasPendingConnectionToEndpoint(endpoint_id));
- {
- MutexLock lock(&mutex_);
- complete_ = false;
- router_.AcceptConnection(client, endpoint_id, listener, callback);
- while (!complete_) cond_.Wait();
- EXPECT_EQ(result_, Status{Status::kSuccess});
- }
- client->LocalEndpointAcceptedConnection(endpoint_id, listener);
- client->RemoteEndpointAcceptedConnection(endpoint_id);
- EXPECT_TRUE(client->IsConnectionAccepted(endpoint_id));
- client->OnConnectionAccepted(endpoint_id);
- EXPECT_TRUE(client->IsConnectedToEndpoint(endpoint_id));
- }
-
- void RejectConnection(ClientProxy* client, const std::string endpoint_id,
- ResultCallback callback) {
- EXPECT_CALL(*mock_, RejectConnection)
- .WillOnce(Return(Status{Status::kSuccess}));
- // Pre-condition for successful Accept is: connection must exist.
- EXPECT_TRUE(client->HasPendingConnectionToEndpoint(endpoint_id));
- {
- MutexLock lock(&mutex_);
- complete_ = false;
- router_.RejectConnection(client, endpoint_id, callback);
- while (!complete_) cond_.Wait();
- EXPECT_EQ(result_, Status{Status::kSuccess});
- }
- client->LocalEndpointRejectedConnection(endpoint_id);
- EXPECT_TRUE(client->IsConnectionRejected(endpoint_id));
- }
-
- void InitiateBandwidthUpgrade(ClientProxy* client,
- const std::string endpoint_id,
- ResultCallback callback) {
- EXPECT_CALL(*mock_, InitiateBandwidthUpgrade).Times(1);
- EXPECT_TRUE(client->IsConnectedToEndpoint(endpoint_id));
- {
- MutexLock lock(&mutex_);
- complete_ = false;
- router_.InitiateBandwidthUpgrade(client, endpoint_id, callback);
- while (!complete_) cond_.Wait();
- EXPECT_EQ(result_, Status{Status::kSuccess});
- }
- }
-
- void SendPayload(ClientProxy* client,
- const std::vector<std::string>& endpoint_ids,
- Payload payload, ResultCallback callback) {
- EXPECT_CALL(*mock_, SendPayload).Times(1);
-
- bool connected = false;
- for (const auto& endpoint_id : endpoint_ids) {
- connected = connected || client->IsConnectedToEndpoint(endpoint_id);
- }
- EXPECT_TRUE(connected);
- {
- MutexLock lock(&mutex_);
- complete_ = false;
- router_.SendPayload(client, absl::MakeSpan(endpoint_ids),
- std::move(payload), callback);
- while (!complete_) cond_.Wait();
- EXPECT_EQ(result_, Status{Status::kSuccess});
- }
- }
-
- void CancelPayload(ClientProxy* client, std::int64_t payload_id,
- ResultCallback callback) {
- EXPECT_CALL(*mock_, CancelPayload)
- .WillOnce(Return(Status{Status::kSuccess}));
- {
- MutexLock lock(&mutex_);
- complete_ = false;
- router_.CancelPayload(client, payload_id, callback);
- while (!complete_) cond_.Wait();
- EXPECT_EQ(result_, Status{Status::kSuccess});
- }
- }
-
- void DisconnectFromEndpoint(ClientProxy* client,
- const std::string endpoint_id,
- ResultCallback callback) {
- EXPECT_CALL(*mock_, DisconnectFromEndpoint).Times(1);
- EXPECT_TRUE(client->IsConnectedToEndpoint(endpoint_id));
- {
- MutexLock lock(&mutex_);
- complete_ = false;
- router_.DisconnectFromEndpoint(client, endpoint_id, callback);
- while (!complete_) cond_.Wait();
- }
- client->OnDisconnected(endpoint_id, false);
- EXPECT_FALSE(client->IsConnectedToEndpoint(endpoint_id));
- }
-
- protected:
- const ResultCallback kCallback{
- .result_cb =
- [this](Status status) {
- MutexLock lock(&mutex_);
- result_ = status;
- complete_ = true;
- cond_.Notify();
- },
- };
- const std::string kServiceId = "service id";
- const std::string kRequestorName = "requestor name";
- const std::string kRemoteEndpointId = "remote endpoint id";
- const std::int64_t kPayloadId = UINT64_C(0x123456789ABCDEF0);
- const ConnectionOptions kConnectionOptions{
- .strategy = Strategy::kP2pPointToPoint,
- .auto_upgrade_bandwidth = true,
- .enforce_topology_constraints = true,
- };
- const OutOfBandConnectionMetadata kOutOfBandConnectionMetadata{
- .medium = Medium::BLUETOOTH,
- .endpoint_id = kFakeInejctedEndpointId,
- .endpoint_info = ByteArray(kFakeInjectedEndpointInfo),
- .remote_bluetooth_mac_address = ByteArray(kFakeMacAddress),
- };
-
- std::vector<proto::connections::Medium> mediums_{
- proto::connections::Medium::BLUETOOTH};
- const ConnectionRequestInfo kConnectionRequestInfo{
- .endpoint_info = ByteArray{kRequestorName},
- .listener = ConnectionListener(),
- };
-
- DiscoveryListener discovery_listener_;
- PayloadListener payload_listener_;
-
- Mutex mutex_;
- ConditionVariable cond_{&mutex_};
- Status result_ ABSL_GUARDED_BY(mutex_) = {Status::kError};
- bool complete_ ABSL_GUARDED_BY(mutex_) = false;
- MockServiceController* mock_;
- ClientProxy client_;
-
- ServiceControllerRouter router_;
-};
-
-namespace {
-TEST_F(ServiceControllerRouterTest, StartAdvertisingCalled) {
- StartAdvertising(&client_, kServiceId, kConnectionOptions,
- kConnectionRequestInfo, kCallback);
-}
-
-TEST_F(ServiceControllerRouterTest, StopAdvertisingCalled) {
- StartAdvertising(&client_, kServiceId, kConnectionOptions,
- kConnectionRequestInfo, kCallback);
- StopAdvertising(&client_, kCallback);
-}
-
-TEST_F(ServiceControllerRouterTest, StartDiscoveryCalled) {
- StartDiscovery(&client_, kServiceId, kConnectionOptions, discovery_listener_,
- kCallback);
-}
-
-TEST_F(ServiceControllerRouterTest, StopDiscoveryCalled) {
- StartDiscovery(&client_, kServiceId, kConnectionOptions, discovery_listener_,
- kCallback);
- StopDiscovery(&client_, kCallback);
-}
-
-TEST_F(ServiceControllerRouterTest, InjectEndpointCalled) {
- StartDiscovery(&client_, kServiceId, kConnectionOptions, discovery_listener_,
- kCallback);
- InjectEndpoint(&client_, kServiceId, kOutOfBandConnectionMetadata, kCallback);
- StopDiscovery(&client_, kCallback);
-}
-
-TEST_F(ServiceControllerRouterTest, RequestConnectionCalled) {
- // Either Advertising, or Discovery should be ongoing.
- StartDiscovery(&client_, kServiceId, kConnectionOptions, discovery_listener_,
- kCallback);
- RequestConnection(&client_, kRemoteEndpointId, kConnectionRequestInfo,
- kCallback);
-}
-
-TEST_F(ServiceControllerRouterTest, AcceptConnectionCalled) {
- // Either Adviertisng, or Discovery should be ongoing.
- StartDiscovery(&client_, kServiceId, kConnectionOptions, discovery_listener_,
- kCallback);
- // Establish connection.
- RequestConnection(&client_, kRemoteEndpointId, kConnectionRequestInfo,
- kCallback);
- // Now, we can accept connection.
- AcceptConnection(&client_, kRemoteEndpointId, payload_listener_, kCallback);
-}
-
-TEST_F(ServiceControllerRouterTest, RejectConnectionCalled) {
- // Either Adviertisng, or Discovery should be ongoing.
- StartDiscovery(&client_, kServiceId, kConnectionOptions, discovery_listener_,
- kCallback);
- // Establish connection.
- RequestConnection(&client_, kRemoteEndpointId, kConnectionRequestInfo,
- kCallback);
- // Now, we can reject connection.
- RejectConnection(&client_, kRemoteEndpointId, kCallback);
-}
-
-TEST_F(ServiceControllerRouterTest, InitiateBandwidthUpgradeCalled) {
- // Either Adviertisng, or Discovery should be ongoing.
- StartDiscovery(&client_, kServiceId, kConnectionOptions, discovery_listener_,
- kCallback);
- // Establish connection.
- RequestConnection(&client_, kRemoteEndpointId, kConnectionRequestInfo,
- kCallback);
- // Now, we can accept connection.
- AcceptConnection(&client_, kRemoteEndpointId, payload_listener_, kCallback);
- // Now we can change connection bandwidth.
- InitiateBandwidthUpgrade(&client_, kRemoteEndpointId, kCallback);
-}
-
-TEST_F(ServiceControllerRouterTest, SendPayloadCalled) {
- // Either Adviertisng, or Discovery should be ongoing.
- StartDiscovery(&client_, kServiceId, kConnectionOptions, discovery_listener_,
- kCallback);
- // Establish connection.
- RequestConnection(&client_, kRemoteEndpointId, kConnectionRequestInfo,
- kCallback);
- // Now, we can accept connection.
- AcceptConnection(&client_, kRemoteEndpointId, payload_listener_, kCallback);
- // Now we can send payload.
- SendPayload(&client_, std::vector<std::string>{kRemoteEndpointId},
- Payload{ByteArray("data")}, kCallback);
-}
-
-TEST_F(ServiceControllerRouterTest, CancelPayloadCalled) {
- // Either Adviertisng, or Discovery should be ongoing.
- StartDiscovery(&client_, kServiceId, kConnectionOptions, discovery_listener_,
- kCallback);
- // Establish connection.
- RequestConnection(&client_, kRemoteEndpointId, kConnectionRequestInfo,
- kCallback);
- // Now, we can accept connection.
- AcceptConnection(&client_, kRemoteEndpointId, payload_listener_, kCallback);
- // We have to know payload id, before we can cancel payload transfer.
- // It is either after a call to SendPayload, or after receiving
- // PayloadProgress callback. Let's assume we have it, and proceed.
- CancelPayload(&client_, kPayloadId, kCallback);
-}
-
-TEST_F(ServiceControllerRouterTest, DisconnectFromEndpointCalled) {
- // Either Adviertisng, or Discovery should be ongoing.
- StartDiscovery(&client_, kServiceId, kConnectionOptions, discovery_listener_,
- kCallback);
- // Establish connection.
- RequestConnection(&client_, kRemoteEndpointId, kConnectionRequestInfo,
- kCallback);
- // Now, we can accept connection.
- AcceptConnection(&client_, kRemoteEndpointId, payload_listener_, kCallback);
- // We can disconnect at any time after RequestConnection.
- DisconnectFromEndpoint(&client_, kRemoteEndpointId, kCallback);
-}
-
-} // namespace
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/simulation_user.cc b/chromium/third_party/nearby/src/cpp/core/internal/simulation_user.cc
deleted file mode 100644
index afeab13404b..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/simulation_user.cc
+++ /dev/null
@@ -1,181 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/simulation_user.h"
-
-#include "absl/functional/bind_front.h"
-#include "core/listeners.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/system_clock.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-void SimulationUser::OnConnectionInitiated(const std::string& endpoint_id,
- const ConnectionResponseInfo& info,
- bool is_outgoing) {
- if (is_outgoing) {
- NEARBY_LOG(INFO, "RequestConnection: initiated_cb called");
- } else {
- NEARBY_LOG(INFO, "StartAdvertising: initiated_cb called");
- discovered_ = DiscoveredInfo{
- .endpoint_id = endpoint_id,
- .endpoint_info = GetInfo(),
- .service_id = service_id_,
- };
- }
- if (initiated_latch_) initiated_latch_->CountDown();
-}
-
-void SimulationUser::OnConnectionAccepted(const std::string& endpoint_id) {
- if (accept_latch_) accept_latch_->CountDown();
-}
-
-void SimulationUser::OnConnectionRejected(const std::string& endpoint_id,
- Status status) {
- if (reject_latch_) reject_latch_->CountDown();
-}
-
-void SimulationUser::OnEndpointFound(const std::string& endpoint_id,
- const ByteArray& endpoint_info,
- const std::string& service_id) {
- NEARBY_LOG(INFO, "Device discovered: id=%s", endpoint_id.c_str());
- discovered_ = DiscoveredInfo{
- .endpoint_id = endpoint_id,
- .endpoint_info = endpoint_info,
- .service_id = service_id,
- };
- if (found_latch_) found_latch_->CountDown();
-}
-
-void SimulationUser::OnEndpointLost(const std::string& endpoint_id) {
- if (lost_latch_) lost_latch_->CountDown();
-}
-
-void SimulationUser::OnPayload(const std::string& endpoint_id,
- Payload payload) {
- payload_ = std::move(payload);
- if (payload_latch_) payload_latch_->CountDown();
-}
-
-void SimulationUser::OnPayloadProgress(const std::string& endpoint_id,
- const PayloadProgressInfo& info) {
- MutexLock lock(&progress_mutex_);
- progress_info_ = info;
- if (future_ && predicate_ && predicate_(info)) future_->Set(true);
-}
-
-bool SimulationUser::WaitForProgress(
- std::function<bool(const PayloadProgressInfo&)> predicate,
- absl::Duration timeout) {
- Future<bool> future;
- {
- MutexLock lock(&progress_mutex_);
- if (predicate(progress_info_)) return true;
- future_ = &future;
- predicate_ = std::move(predicate);
- }
- auto response = future.Get(timeout);
- {
- MutexLock lock(&progress_mutex_);
- future_ = nullptr;
- predicate_ = nullptr;
- }
- return response.ok() && response.result();
-}
-
-void SimulationUser::StartAdvertising(const std::string& service_id,
- CountDownLatch* latch) {
- initiated_latch_ = latch;
- service_id_ = service_id;
- ConnectionListener listener = {
- .initiated_cb =
- std::bind(&SimulationUser::OnConnectionInitiated, this,
- std::placeholders::_1, std::placeholders::_2, false),
- .accepted_cb =
- absl::bind_front(&SimulationUser::OnConnectionAccepted, this),
- .rejected_cb =
- absl::bind_front(&SimulationUser::OnConnectionRejected, this),
- };
- EXPECT_TRUE(mgr_.StartAdvertising(&client_, service_id_, options_,
- {
- .endpoint_info = info_,
- .listener = std::move(listener),
- })
- .Ok());
-}
-
-void SimulationUser::StartDiscovery(const std::string& service_id,
- CountDownLatch* latch) {
- found_latch_ = latch;
- EXPECT_TRUE(
- mgr_.StartDiscovery(&client_, service_id, options_,
- {
- .endpoint_found_cb = absl::bind_front(
- &SimulationUser::OnEndpointFound, this),
- .endpoint_lost_cb = absl::bind_front(
- &SimulationUser::OnEndpointLost, this),
- })
- .Ok());
-}
-
-void SimulationUser::InjectEndpoint(
- const std::string& service_id,
- const OutOfBandConnectionMetadata& metadata) {
- mgr_.InjectEndpoint(&client_, service_id, metadata);
-}
-
-void SimulationUser::RequestConnection(CountDownLatch* latch) {
- initiated_latch_ = latch;
- ConnectionListener listener = {
- .initiated_cb =
- std::bind(&SimulationUser::OnConnectionInitiated, this,
- std::placeholders::_1, std::placeholders::_2, true),
- .accepted_cb =
- absl::bind_front(&SimulationUser::OnConnectionAccepted, this),
- .rejected_cb =
- absl::bind_front(&SimulationUser::OnConnectionRejected, this),
- };
- client_.AddCancellationFlag(discovered_.endpoint_id);
- EXPECT_TRUE(
- mgr_.RequestConnection(&client_, discovered_.endpoint_id,
- {
- .endpoint_info = discovered_.endpoint_info,
- .listener = std::move(listener),
- },
- connection_options_)
- .Ok());
-}
-
-void SimulationUser::AcceptConnection(CountDownLatch* latch) {
- accept_latch_ = latch;
- PayloadListener listener = {
- .payload_cb = absl::bind_front(&SimulationUser::OnPayload, this),
- .payload_progress_cb =
- absl::bind_front(&SimulationUser::OnPayloadProgress, this),
- };
- EXPECT_TRUE(mgr_.AcceptConnection(&client_, discovered_.endpoint_id,
- std::move(listener))
- .Ok());
-}
-
-void SimulationUser::RejectConnection(CountDownLatch* latch) {
- reject_latch_ = latch;
- EXPECT_TRUE(mgr_.RejectConnection(&client_, discovered_.endpoint_id).Ok());
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/simulation_user.h b/chromium/third_party/nearby/src/cpp/core/internal/simulation_user.h
deleted file mode 100644
index 6e62a6be6fb..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/simulation_user.h
+++ /dev/null
@@ -1,172 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_SIMULATION_USER_H_
-#define CORE_INTERNAL_SIMULATION_USER_H_
-
-#include <string>
-
-#include "gtest/gtest.h"
-#include "core/internal/bwu_manager.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/endpoint_channel_manager.h"
-#include "core/internal/endpoint_manager.h"
-#include "core/internal/injected_bluetooth_device_store.h"
-#include "core/internal/payload_manager.h"
-#include "core/internal/pcp_manager.h"
-#include "core/options.h"
-#include "platform/base/medium_environment.h"
-#include "platform/public/condition_variable.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/future.h"
-
-// Test-only class to help run end-to-end simulations for nearby connections
-// protocol.
-//
-// This is a "standalone" version of PcpManager. It can run independently,
-// provided MediumEnvironment has adequate support for all medium types in use.
-namespace location {
-namespace nearby {
-namespace connections {
-
-class SimulationUser {
- public:
- struct DiscoveredInfo {
- std::string endpoint_id;
- ByteArray endpoint_info;
- std::string service_id;
-
- bool Empty() const { return endpoint_id.empty(); }
- void Clear() { endpoint_id.clear(); }
- };
-
- explicit SimulationUser(
- const std::string& device_name,
- BooleanMediumSelector allowed = BooleanMediumSelector())
- : connection_options_{
- .keep_alive_interval_millis = FeatureFlags::GetInstance()
- .GetFlags()
- .keep_alive_interval_millis,
- .keep_alive_timeout_millis = FeatureFlags::GetInstance()
- .GetFlags()
- .keep_alive_timeout_millis,
- },
- info_{ByteArray{device_name}},
- options_{
- .strategy = Strategy::kP2pCluster,
- .allowed = allowed,
- } {}
- virtual ~SimulationUser() { Stop(); }
- void Stop() {
- pm_.DisconnectFromEndpointManager();
- mgr_.DisconnectFromEndpointManager();
- bwu_.Shutdown();
- }
-
- // Calls PcpManager::StartAdvertising.
- // If latch is provided, will call latch->CountDown() in the initiated_cb
- // callback.
- void StartAdvertising(const std::string& service_id, CountDownLatch* latch);
-
- // Calls PcpManager::StartDiscovery.
- // If latch is provided, will call latch->CountDown() in the endpoint_found_cb
- // callback.
- void StartDiscovery(const std::string& service_id, CountDownLatch* latch);
-
- // Calls PcpManager::InjectEndpoint.
- void InjectEndpoint(const std::string& service_id,
- const OutOfBandConnectionMetadata& metadata);
-
- // Calls PcpManager::RequestConnection.
- // If latch is provided, latch->CountDown() will be called in the initiated_cb
- // callback.
- void RequestConnection(CountDownLatch* latch);
-
- // Calls PcpManager::AcceptConnection.
- // If latch is provided, latch->CountDown() will be called in the accepted_cb
- // callback.
- void AcceptConnection(CountDownLatch* latch);
-
- // Calls PcpManager::RejectConnection.
- // If latch is provided, latch->CountDown() will be called in the rejected_cb
- // callback.
- void RejectConnection(CountDownLatch* latch);
-
- // Unlike acceptance, rejection does not have to be mutual, in order to work.
- // This method will allow to synchronize on the remote rejection, without
- // performing a local rejection.
- // latch.CountDown() will be called in the rejected_cb callback.
- void ExpectRejectedConnection(CountDownLatch& latch) {
- reject_latch_ = &latch;
- }
-
- void ExpectPayload(CountDownLatch& latch) { payload_latch_ = &latch; }
-
- const DiscoveredInfo& GetDiscovered() const { return discovered_; }
- ByteArray GetInfo() const { return info_; }
-
- bool WaitForProgress(std::function<bool(const PayloadProgressInfo&)> pred,
- absl::Duration timeout);
-
- protected:
- // ConnectionListener callbacks
- void OnConnectionInitiated(const std::string& endpoint_id,
- const ConnectionResponseInfo& info,
- bool is_outgoing);
- void OnConnectionAccepted(const std::string& endpoint_id);
- void OnConnectionRejected(const std::string& endpoint_id, Status status);
-
- // DiscoveryListener callbacks
- void OnEndpointFound(const std::string& endpoint_id,
- const ByteArray& endpoint_info,
- const std::string& service_id);
- void OnEndpointLost(const std::string& endpoint_id);
-
- // PayloadListener callbacks
- void OnPayload(const std::string& endpoint_id, Payload payload);
- void OnPayloadProgress(const std::string& endpoint_id,
- const PayloadProgressInfo& info);
-
- std::string service_id_;
- DiscoveredInfo discovered_;
- ConnectionOptions connection_options_;
- Mutex progress_mutex_;
- ConditionVariable progress_sync_{&progress_mutex_};
- PayloadProgressInfo progress_info_;
- Payload payload_;
- CountDownLatch* initiated_latch_ = nullptr;
- CountDownLatch* accept_latch_ = nullptr;
- CountDownLatch* reject_latch_ = nullptr;
- CountDownLatch* found_latch_ = nullptr;
- CountDownLatch* lost_latch_ = nullptr;
- CountDownLatch* payload_latch_ = nullptr;
- Future<bool>* future_ = nullptr;
- std::function<bool(const PayloadProgressInfo&)> predicate_;
- ByteArray info_;
- Mediums mediums_;
- ConnectionOptions options_;
- ClientProxy client_;
- EndpointChannelManager ecm_;
- EndpointManager em_{&ecm_};
- BwuManager bwu_{mediums_, em_, ecm_, {}, {}};
- InjectedBluetoothDeviceStore injected_bluetooth_device_store_;
- PcpManager mgr_{mediums_, ecm_, em_, bwu_, injected_bluetooth_device_store_};
- PayloadManager pm_{em_};
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_SIMULATION_USER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/webrtc_bwu_handler.cc b/chromium/third_party/nearby/src/cpp/core/internal/webrtc_bwu_handler.cc
deleted file mode 100644
index c3b536de0a9..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/webrtc_bwu_handler.cc
+++ /dev/null
@@ -1,167 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/webrtc_bwu_handler.h"
-
-#include <string>
-
-#include "absl/functional/bind_front.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/mediums/utils.h"
-#include "core/internal/mediums/webrtc_peer_id.h"
-#include "core/internal/offline_frames.h"
-#include "core/internal/webrtc_endpoint_channel.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-WebrtcBwuHandler::WebrtcBwuHandler(Mediums& mediums,
- EndpointChannelManager& channel_manager,
- BwuNotifications notifications)
- : BaseBwuHandler(channel_manager, std::move(notifications)),
- mediums_(mediums) {}
-
-void WebrtcBwuHandler::Revert() {
- for (const auto& service_id : active_service_ids_) {
- webrtc_.StopAcceptingConnections(service_id);
- }
- active_service_ids_.clear();
-
- NEARBY_LOG(INFO, "WebrtcBwuHandler successfully reverted state.");
-}
-
-// Accept Connection Callback.
-// Notifies that the remote party called WebRtc::Connect()
-// for this socket.
-void WebrtcBwuHandler::OnIncomingWebrtcConnection(
- ClientProxy* client, const std::string& upgrade_service_id,
- mediums::WebRtcSocketWrapper socket) {
- std::string service_id = Utils::UnwrapUpgradeServiceId(upgrade_service_id);
- auto channel = std::make_unique<WebRtcEndpointChannel>(service_id, socket);
- auto webrtc_socket =
- std::make_unique<WebrtcIncomingSocket>(service_id, socket);
- std::unique_ptr<IncomingSocketConnection> connection(
- new IncomingSocketConnection{std::move(webrtc_socket),
- std::move(channel)});
-
- bwu_notifications_.incoming_connection_cb(client, std::move(connection));
-}
-
-// Called by BWU initiator. Set up WebRTC upgraded medium for this endpoint,
-// and returns a upgrade path info (PeerId, LocationHint) for remote party to
-// perform discovery.
-ByteArray WebrtcBwuHandler::InitializeUpgradedMediumForEndpoint(
- ClientProxy* client, const std::string& service_id,
- const std::string& endpoint_id) {
- // Use wrapped service ID to avoid have the same ID with the one for
- // startAdvertising. Otherwise, the listening request would be ignored because
- // the medium already start accepting the connection because the client not
- // stop the advertising yet.
- std::string upgrade_service_id = Utils::WrapUpgradeServiceId(service_id);
-
- LocationHint location_hint =
- Utils::BuildLocationHint(webrtc_.GetDefaultCountryCode());
-
- mediums::WebrtcPeerId self_id{mediums::WebrtcPeerId::FromRandom()};
- if (!webrtc_.IsAcceptingConnections(service_id)) {
- if (!webrtc_.StartAcceptingConnections(
- upgrade_service_id, self_id, location_hint,
- {
- .accepted_cb = absl::bind_front(
- &WebrtcBwuHandler::OnIncomingWebrtcConnection, this, client,
- upgrade_service_id),
- })) {
- NEARBY_LOG(ERROR,
- "WebRtcBwuHandler couldn't initiate the WEB_RTC upgrade for "
- "endpoint %s because it failed to start listening for "
- "incoming WebRTC connections.",
- endpoint_id.c_str());
- return {};
- }
- NEARBY_LOG(INFO,
- "WebRtcBwuHandler successfully started listening for incoming "
- "WebRTC connections while upgrading endpoint %s",
- endpoint_id.c_str());
- }
-
- // cache service ID to revert
- active_service_ids_.emplace(upgrade_service_id);
-
- return parser::ForBwuWebrtcPathAvailable(self_id.GetId(), location_hint);
-}
-
-// Called by BWU target. Retrieves a new medium info from incoming message,
-// and establishes connection over WebRTC using this info.
-std::unique_ptr<EndpointChannel>
-WebrtcBwuHandler::CreateUpgradedEndpointChannel(
- ClientProxy* client, const std::string& service_id,
- const std::string& endpoint_id, const UpgradePathInfo& upgrade_path_info) {
- const UpgradePathInfo::WebRtcCredentials& web_rtc_credentials =
- upgrade_path_info.web_rtc_credentials();
- mediums::WebrtcPeerId peer_id(web_rtc_credentials.peer_id());
-
- LocationHint location_hint;
- location_hint.set_format(LocationStandard::UNKNOWN);
- if (web_rtc_credentials.has_location_hint()) {
- location_hint = web_rtc_credentials.location_hint();
- }
- NEARBY_LOG(INFO,
- "WebRtcBwuHandler is attempting to connect to remote peer %s, "
- "location hint %s",
- peer_id.GetId().c_str(), location_hint.DebugString().c_str());
-
- mediums::WebRtcSocketWrapper socket =
- webrtc_.Connect(service_id, peer_id, location_hint,
- client->GetCancellationFlag(endpoint_id));
- if (!socket.IsValid()) {
- NEARBY_LOG(ERROR,
- "WebRtcBwuHandler failed to connect to remote peer (%s) on "
- "endpoint %s, aborting upgrade.",
- peer_id.GetId().c_str(), endpoint_id.c_str());
- return nullptr;
- }
-
- NEARBY_LOG(INFO,
- "WebRtcBwuHandler successfully connected to remote "
- "peer (%s) while upgrading endpoint %s.",
- peer_id.GetId().c_str(), endpoint_id.c_str());
-
- // Create a new WebRtcEndpointChannel.
- auto channel = std::make_unique<WebRtcEndpointChannel>(service_id, socket);
- if (channel == nullptr) {
- socket.Close();
- NEARBY_LOG(ERROR,
- "WebRtcBwuHandler failed to create new EndpointChannel for "
- "outgoing socket %p, aborting upgrade.",
- &socket.GetImpl());
- }
-
- return channel;
-}
-
-void WebrtcBwuHandler::OnEndpointDisconnect(ClientProxy* client,
- const std::string& endpoint_id) {}
-
-WebrtcBwuHandler::WebrtcIncomingSocket::WebrtcIncomingSocket(
- const std::string& name, mediums::WebRtcSocketWrapper socket)
- : name_(name), socket_(socket) {}
-
-void WebrtcBwuHandler::WebrtcIncomingSocket::Close() { socket_.Close(); }
-
-std::string WebrtcBwuHandler::WebrtcIncomingSocket::ToString() { return name_; }
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/webrtc_bwu_handler.h b/chromium/third_party/nearby/src/cpp/core/internal/webrtc_bwu_handler.h
deleted file mode 100644
index 6587b643e2b..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/webrtc_bwu_handler.h
+++ /dev/null
@@ -1,95 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_WEBRTC_BWU_HANDLER_H_
-#define CORE_INTERNAL_WEBRTC_BWU_HANDLER_H_
-
-#include "core/internal/base_bwu_handler.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/endpoint_channel_manager.h"
-#include "core/internal/mediums/mediums.h"
-#include "core/internal/mediums/webrtc_socket_wrapper.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-using BwuNegotiationFrame = BandwidthUpgradeNegotiationFrame;
-
-// Defines the set of methods that need to be implemented to handle the
-// per-Medium-specific operations needed to upgrade an EndpointChannel.
-class WebrtcBwuHandler : public BaseBwuHandler {
- public:
- WebrtcBwuHandler(Mediums& mediums, EndpointChannelManager& channel_manager,
- BwuNotifications notifications);
- ~WebrtcBwuHandler() override = default;
-
- private:
- // Called by the Initiator to setup the upgraded medium for this endpoint (if
- // that hasn't already been done), and returns a serialized UpgradePathInfo
- // that can be sent to the Responder.
- // @BwuHandlerThread
- ByteArray InitializeUpgradedMediumForEndpoint(
- ClientProxy* client, const std::string& service_id,
- const std::string& endpoint_id) override;
- // Called to revert any state changed by the Initiator to setup the upgraded
- // medium for an endpoint.
- // @BwuHandlerThread
- void Revert() override;
-
- // Called by the Responder to setup the upgraded medium for this endpoint (if
- // that hasn't already been done) using the UpgradePathInfo sent by the
- // Initiator, and returns a new EndpointChannel for the upgraded medium.
- // @BwuHandlerThread
- std::unique_ptr<EndpointChannel> CreateUpgradedEndpointChannel(
- ClientProxy* client, const std::string& service_id,
- const std::string& endpoint_id,
- const UpgradePathInfo& upgrade_path_info) override;
- // Returns the upgrade medium of the BwuHandler.
- // @BwuHandlerThread
- Medium GetUpgradeMedium() const override { return Medium::WEB_RTC; }
-
- void OnIncomingWebrtcConnection(ClientProxy* client,
- const std::string& service_id,
- mediums::WebRtcSocketWrapper socket);
-
- void OnEndpointDisconnect(ClientProxy* client,
- const std::string& endpoint_id) override;
-
- std::string GetCountryCode();
-
- class WebrtcIncomingSocket : public BwuHandler::IncomingSocket {
- public:
- explicit WebrtcIncomingSocket(const std::string& name,
- mediums::WebRtcSocketWrapper socket);
- ~WebrtcIncomingSocket() override = default;
-
- std::string ToString() override;
- void Close() override;
-
- private:
- std::string name_;
- mediums::WebRtcSocketWrapper socket_;
- };
-
- Mediums& mediums_;
- mediums::WebRtc& webrtc_{mediums_.GetWebRtc()};
- absl::flat_hash_set<std::string> active_service_ids_;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_WEBRTC_BWU_HANDLER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/webrtc_endpoint_channel.cc b/chromium/third_party/nearby/src/cpp/core/internal/webrtc_endpoint_channel.cc
deleted file mode 100644
index 18d7c701cc9..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/webrtc_endpoint_channel.cc
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/webrtc_endpoint_channel.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-WebRtcEndpointChannel::WebRtcEndpointChannel(
- const std::string& channel_name, mediums::WebRtcSocketWrapper socket)
- : BaseEndpointChannel(channel_name, &socket.GetInputStream(),
- &socket.GetOutputStream()),
- webrtc_socket_(std::move(socket)) {}
-
-proto::connections::Medium WebRtcEndpointChannel::GetMedium() const {
- return proto::connections::Medium::WEB_RTC;
-}
-
-void WebRtcEndpointChannel::CloseImpl() { webrtc_socket_.Close(); }
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/webrtc_endpoint_channel.h b/chromium/third_party/nearby/src/cpp/core/internal/webrtc_endpoint_channel.h
deleted file mode 100644
index 5515ab6e38f..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/webrtc_endpoint_channel.h
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_WEBRTC_ENDPOINT_CHANNEL_H_
-#define CORE_INTERNAL_WEBRTC_ENDPOINT_CHANNEL_H_
-
-#include "core/internal/base_endpoint_channel.h"
-#include "core/internal/mediums/webrtc_socket_wrapper.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-class WebRtcEndpointChannel final : public BaseEndpointChannel {
- public:
- WebRtcEndpointChannel(const std::string& channel_name,
- mediums::WebRtcSocketWrapper webrtc_socket);
-
- proto::connections::Medium GetMedium() const override;
-
- private:
- void CloseImpl() override;
-
- mediums::WebRtcSocketWrapper webrtc_socket_;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_WEBRTC_ENDPOINT_CHANNEL_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_bwu_handler.cc b/chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_bwu_handler.cc
deleted file mode 100644
index 9b8eeedb96a..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_bwu_handler.cc
+++ /dev/null
@@ -1,166 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/wifi_lan_bwu_handler.h"
-
-#include <locale>
-#include <string>
-
-#include "absl/functional/bind_front.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/mediums/utils.h"
-#include "core/internal/offline_frames.h"
-#include "core/internal/wifi_lan_endpoint_channel.h"
-#include "platform/public/wifi_lan.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-WifiLanBwuHandler::WifiLanBwuHandler(Mediums& mediums,
- EndpointChannelManager& channel_manager,
- BwuNotifications notifications)
- : BaseBwuHandler(channel_manager, std::move(notifications)),
- mediums_(mediums) {}
-
-// Called by BWU initiator. Set up WifiLan upgraded medium for this endpoint,
-// and returns a upgrade path info (ip address, port) for remote party to
-// perform discovery.
-ByteArray WifiLanBwuHandler::InitializeUpgradedMediumForEndpoint(
- ClientProxy* client, const std::string& service_id,
- const std::string& endpoint_id) {
- // Use wrapped service ID to avoid have the same ID with the one for
- // startAdvertising. Otherwise, the listening request would be ignored because
- // the medium already start accepting the connection because the client not
- // stop the advertising yet.
- std::string upgrade_service_id = Utils::WrapUpgradeServiceId(service_id);
-
- auto credential = wifi_lan_medium_.GetCredentials(upgrade_service_id);
- auto ip_address = credential.first;
- auto port = credential.second;
- if (ip_address.empty()) {
- NEARBY_LOGS(INFO)
- << "WifiLanBwuHandler couldn't initiate the wifi_lan upgrade for "
- "endpoint "
- << endpoint_id
- << " because the wifi_lan ip address were unable to be obtained.";
- return {};
- }
-
- if (!wifi_lan_medium_.IsAcceptingConnections(upgrade_service_id)) {
- if (!wifi_lan_medium_.StartAcceptingConnections(
- upgrade_service_id,
- {
- .accepted_cb = absl::bind_front(
- &WifiLanBwuHandler::OnIncomingWifiLanConnection, this,
- client, service_id),
- })) {
- NEARBY_LOGS(ERROR)
- << "WifiLanBwuHandler couldn't initiate the WifiLan upgrade for "
- "endpoint "
- << endpoint_id
- << " because it failed to start listening for "
- "incoming WifiLan connections.";
- return {};
- }
- NEARBY_LOGS(INFO)
- << "WifiLanBwuHandler successfully started listening for incoming "
- "WifiLan connections while upgrading endpoint "
- << endpoint_id;
- }
-
- // cache service ID to revert
- active_service_ids_.insert(upgrade_service_id);
-
- return parser::ForBwuWifiLanPathAvailable(ip_address, port);
-}
-
-void WifiLanBwuHandler::Revert() {
- for (const std::string& service_id : active_service_ids_) {
- wifi_lan_medium_.StopAcceptingConnections(service_id);
- }
- active_service_ids_.clear();
-
- NEARBY_LOG(INFO, "WifiLanBwuHandler successfully reverted all states.");
-}
-
-// Called by BWU target. Retrieves a new medium info from incoming message,
-// and establishes connection over WifiLan using this info.
-std::unique_ptr<EndpointChannel>
-WifiLanBwuHandler::CreateUpgradedEndpointChannel(
- ClientProxy* client, const std::string& service_id,
- const std::string& endpoint_id, const UpgradePathInfo& upgrade_path_info) {
- if (!upgrade_path_info.has_wifi_lan_socket()) {
- return nullptr;
- }
- const UpgradePathInfo::WifiLanSocket& upgrade_path_info_socket =
- upgrade_path_info.wifi_lan_socket();
- if (!upgrade_path_info_socket.has_ip_address() ||
- !upgrade_path_info_socket.has_wifi_port()) {
- NEARBY_LOG(ERROR, "WifiLanBwuHandler failed to parse UpgradePathInfo.");
- return nullptr;
- }
-
- const std::string& ip_address = upgrade_path_info_socket.ip_address();
- std::int32_t port = upgrade_path_info_socket.wifi_port();
-
- NEARBY_LOGS(VERBOSE) << "WifiLanBwuHandler is attempting to connect to "
- "available WifiLan service ("
- << ip_address << ":" << port << ") for endpoint "
- << endpoint_id;
-
- WifiLanSocket socket = wifi_lan_medium_.Connect(
- service_id, ip_address, port, client->GetCancellationFlag(endpoint_id));
- if (!socket.IsValid()) {
- NEARBY_LOGS(ERROR)
- << "WifiLanBwuHandler failed to connect to the WifiLan service ("
- << ip_address << ":" << port << ") for endpoint " << endpoint_id;
- return nullptr;
- }
-
- NEARBY_LOGS(VERBOSE)
- << "WifiLanBwuHandler successfully connected to WifiLan service ("
- << ip_address << ":" << port << ") while upgrading endpoint "
- << endpoint_id;
-
- // Create a new WifiLanEndpointChannel.
- auto channel = absl::make_unique<WifiLanEndpointChannel>(service_id, socket);
- if (channel == nullptr) {
- NEARBY_LOGS(ERROR) << "WifiLanBwuHandler failed to create WifiLan endpoint "
- "channel to the WifiLan service ("
- << ip_address << ":" << port << ") for endpoint "
- << endpoint_id;
- socket.Close();
- return nullptr;
- }
-
- return channel;
-}
-
-// Accept Connection Callback.
-void WifiLanBwuHandler::OnIncomingWifiLanConnection(
- ClientProxy* client, const std::string& service_id, WifiLanSocket socket) {
- auto channel = absl::make_unique<WifiLanEndpointChannel>(service_id, socket);
- std::unique_ptr<IncomingSocketConnection> connection(
- new IncomingSocketConnection{
- .socket =
- absl::make_unique<WifiLanIncomingSocket>(service_id, socket),
- .channel = std::move(channel),
- });
- bwu_notifications_.incoming_connection_cb(client, std::move(connection));
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_bwu_handler.h b/chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_bwu_handler.h
deleted file mode 100644
index c16fbe74c17..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_bwu_handler.h
+++ /dev/null
@@ -1,80 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_WIFI_LAN_BWU_HANDLER_H_
-#define CORE_INTERNAL_WIFI_LAN_BWU_HANDLER_H_
-
-#include "core/internal/base_bwu_handler.h"
-#include "core/internal/client_proxy.h"
-#include "core/internal/endpoint_channel_manager.h"
-#include "core/internal/mediums/mediums.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Defines the set of methods that need to be implemented to handle the
-// per-Medium-specific operations needed to upgrade an EndpointChannel.
-class WifiLanBwuHandler : public BaseBwuHandler {
- public:
- WifiLanBwuHandler(Mediums& mediums, EndpointChannelManager& channel_manager,
- BwuNotifications notifications);
- ~WifiLanBwuHandler() override = default;
-
- private:
- ByteArray InitializeUpgradedMediumForEndpoint(
- ClientProxy* client, const std::string& service_id,
- const std::string& endpoint_id) override;
-
- void Revert() override;
-
- std::unique_ptr<EndpointChannel> CreateUpgradedEndpointChannel(
- ClientProxy* client, const std::string& service_id,
- const std::string& endpoint_id,
- const UpgradePathInfo& upgrade_path_info) override;
-
- Medium GetUpgradeMedium() const override { return Medium::WIFI_LAN; }
-
- void OnEndpointDisconnect(ClientProxy* client,
- const std::string& endpoint_id) override {}
-
- void OnIncomingWifiLanConnection(ClientProxy* client,
- const std::string& service_id,
- WifiLanSocket socket);
-
- class WifiLanIncomingSocket : public BwuHandler::IncomingSocket {
- public:
- explicit WifiLanIncomingSocket(const std::string& name,
- WifiLanSocket socket)
- : name_(name), socket_(socket) {}
- ~WifiLanIncomingSocket() override = default;
-
- std::string ToString() override { return name_; }
- void Close() override { socket_.Close(); }
-
- private:
- std::string name_;
- WifiLanSocket socket_;
- };
-
- Mediums& mediums_;
- WifiLan& wifi_lan_medium_{mediums_.GetWifiLan()};
- absl::flat_hash_set<std::string> active_service_ids_;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_WIFI_LAN_BWU_HANDLER_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_endpoint_channel.cc b/chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_endpoint_channel.cc
deleted file mode 100644
index ec7503efd15..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_endpoint_channel.cc
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/wifi_lan_endpoint_channel.h"
-
-#include <string>
-
-#include "platform/public/logging.h"
-#include "platform/public/wifi_lan.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-WifiLanEndpointChannel::WifiLanEndpointChannel(const std::string& channel_name,
- WifiLanSocket socket)
- : BaseEndpointChannel(channel_name, &socket.GetInputStream(),
- &socket.GetOutputStream()),
- socket_(std::move(socket)) {}
-
-proto::connections::Medium WifiLanEndpointChannel::GetMedium() const {
- return proto::connections::Medium::WIFI_LAN;
-}
-
-void WifiLanEndpointChannel::CloseImpl() {
- auto status = socket_.Close();
- if (!status.Ok()) {
- NEARBY_LOGS(INFO)
- << "Failed to close underlying socket for WifiLanEndpointChannel "
- << GetName() << " : exception = " << status.value;
- }
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_endpoint_channel.h b/chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_endpoint_channel.h
deleted file mode 100644
index e7c79f9ceb4..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_endpoint_channel.h
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_WIFI_LAN_ENDPOINT_CHANNEL_H_
-#define CORE_INTERNAL_WIFI_LAN_ENDPOINT_CHANNEL_H_
-
-#include "core/internal/base_endpoint_channel.h"
-#include "platform/public/wifi_lan.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-class WifiLanEndpointChannel final : public BaseEndpointChannel {
- public:
- // Creates both outgoing and incoming WifiLan channels.
- WifiLanEndpointChannel(const std::string& channel_name, WifiLanSocket socket);
-
- proto::connections::Medium GetMedium() const override;
-
- private:
- void CloseImpl() override;
-
- WifiLanSocket socket_;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_WIFI_LAN_ENDPOINT_CHANNEL_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_service_info.cc b/chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_service_info.cc
deleted file mode 100644
index e3bfcf71126..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_service_info.cc
+++ /dev/null
@@ -1,205 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/wifi_lan_service_info.h"
-
-#include <inttypes.h>
-
-#include <cstring>
-#include <utility>
-
-#include "absl/strings/str_cat.h"
-#include "platform/base/base64_utils.h"
-#include "platform/base/base_input_stream.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// These definitions are necessary before C++17.
-constexpr absl::string_view WifiLanServiceInfo::kKeyEndpointInfo;
-constexpr std::uint32_t WifiLanServiceInfo::kServiceIdHashLength;
-constexpr int WifiLanServiceInfo::kMaxEndpointInfoLength;
-
-WifiLanServiceInfo::WifiLanServiceInfo(Version version, Pcp pcp,
- absl::string_view endpoint_id,
- const ByteArray& service_id_hash,
- const ByteArray& endpoint_info,
- const ByteArray& uwb_address,
- WebRtcState web_rtc_state) {
- if (version != Version::kV1 || endpoint_id.empty() ||
- endpoint_id.length() != kEndpointIdLength ||
- service_id_hash.size() != kServiceIdHashLength ||
- endpoint_info.size() > kMaxEndpointInfoLength) {
- return;
- }
- switch (pcp) {
- case Pcp::kP2pCluster: // Fall through
- case Pcp::kP2pStar: // Fall through
- case Pcp::kP2pPointToPoint:
- break;
- default:
- return;
- }
-
- version_ = version;
- pcp_ = pcp;
- service_id_hash_ = service_id_hash;
- endpoint_id_ = std::string(endpoint_id);
- endpoint_info_ = endpoint_info;
- uwb_address_ = uwb_address;
- web_rtc_state_ = web_rtc_state;
-}
-
-WifiLanServiceInfo::WifiLanServiceInfo(const NsdServiceInfo& nsd_service_info) {
- auto txt_endpoint_info_name =
- nsd_service_info.GetTxtRecord(std::string(kKeyEndpointInfo));
- if (!txt_endpoint_info_name.empty()) {
- endpoint_info_ = Base64Utils::Decode(txt_endpoint_info_name);
- if (endpoint_info_.size() > kMaxEndpointInfoLength) {
- NEARBY_LOG(INFO,
- "Cannot deserialize EndpointInfo: expecting endpoint info "
- "max %d raw bytes, got %" PRIu64,
- kMaxEndpointInfoLength, endpoint_info_.size());
- return;
- }
- }
-
- auto service_info_name = nsd_service_info.GetServiceName();
- ByteArray service_info_bytes = Base64Utils::Decode(service_info_name);
- if (service_info_bytes.Empty()) {
- NEARBY_LOG(
- INFO,
- "Cannot deserialize WifiLanServiceInfo: failed Base64 decoding of %s",
- std::string(service_info_name).c_str());
- return;
- }
-
- if (service_info_bytes.size() < kMinLanServiceNameLength) {
- NEARBY_LOG(INFO,
- "Cannot deserialize WifiLanServiceInfo: expecting min %d raw "
- "bytes, got %" PRIu64,
- kMinLanServiceNameLength, service_info_bytes.size());
- return;
- }
-
- BaseInputStream base_input_stream{service_info_bytes};
- // The first 1 byte is supposed to be the version and pcp.
- auto version_and_pcp_byte = static_cast<char>(base_input_stream.ReadUint8());
- // The upper 3 bits are supposed to be the version.
- version_ =
- static_cast<Version>((version_and_pcp_byte & kVersionBitmask) >> 5);
- if (version_ != Version::kV1) {
- NEARBY_LOG(INFO,
- "Cannot deserialize WifiLanServiceInfo: unsupported Version %d",
- version_);
- return;
- }
- // The lower 5 bits are supposed to be the Pcp.
- pcp_ = static_cast<Pcp>(version_and_pcp_byte & kPcpBitmask);
- switch (pcp_) {
- case Pcp::kP2pCluster: // Fall through
- case Pcp::kP2pStar: // Fall through
- case Pcp::kP2pPointToPoint:
- break;
- default:
- NEARBY_LOG(INFO,
- "Cannot deserialize WifiLanServiceInfo: unsupported V1 PCP %d",
- pcp_);
- }
-
- // The next 4 bytes are supposed to be the endpoint_id.
- endpoint_id_ = std::string{base_input_stream.ReadBytes(kEndpointIdLength)};
-
- // The next 3 bytes are supposed to be the service_id_hash.
- service_id_hash_ = base_input_stream.ReadBytes(kServiceIdHashLength);
-
- // The next 1 byte is supposed to be the length of the uwb_address. If
- // available, continues to deserialize UWB address and extra field of WebRtc
- // state.
- if (base_input_stream.IsAvailable(1)) {
- std::uint32_t expected_uwb_address_length = base_input_stream.ReadUint8();
- // If the length of uwb_address is not zero, then retrieve it.
- if (expected_uwb_address_length != 0) {
- uwb_address_ = base_input_stream.ReadBytes(expected_uwb_address_length);
- if (uwb_address_.Empty() ||
- uwb_address_.size() != expected_uwb_address_length) {
- NEARBY_LOG(INFO,
- "Cannot deserialize WifiLanServiceInfo: expected "
- "uwbAddress size to be %d bytes, got %" PRIu64,
- expected_uwb_address_length, uwb_address_.size());
- // Clear enpoint_id for validity.
- endpoint_id_.clear();
- return;
- }
- }
-
- // The next 1 byte is extra field.
- web_rtc_state_ = WebRtcState::kUndefined;
- if (base_input_stream.IsAvailable(kExtraFieldLength)) {
- auto extra_field = static_cast<char>(base_input_stream.ReadUint8());
- web_rtc_state_ = (extra_field & kWebRtcConnectableFlagBitmask) == 1
- ? WebRtcState::kConnectable
- : WebRtcState::kUnconnectable;
- }
- }
-}
-
-WifiLanServiceInfo::operator NsdServiceInfo() const {
- if (!IsValid()) {
- return {};
- }
-
- // The upper 3 bits are the Version.
- auto version_and_pcp_byte = static_cast<char>(
- (static_cast<uint32_t>(Version::kV1) << 5) & kVersionBitmask);
- // The lower 5 bits are the PCP.
- version_and_pcp_byte |=
- static_cast<char>(static_cast<uint32_t>(pcp_) & kPcpBitmask);
-
- std::string out = absl::StrCat(std::string(1, version_and_pcp_byte),
- endpoint_id_, std::string(service_id_hash_));
-
- // The next bytes are UWB address field.
- if (!uwb_address_.Empty()) {
- absl::StrAppend(&out, std::string(1, uwb_address_.size()));
- absl::StrAppend(&out, std::string(uwb_address_));
- } else {
- // Write UWB address with length 0 to be able to read the next field, which
- // needs to be appended.
- if (web_rtc_state_ != WebRtcState::kUndefined)
- absl::StrAppend(&out, std::string(1, uwb_address_.size()));
- }
-
- // The next 1 byte is extra field.
- if (web_rtc_state_ != WebRtcState::kUndefined) {
- int web_rtc_connectable_flag =
- (web_rtc_state_ == WebRtcState::kConnectable) ? 1 : 0;
- char field_byte = static_cast<char>(web_rtc_connectable_flag) &
- kWebRtcConnectableFlagBitmask;
- absl::StrAppend(&out, std::string(1, field_byte));
- }
-
- NsdServiceInfo nsd_service_info;
- nsd_service_info.SetServiceName(
- Base64Utils::Encode(ByteArray{std::move(out)}));
- nsd_service_info.SetTxtRecord(std::string(kKeyEndpointInfo),
- Base64Utils::Encode(endpoint_info_));
- return nsd_service_info;
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_service_info.h b/chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_service_info.h
deleted file mode 100644
index 943fe51db20..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_service_info.h
+++ /dev/null
@@ -1,97 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_INTERNAL_WIFI_LAN_SERVICE_INFO_H_
-#define CORE_INTERNAL_WIFI_LAN_SERVICE_INFO_H_
-
-#include <cstdint>
-
-#include "absl/strings/string_view.h"
-#include "core/internal/base_pcp_handler.h"
-#include "core/internal/pcp.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/nsd_service_info.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Represents the format of the WifiLan service info used in Advertising +
-// Discovery.
-//
-// See go/nearby-offline-data-interchange-formats for the specification.
-class WifiLanServiceInfo {
- public:
- // Versions of the WifiLanServiceInfo.
- enum class Version {
- kUndefined = 0,
- kV1 = 1,
- };
-
- // The key of TXTRecord for EndpointInfo.
- static constexpr absl::string_view kKeyEndpointInfo{"n"};
- static constexpr std::uint32_t kServiceIdHashLength = 3;
- static constexpr int kMaxEndpointInfoLength = 131;
-
- WifiLanServiceInfo() = default;
- WifiLanServiceInfo(Version version, Pcp pcp, absl::string_view endpoint_id,
- const ByteArray& service_id_hash,
- const ByteArray& endpoint_info,
- const ByteArray& uwb_address, WebRtcState web_rtc_state);
-
- // Constructs WifiLanServiceInfo through NsdServiceInfo.
- explicit WifiLanServiceInfo(const NsdServiceInfo& nsd_service_info);
- WifiLanServiceInfo(const WifiLanServiceInfo&) = default;
- WifiLanServiceInfo& operator=(const WifiLanServiceInfo&) = default;
- WifiLanServiceInfo(WifiLanServiceInfo&&) = default;
- WifiLanServiceInfo& operator=(WifiLanServiceInfo&&) = default;
- ~WifiLanServiceInfo() = default;
-
- explicit operator NsdServiceInfo() const;
-
- bool IsValid() const { return !endpoint_id_.empty(); }
- Version GetVersion() const { return version_; }
- Pcp GetPcp() const { return pcp_; }
- std::string GetEndpointId() const { return endpoint_id_; }
- ByteArray GetEndpointInfo() const { return endpoint_info_; }
- ByteArray GetServiceIdHash() const { return service_id_hash_; }
- ByteArray GetUwbAddress() const { return uwb_address_; }
- WebRtcState GetWebRtcState() const { return web_rtc_state_; }
-
- private:
- static constexpr int kMinLanServiceNameLength = 9;
- static constexpr int kEndpointIdLength = 4;
- static constexpr int kUwbAddressLengthSize = 1;
- static constexpr int kExtraFieldLength = 1;
-
- static constexpr int kVersionBitmask = 0x0E0;
- static constexpr int kPcpBitmask = 0x01F;
- static constexpr int kVersionShift = 5;
- static constexpr int kWebRtcConnectableFlagBitmask = 0x01;
-
- Version version_{Version::kUndefined};
- Pcp pcp_{Pcp::kUnknown};
- std::string endpoint_id_;
- ByteArray service_id_hash_;
- ByteArray endpoint_info_;
- // TODO(b/169550050): Define UWB address field.
- ByteArray uwb_address_;
- WebRtcState web_rtc_state_{WebRtcState::kUndefined};
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_INTERNAL_WIFI_LAN_SERVICE_INFO_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_service_info_test.cc b/chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_service_info_test.cc
deleted file mode 100644
index ffa9d79b81a..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/internal/wifi_lan_service_info_test.cc
+++ /dev/null
@@ -1,171 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/internal/wifi_lan_service_info.h"
-
-#include <cstring>
-#include <memory>
-
-#include "gtest/gtest.h"
-#include "platform/base/base64_utils.h"
-#include "platform/base/nsd_service_info.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-
-constexpr WifiLanServiceInfo::Version kVersion =
- WifiLanServiceInfo::Version::kV1;
-constexpr Pcp kPcp = Pcp::kP2pCluster;
-constexpr absl::string_view kEndPointID{"AB12"};
-constexpr absl::string_view kServiceIDHashBytes{"\x0a\x0b\x0c"};
-constexpr absl::string_view kEndPointName{"RAWK + ROWL!"};
-constexpr WebRtcState kWebRtcState = WebRtcState::kConnectable;
-
-// TODO(b/169550050): Implement UWBAddress.
-TEST(WifiLanServiceInfoTest, ConstructionWorks) {
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- ByteArray endpoint_info{std::string(kEndPointName)};
- WifiLanServiceInfo wifi_lan_service_info{
- kVersion, kPcp, kEndPointID, service_id_hash,
- endpoint_info, ByteArray{}, kWebRtcState};
-
- EXPECT_TRUE(wifi_lan_service_info.IsValid());
- EXPECT_EQ(kPcp, wifi_lan_service_info.GetPcp());
- EXPECT_EQ(kVersion, wifi_lan_service_info.GetVersion());
- EXPECT_EQ(kEndPointID, wifi_lan_service_info.GetEndpointId());
- EXPECT_EQ(service_id_hash, wifi_lan_service_info.GetServiceIdHash());
- EXPECT_EQ(endpoint_info, wifi_lan_service_info.GetEndpointInfo());
-}
-
-TEST(WifiLanServiceInfoTest, ConstructionFromSerializedStringWorks) {
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- ByteArray endpoint_info{std::string(kEndPointName)};
- WifiLanServiceInfo org_wifi_lan_service_info{
- kVersion, kPcp, kEndPointID, service_id_hash,
- endpoint_info, ByteArray{}, kWebRtcState};
- NsdServiceInfo nsd_service_info{org_wifi_lan_service_info};
-
- WifiLanServiceInfo wifi_lan_service_info{nsd_service_info};
-
- EXPECT_TRUE(wifi_lan_service_info.IsValid());
- EXPECT_EQ(kPcp, wifi_lan_service_info.GetPcp());
- EXPECT_EQ(kVersion, wifi_lan_service_info.GetVersion());
- EXPECT_EQ(kEndPointID, wifi_lan_service_info.GetEndpointId());
- EXPECT_EQ(service_id_hash, wifi_lan_service_info.GetServiceIdHash());
- EXPECT_EQ(endpoint_info, wifi_lan_service_info.GetEndpointInfo());
- EXPECT_EQ(kWebRtcState, wifi_lan_service_info.GetWebRtcState());
-}
-
-TEST(WifiLanServiceInfoTest, ConstructionFailsWithBadVersion) {
- auto bad_version = static_cast<WifiLanServiceInfo::Version>(666);
-
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- ByteArray endpoint_info{std::string(kEndPointName)};
- WifiLanServiceInfo wifi_lan_service_info{
- bad_version, kPcp, kEndPointID, service_id_hash,
- endpoint_info, ByteArray{}, kWebRtcState};
-
- EXPECT_FALSE(wifi_lan_service_info.IsValid());
-}
-
-TEST(WifiLanServiceInfoTest, ConstructionFailsWithBadPCP) {
- auto bad_pcp = static_cast<Pcp>(666);
-
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- ByteArray endpoint_info{std::string(kEndPointName)};
- WifiLanServiceInfo wifi_lan_service_info{
- kVersion, bad_pcp, kEndPointID, service_id_hash,
- endpoint_info, ByteArray{}, kWebRtcState};
-
- EXPECT_FALSE(wifi_lan_service_info.IsValid());
-}
-
-TEST(WifiLanServiceInfoTest, ConstructionFailsWithShortEndpointId) {
- std::string short_endpoint_id("AB1");
-
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- ByteArray endpoint_info{std::string(kEndPointName)};
- WifiLanServiceInfo wifi_lan_service_info{
- kVersion, kPcp, short_endpoint_id, service_id_hash,
- endpoint_info, ByteArray{}, kWebRtcState};
-
- EXPECT_FALSE(wifi_lan_service_info.IsValid());
-}
-
-TEST(WifiLanServiceInfoTest, ConstructionFailsWithLongEndpointId) {
- std::string long_endpoint_id("AB12X");
-
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- ByteArray endpoint_info{std::string(kEndPointName)};
- WifiLanServiceInfo wifi_lan_service_info{
- kVersion, kPcp, long_endpoint_id, service_id_hash,
- endpoint_info, ByteArray{}, kWebRtcState};
-
- EXPECT_FALSE(wifi_lan_service_info.IsValid());
-}
-
-TEST(WifiLanServiceInfoTest, ConstructionFailsWithShortServiceIdHash) {
- char short_service_id_hash_bytes[] = "\x0a\x0b";
-
- ByteArray short_service_id_hash{short_service_id_hash_bytes};
- ByteArray endpoint_info{std::string(kEndPointName)};
- WifiLanServiceInfo wifi_lan_service_info{
- kVersion, kPcp, kEndPointID, short_service_id_hash,
- endpoint_info, ByteArray{}, kWebRtcState};
-
- EXPECT_FALSE(wifi_lan_service_info.IsValid());
-}
-
-TEST(WifiLanServiceInfoTest, ConstructionFailsWithLongServiceIdHash) {
- char long_service_id_hash_bytes[] = "\x0a\x0b\x0c\x0d";
-
- ByteArray long_service_id_hash{long_service_id_hash_bytes};
- ByteArray endpoint_info{std::string(kEndPointName)};
- WifiLanServiceInfo wifi_lan_service_info{
- kVersion, kPcp, kEndPointID, long_service_id_hash,
- endpoint_info, ByteArray{}, kWebRtcState};
-
- EXPECT_FALSE(wifi_lan_service_info.IsValid());
-}
-
-TEST(WifiLanServiceInfoTest, ConstructionFailsWithShortServiceNameLength) {
- char wifi_lan_service_info_name[] = {'X', '\0'};
- ByteArray wifi_lan_service_info_bytes{wifi_lan_service_info_name};
-
- NsdServiceInfo nsd_service_info;
- nsd_service_info.SetServiceName(
- Base64Utils::Encode(wifi_lan_service_info_bytes));
-
- WifiLanServiceInfo wifi_lan_service_info{nsd_service_info};
-
- EXPECT_FALSE(wifi_lan_service_info.IsValid());
-}
-
-TEST(WifiLanServiceInfoTest, ConstructionFailsWithLongEndpointInfoLength) {
- ByteArray service_id_hash{std::string(kServiceIDHashBytes)};
- ByteArray long_endpoint_info(WifiLanServiceInfo::kMaxEndpointInfoLength + 1);
-
- WifiLanServiceInfo wifi_lan_service_info{
- kVersion, kPcp, kEndPointID, service_id_hash,
- long_endpoint_info, ByteArray{}, kWebRtcState};
-
- EXPECT_FALSE(wifi_lan_service_info.IsValid());
-}
-
-} // namespace
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/listeners.h b/chromium/third_party/nearby/src/cpp/core/listeners.h
deleted file mode 100644
index f9c0208daac..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/listeners.h
+++ /dev/null
@@ -1,198 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_LISTENERS_H_
-#define CORE_LISTENERS_H_
-
-#include <cstdint>
-#include <functional>
-#include <memory>
-#include <string>
-
-// This file defines all the protocol listeners and their parameter structures.
-// Listeners are defined as collections of std::function<T> instances, which is
-// more flexible than a virtual function:
-// - a subset of listener callbacks may be overridden, while others may remain
-// default-initialized.
-// - callbacks may be initialized with lambdas; lambda definitions are concize.
-
-#include "core/options.h"
-#include "core/payload.h"
-#include "core/status.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/byte_utils.h"
-#include "platform/base/listeners.h"
-#include "platform/public/core_config.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Common callback for asynchronously invoked methods.
-// Called after a job scheduled for execution is completed.
-// This is not the same as completion of the associated process,
-// which may have many states, and multiple async jobs, and be still ongoing.
-// Progress on the overall process is reported by the associated listener.
-struct DLL_API ResultCallback {
- // Callback to access the status of the operation when available.
- // status - result of job execution;
- // Status::kSuccess, if successful; anything else indicates failure.
- std::function<void(Status)> result_cb = DefaultCallback<Status>();
-};
-
-struct DLL_API ConnectionResponseInfo {
- std::string GetAuthenticationDigits() {
- return ByteUtils::ToFourDigitString(raw_authentication_token);
- }
-
- ByteArray remote_endpoint_info;
- std::string authentication_token;
- ByteArray raw_authentication_token;
- bool is_incoming_connection = false;
- bool is_connection_verified = false;
-};
-
-struct DLL_API PayloadProgressInfo {
- std::int64_t payload_id = 0;
- enum class Status {
- kSuccess,
- kFailure,
- kInProgress,
- kCanceled,
- } status = Status::kSuccess;
- std::int64_t total_bytes = 0;
- std::int64_t bytes_transferred = 0;
-};
-
-enum class DLL_API DistanceInfo {
- kUnknown = 1,
- kVeryClose = 2,
- kClose = 3,
- kFar = 4,
-};
-
-struct DLL_API ConnectionListener {
- // A basic encrypted channel has been created between you and the endpoint.
- // Both sides are now asked if they wish to accept or reject the connection
- // before any data can be sent over this channel.
- //
- // This is your chance, before you accept the connection, to confirm that you
- // connected to the correct device. Both devices are given an identical token;
- // it's up to you to decide how to verify it before proceeding. Typically this
- // involves showing the token on both devices and having the users manually
- // compare and confirm; however, this is only required if you desire a secure
- // connection between the devices.
- //
- // Whichever route you decide to take (including not authenticating the other
- // device), call Core::AcceptConnection() when you're ready to talk, or
- // Core::RejectConnection() to close the connection.
- //
- // endpoint_id - The identifier for the remote endpoint.
- // info - Other relevant information about the connection.
- std::function<void(const std::string& endpoint_id,
- const ConnectionResponseInfo& info)>
- initiated_cb =
- DefaultCallback<const std::string&, const ConnectionResponseInfo&>();
-
- // Called after both sides have accepted the connection.
- // Both sides may now send Payloads to each other.
- // Call Core::SendPayload() or wait for incoming PayloadListener::OnPayload().
- //
- // endpoint_id - The identifier for the remote endpoint.
- std::function<void(const std::string& endpoint_id)> accepted_cb =
- DefaultCallback<const std::string&>();
-
- // Called when either side rejected the connection.
- // Payloads can not be exchaged. Call Core::DisconnectFromEndpoint()
- // to terminate connection.
- //
- // endpoint_id - The identifier for the remote endpoint.
- std::function<void(const std::string& endpoint_id, Status status)>
- rejected_cb = DefaultCallback<const std::string&, Status>();
-
- // Called when a remote endpoint is disconnected or has become unreachable.
- // At this point service (re-)discovery may start again.
- //
- // endpoint_id - The identifier for the remote endpoint.
- std::function<void(const std::string& endpoint_id)> disconnected_cb =
- DefaultCallback<const std::string&>();
-
- // Called when the connection's available bandwidth has changed.
- //
- // endpoint_id - The identifier for the remote endpoint.
- // medium - Medium we upgraded to.
- std::function<void(const std::string& endpoint_id, Medium medium)>
- bandwidth_changed_cb = DefaultCallback<const std::string&, Medium>();
-};
-
-struct DLL_API DiscoveryListener {
- // Called when a remote endpoint is discovered.
- //
- // endpoint_id - The ID of the remote endpoint that was discovered.
- // endpoint_info - The info of the remote endpoint representd by ByteArray.
- // service_id - The ID of the service advertised by the remote endpoint.
- std::function<void(const std::string& endpoint_id,
- const ByteArray& endpoint_info,
- const std::string& service_id)>
- endpoint_found_cb = DefaultCallback<const std::string&, const ByteArray&,
- const std::string&>();
-
- // Called when a remote endpoint is no longer discoverable; only called for
- // endpoints that previously had been passed to {@link
- // #onEndpointFound(String, DiscoveredEndpointInfo)}.
- //
- // endpoint_id - The ID of the remote endpoint that was lost.
- std::function<void(const std::string& endpoint_id)> endpoint_lost_cb =
- DefaultCallback<const std::string&>();
-
- // Called when a remote endpoint is found with an updated distance.
- //
- // arguments:
- // endpoint_id - The ID of the remote endpoint that was lost.
- // info - The distance info, encoded as enum value.
- std::function<void(const std::string& endpoint_id, DistanceInfo info)>
- endpoint_distance_changed_cb =
- DefaultCallback<const std::string&, DistanceInfo>();
-};
-
-struct DLL_API PayloadListener {
- // Called when a Payload is received from a remote endpoint. Depending
- // on the type of the Payload, all of the data may or may not have been
- // received at the time of this call. Use OnPayloadProgress() to
- // get updates on the status of the data received.
- //
- // endpoint_id - The identifier for the remote endpoint that sent the
- // payload.
- // payload - The Payload object received.
- std::function<void(const std::string& endpoint_id, Payload payload)>
- payload_cb = DefaultCallback<const std::string&, Payload>();
-
- // Called with progress information about an active Payload transfer, either
- // incoming or outgoing.
- //
- // endpoint_id - The identifier for the remote endpoint that is sending or
- // receiving this payload.
- // info - The PayloadProgressInfo structure describing the status of
- // the transfer.
- std::function<void(const std::string& endpoint_id,
- const PayloadProgressInfo& info)>
- payload_progress_cb =
- DefaultCallback<const std::string&, const PayloadProgressInfo&>();
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_LISTENERS_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/listeners_test.cc b/chromium/third_party/nearby/src/cpp/core/listeners_test.cc
deleted file mode 100644
index d2221db965a..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/listeners_test.cc
+++ /dev/null
@@ -1,59 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/listeners.h"
-
-#include <memory>
-#include <utility>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-namespace {
-
-TEST(ListenersTest, EnsureDefaultInitializedIsCallable) {
- ConnectionListener listener;
- std::string endpoint_id("endpoint_id");
- listener.initiated_cb(endpoint_id, ConnectionResponseInfo());
- listener.accepted_cb(endpoint_id);
- listener.rejected_cb(endpoint_id, {Status::kError});
- listener.disconnected_cb(endpoint_id);
- listener.bandwidth_changed_cb(endpoint_id, Medium());
- SUCCEED();
-}
-
-TEST(ListenersTest, EnsurePartiallyInitializedIsCallable) {
- std::string endpoint_id = {"endpoint_id"};
- bool initiated_cb_called = false;
- ConnectionListener listener{
- .initiated_cb =
- [&](std::string, ConnectionResponseInfo) {
- initiated_cb_called = true;
- },
- };
- listener.initiated_cb(endpoint_id, ConnectionResponseInfo());
- listener.accepted_cb(endpoint_id);
- listener.rejected_cb(endpoint_id, {Status::kError});
- listener.disconnected_cb(endpoint_id);
- listener.bandwidth_changed_cb(endpoint_id, Medium());
- EXPECT_TRUE(initiated_cb_called);
-}
-
-} // namespace
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/options.cc b/chromium/third_party/nearby/src/cpp/core/options.cc
deleted file mode 100644
index 58da2d22863..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/options.cc
+++ /dev/null
@@ -1,89 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/options.h"
-
-#include <string>
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Verify if ConnectionOptions is in a not-initialized (Empty) state.
-bool ConnectionOptions::Empty() const { return strategy.IsNone(); }
-
-// Bring ConnectionOptions to a not-initialized (Empty) state.
-void ConnectionOptions::Clear() { strategy.Clear(); }
-
-// Returns a copy and normalizes allowed mediums:
-// (1) If is_out_of_band_connection is true, verifies that there is only one
-// medium allowed, defaulting to only Bluetooth if unspecified.
-// (2) If no mediums are allowed, allow all mediums.
-ConnectionOptions ConnectionOptions::CompatibleOptions() const {
- ConnectionOptions result = *this;
-
- // Out-of-band connections initiate connections via an injected endpoint
- // rather than through the normal discovery flow. These types of connections
- // can only be injected via a single medium.
- if (is_out_of_band_connection) {
- int num_enabled = result.allowed.Count(true);
-
- // Default to allow only Bluetooth if no single medium is specified.
- if (num_enabled != 1) {
- result.allowed.SetAll(false);
- result.allowed.bluetooth = true;
- }
- return result;
- }
-
- // Normal connections (i.e., not out-of-band) connections can specify
- // multiple mediums. If none are specified, default to allowing all mediums.
- if (!allowed.Any(true)) result.allowed.SetAll(true);
- return result;
-}
-
-std::vector<Medium> ConnectionOptions::GetMediums() const {
- return allowed.GetMediums(true);
-}
-
-// This call follows the standard Microsoft calling pattern of calling first
-// to get the size of the array. Caller then allocates memory for the array,
-// and makes this call again to copy the array into the provided location.
-void ConnectionOptions::GetMediums(
- location::nearby::proto::connections::Medium* mediums,
- uint32_t* mediumsSize) {
- auto size = GetMediums().size();
-
- // Caller is seeking the size of mediums
- if (mediums == nullptr) {
- *mediumsSize = size;
- return;
- }
-
- // Caller has not specified enough memory
- if (*mediumsSize < size) {
- mediums = nullptr; // ensure nullptr return
- *mediumsSize = size; // update the size to indicate the correct size
- return;
- }
-
- for (uint32_t i = 0; i < size; i++) {
- // Construct an array at the given location
- mediums[i] = GetMediums().at(i);
- }
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/options.h b/chromium/third_party/nearby/src/cpp/core/options.h
deleted file mode 100644
index ff1ca03b48b..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/options.h
+++ /dev/null
@@ -1,155 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-#ifndef CORE_OPTIONS_H_
-#define CORE_OPTIONS_H_
-#include <string>
-
-#include "core/strategy.h"
-#include "platform/base/byte_array.h"
-#include "proto/connections_enums.pb.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-using Medium = location::nearby::proto::connections::Medium;
-
-// Generic type: allows definition of a feature T for every Medium.
-template <typename T>
-struct MediumSelector {
- T bluetooth;
- T ble;
- T web_rtc;
- T wifi_lan;
-
- constexpr MediumSelector() = default;
- constexpr MediumSelector(const MediumSelector&) = default;
- constexpr MediumSelector& operator=(const MediumSelector&) = default;
- constexpr bool Any(T value) const {
- return bluetooth == value || ble == value || web_rtc == value ||
- wifi_lan == value;
- }
-
- constexpr bool All(T value) const {
- return bluetooth == value && ble == value && web_rtc == value &&
- wifi_lan == value;
- }
-
- constexpr int Count(T value) const {
- int count = 0;
- if (bluetooth == value) count++;
- if (ble == value) count++;
- if (wifi_lan == value) count++;
- if (web_rtc == value) count++;
- return count;
- }
-
- constexpr MediumSelector& SetAll(T value) {
- bluetooth = value;
- ble = value;
- web_rtc = value;
- wifi_lan = value;
- return *this;
- }
-
- std::vector<Medium> GetMediums(T value) const {
- std::vector<Medium> mediums;
- // Mediums are sorted in order of decreasing preference.
- if (wifi_lan == value) mediums.push_back(Medium::WIFI_LAN);
- if (web_rtc == value) mediums.push_back(Medium::WEB_RTC);
- if (bluetooth == value) mediums.push_back(Medium::BLUETOOTH);
- if (ble == value) mediums.push_back(Medium::BLE);
- return mediums;
- }
-};
-
-// Feature On/Off switch for mediums.
-using BooleanMediumSelector = MediumSelector<bool>;
-
-// Represents the various power levels that can be used, on mediums that support
-// it.
-enum class PowerLevel {
- kHighPower = 0,
- kLowPower = 1,
-};
-
-// Connection Options: used for both Advertising and Discovery.
-// All fields are mutable, to make the type copy-assignable.
-struct DLL_API ConnectionOptions {
- Strategy strategy;
- BooleanMediumSelector allowed{BooleanMediumSelector().SetAll(true)};
- bool auto_upgrade_bandwidth;
- bool enforce_topology_constraints;
- bool low_power;
- bool enable_bluetooth_listening;
- bool enable_webrtc_listening;
-
- // Whether this is intended to be used in conjunction with InjectEndpoint().
- bool is_out_of_band_connection = false;
- ByteArray remote_bluetooth_mac_address;
- std::string fast_advertisement_service_uuid;
- int keep_alive_interval_millis = 0;
- int keep_alive_timeout_millis = 0;
-
- // Verify if ConnectionOptions is in a not-initialized (Empty) state.
- bool Empty() const;
-
- // Bring ConnectionOptions to a not-initialized (Empty) state.
- void Clear();
-
- // Returns a copy and normalizes allowed mediums:
- // (1) If is_out_of_band_connection is true, verifies that there is only one
- // medium allowed, defaulting to only Bluetooth if unspecified.
- // (2) If no mediums are allowed, allow all mediums.
- ConnectionOptions CompatibleOptions() const;
-
- std::vector<Medium> GetMediums() const;
-
- // This call follows the standard Microsoft calling pattern of calling first
- // to get the size of the array. Caller then allocates memory for the array,
- // and makes this call again to copy the array into the provided location.
- void GetMediums(location::nearby::proto::connections::Medium* mediums,
- uint32_t* mediumsSize);
-};
-
-// Metadata injected to facilitate out-of-band connections. The medium field is
-// required, and the other fields are only specified for a specific medium.
-// Currently, Bluetooth is the only supported medium for out-of-band
-// connections.
-struct OutOfBandConnectionMetadata {
- // Medium to use for the out-of-band connection.
- Medium medium;
-
- // Endpoint ID to use for the injected connection; will be included in the
- // endpoint_found_cb callback. Must be exactly 4 bytes and should be randomly-
- // generated such that no two IDs are identical.
- std::string endpoint_id;
-
- // Endpoint info to use for the injected connection; will be included in the
- // endpoint_found_cb callback. Should uniquely identify the InjectEndpoint()
- // call so that the client which made the call can verify the endpoint
- // that was found is the one that was injected.
- //
- // Cannot be empty, and must be <131 bytes.
- ByteArray endpoint_info;
-
- // Used for Bluetooth connections.
- ByteArray remote_bluetooth_mac_address;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_OPTIONS_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/params.h b/chromium/third_party/nearby/src/cpp/core/params.h
deleted file mode 100644
index 3843cee9e82..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/params.h
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_PARAMS_H_
-#define CORE_PARAMS_H_
-
-#include <string>
-
-#include "core/listeners.h"
-#include "platform/base/byte_array.h"
-#include "platform/public/core_config.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Used by Discovery in Core::RequestConnection().
-// Used by Advertising in Core::StartAdvertising().
-struct DLL_API ConnectionRequestInfo {
- // endpoint_info - Identifing information about this endpoint (eg. name,
- // device type).
- // listener - A set of callbacks notified when remote endpoints request a
- // connection to this endpoint.
- ByteArray endpoint_info;
- ConnectionListener listener;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_PARAMS_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/payload.cc b/chromium/third_party/nearby/src/cpp/core/payload.cc
deleted file mode 100644
index 20acef85c4b..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/payload.cc
+++ /dev/null
@@ -1,101 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/payload.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Payload is default-constructible, and moveable, but not copyable container
-// that holds at most one instance of one of:
-// ByteArray, InputStream, or InputFile.
-Payload::Payload(Payload&& other) noexcept = default;
-Payload::~Payload() = default;
-Payload& Payload::operator=(Payload&& other) noexcept = default;
-
-// Default (invalid) payload.
-Payload::Payload() : content_(absl::monostate()) {}
-
-// Constructors for outgoing payloads.
-Payload::Payload(ByteArray&& bytes) : content_(std::move(bytes)) {}
-
-Payload::Payload(const ByteArray& bytes) : content_(bytes) {}
-
-Payload::Payload(InputFile file)
- : content_(std::move(file)),
- id_(std::hash<std::string>()(file.GetFilePath())) {}
-
-// TODO(jfcarroll): Convert std::function to function pointer
-Payload::Payload(std::function<InputStream&()> stream)
- : content_(std::move(stream)) {}
-
-// Constructors for incoming payloads.
-Payload::Payload(Id id, ByteArray&& bytes)
- : content_(std::move(bytes)), id_(id) {}
-
-Payload::Payload(Id id, const ByteArray& bytes) : content_(bytes), id_(id) {}
-
-Payload::Payload(Id id, InputFile file) : content_(std::move(file)), id_(id) {}
-
-// TODO(jfcarroll): Convert std::function to function pointer
-Payload::Payload(Id id, std::function<InputStream&()> stream)
- : content_(std::move(stream)), id_(id) {}
-
-// Returns ByteArray payload, if it has been defined, or empty ByteArray.
-const ByteArray& Payload::AsBytes() const& {
- static const ByteArray empty; // NOLINT: function-level static is OK.
- auto* result = absl::get_if<ByteArray>(&content_);
- return result ? *result : empty;
-}
-ByteArray&& Payload::AsBytes() && {
- auto* result = absl::get_if<ByteArray>(&content_);
- return result ? std::move(*result) : std::move(ByteArray());
-}
-// Returns InputStream* payload, if it has been defined, or nullptr.
-InputStream* Payload::AsStream() {
- auto* result = absl::get_if<std::function<InputStream&()>>(&content_);
- return result ? &(*result)() : nullptr;
-}
-// Returns InputFile* payload, if it has been defined, or nullptr.
-InputFile* Payload::AsFile() { return absl::get_if<InputFile>(&content_); }
-
-// Returns Payload unique ID.
-Payload::Id Payload::GetId() const { return id_; }
-
-// Returns Payload type.
-Payload::Type Payload::GetType() const { return type_; }
-
-// Sets the payload offset in bytes
-void Payload::SetOffset(size_t offset) {
- CHECK(type_ == Type::kFile || type_ == Type::kStream);
- InputFile* file = AsFile();
- if (file != nullptr) {
- CHECK(file->GetTotalSize() > 0 && offset < (size_t)file->GetTotalSize());
- }
- offset_ = offset;
-}
-
-size_t Payload::GetOffset() { return offset_; }
-
-// Generate Payload Id; to be passed to outgoing file constructor.
-Payload::Id Payload::GenerateId() { return Prng().NextInt64(); }
-
-Payload::Type Payload::FindType() const {
- return static_cast<Type>(content_.index());
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/payload.h b/chromium/third_party/nearby/src/cpp/core/payload.h
deleted file mode 100644
index ec66062b0c2..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/payload.h
+++ /dev/null
@@ -1,104 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef CORE_PAYLOAD_H_
-#define CORE_PAYLOAD_H_
-
-#include <cstdint>
-#include <functional>
-#include <memory>
-#include <utility>
-
-#include "absl/types/variant.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/input_stream.h"
-#include "platform/base/payload_id.h"
-#include "platform/base/prng.h"
-#include "platform/public/core_config.h"
-#include "platform/public/file.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Payload is default-constructible, and moveable, but not copyable container
-// that holds at most one instance of one of:
-// ByteArray, InputStream, or InputFile.
-class DLL_API Payload {
- public:
- using Id = PayloadId;
- // Order of types in variant, and values in Type enum is important.
- // Enum values must match respective variant types.
- using Content = absl::variant<absl::monostate, ByteArray,
- std::function<InputStream&()>, InputFile>;
- enum class Type { kUnknown = 0, kBytes = 1, kStream = 2, kFile = 3 };
-
- Payload(Payload&& other) noexcept;
- ~Payload();
- Payload& operator=(Payload&& other) noexcept;
-
- // Default (invalid) payload.
- Payload();
-
- // Constructors for outgoing payloads.
- explicit Payload(ByteArray&& bytes);
-
- explicit Payload(const ByteArray& bytes);
- explicit Payload(InputFile file);
- explicit Payload(std::function<InputStream&()> stream);
-
- // Constructors for incoming payloads.
- Payload(Id id, ByteArray&& bytes);
- Payload(Id id, const ByteArray& bytes);
- Payload(Id id, InputFile file);
- Payload(Id id, std::function<InputStream&()> stream);
-
-
- // Returns ByteArray payload, if it has been defined, or empty ByteArray.
- const ByteArray& AsBytes() const&;
- ByteArray&& AsBytes() &&;
- // Returns InputStream* payload, if it has been defined, or nullptr.
- InputStream* AsStream();
- // Returns InputFile* payload, if it has been defined, or nullptr.
- InputFile* AsFile();
-
- // Returns Payload unique ID.
- Id GetId() const;
-
- // Returns Payload type.
- Type GetType() const;
-
- // Sets the payload offset in bytes
- void SetOffset(size_t offset);
-
- size_t GetOffset();
-
- // Generate Payload Id; to be passed to outgoing file constructor.
- static Id GenerateId();
-
- private:
- Type FindType() const;
-
- Content content_;
- Id id_{GenerateId()};
- Type type_{FindType()};
- size_t offset_{0};
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // CORE_PAYLOAD_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/payload_test.cc b/chromium/third_party/nearby/src/cpp/core/payload_test.cc
deleted file mode 100644
index f6d54c76fd9..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/payload_test.cc
+++ /dev/null
@@ -1,107 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/payload.h"
-
-#include <memory>
-#include <type_traits>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/input_stream.h"
-#include "platform/public/file.h"
-#include "platform/public/pipe.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-TEST(PayloadTest, DefaultPayloadHasUnknownType) {
- Payload payload;
- EXPECT_EQ(payload.GetType(), Payload::Type::kUnknown);
-}
-
-TEST(PayloadTest, SupportsByteArrayType) {
- const ByteArray bytes("bytes");
- Payload payload(bytes);
- EXPECT_EQ(payload.GetType(), Payload::Type::kBytes);
- EXPECT_EQ(payload.AsStream(), nullptr);
- EXPECT_EQ(payload.AsFile(), nullptr);
- EXPECT_EQ(payload.AsBytes(), bytes);
-}
-
-TEST(PayloadTest, SupportsFileType) {
- constexpr size_t kOffset = 99;
- const auto payload_id = Payload::GenerateId();
- InputFile file(payload_id, 100);
- InputStream& stream = file.GetInputStream();
-
- Payload payload(payload_id, std::move(file));
- payload.SetOffset(kOffset);
-
- EXPECT_EQ(payload.GetType(), Payload::Type::kFile);
- EXPECT_EQ(payload.AsStream(), nullptr);
- EXPECT_EQ(&payload.AsFile()->GetInputStream(), &stream);
- EXPECT_EQ(payload.AsBytes(), ByteArray{});
- EXPECT_EQ(payload.GetOffset(), kOffset);
-}
-
-TEST(PayloadTest, SupportsStreamType) {
- constexpr size_t kOffset = 1234456;
- auto pipe = std::make_shared<Pipe>();
-
- Payload payload([streamable = pipe]() -> InputStream& {
- // For some reason, linter warns us that we return a dangling reference.
- // This is not true: we return a reference to internal variable of a
- // shared_ptr<Pipe> which remains valid while Payload is valid, since
- // shared_ptr<Pipe> is captured by value.
- return streamable->GetInputStream(); // NOLINT
- });
- payload.SetOffset(kOffset);
-
- EXPECT_EQ(payload.GetType(), Payload::Type::kStream);
- EXPECT_EQ(payload.AsStream(), &pipe->GetInputStream());
- EXPECT_EQ(payload.AsFile(), nullptr);
- EXPECT_EQ(payload.AsBytes(), ByteArray{});
- EXPECT_EQ(payload.GetOffset(), kOffset);
-}
-
-TEST(PayloadTest, PayloadIsMoveable) {
- Payload payload1;
- Payload payload2(ByteArray("bytes"));
- auto id = payload2.GetId();
- ByteArray bytes = payload2.AsBytes();
- EXPECT_EQ(payload1.GetType(), Payload::Type::kUnknown);
- EXPECT_EQ(payload2.GetType(), Payload::Type::kBytes);
- payload1 = std::move(payload2);
- EXPECT_EQ(payload1.GetType(), Payload::Type::kBytes);
- EXPECT_EQ(payload1.AsBytes(), bytes);
- EXPECT_EQ(payload1.GetId(), id);
-}
-
-TEST(PayloadTest, PayloadHasUniqueId) {
- Payload payload1;
- Payload payload2;
- EXPECT_NE(payload1.GetId(), payload2.GetId());
-}
-
-TEST(PayloadTest, PayloadIsNotCopyable) {
- EXPECT_FALSE(std::is_copy_constructible_v<Payload>);
- EXPECT_FALSE(std::is_copy_assignable_v<Payload>);
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/status_test.cc b/chromium/third_party/nearby/src/cpp/core/status_test.cc
deleted file mode 100644
index 1f64be5b5ba..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/status_test.cc
+++ /dev/null
@@ -1,58 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/status.h"
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-TEST(StatusTest, DefaultIsError) {
- Status status;
- EXPECT_FALSE(status.Ok());
- EXPECT_EQ(status, Status{Status::kError});
-}
-
-TEST(StatusTest, DefaultEquals) {
- Status status1;
- Status status2;
- EXPECT_EQ(status1, status2);
-}
-
-TEST(StatusTest, ExplicitInitEquals) {
- Status status1 = {Status::kSuccess};
- Status status2 = {Status::kSuccess};
- EXPECT_EQ(status1, status2);
- EXPECT_TRUE(status1.Ok());
-}
-
-TEST(StatusTest, ExplicitInitNotEquals) {
- Status status1 = {Status::kSuccess};
- Status status2 = {Status::kAlreadyAdvertising};
- EXPECT_NE(status1, status2);
-}
-
-TEST(StatusTest, CopyInitEquals) {
- Status status1 = {Status::kAlreadyAdvertising};
- Status status2 = {status1};
-
- EXPECT_EQ(status1, status2);
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/strategy.cc b/chromium/third_party/nearby/src/cpp/core/strategy.cc
deleted file mode 100644
index f42e3f743ad..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/strategy.cc
+++ /dev/null
@@ -1,59 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/strategy.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-const Strategy Strategy::kNone = {Strategy::ConnectionType::kNone,
- Strategy::TopologyType::kUnknown};
-const Strategy Strategy::kP2pCluster{Strategy::ConnectionType::kPointToPoint,
- Strategy::TopologyType::kManyToMany};
-const Strategy Strategy::kP2pStar{Strategy::ConnectionType::kPointToPoint,
- Strategy::TopologyType::kOneToMany};
-const Strategy Strategy::kP2pPointToPoint{
- Strategy::ConnectionType::kPointToPoint, Strategy::TopologyType::kOneToOne};
-
-bool Strategy::IsNone() const { return *this == kNone; }
-
-bool Strategy::IsValid() const {
- return *this == kP2pStar || *this == kP2pCluster || *this == kP2pPointToPoint;
-}
-
-std::string Strategy::GetName() const {
- if (*this == Strategy::kP2pCluster) {
- return "P2P_CLUSTER";
- } else if (*this == Strategy::kP2pStar) {
- return "P2P_STAR";
- } else if (*this == Strategy::kP2pPointToPoint) {
- return "P2P_POINT_TO_POINT";
- } else {
- return "UNKNOWN";
- }
-}
-
-bool operator==(const Strategy& lhs, const Strategy& rhs) {
- return lhs.connection_type_ == rhs.connection_type_ &&
- lhs.topology_type_ == rhs.topology_type_;
-}
-
-bool operator!=(const Strategy& lhs, const Strategy& rhs) {
- return !(lhs == rhs);
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/core/strategy.h b/chromium/third_party/nearby/src/cpp/core/strategy.h
deleted file mode 100644
index f85d7d60aa6..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/strategy.h
+++ /dev/null
@@ -1,72 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-#ifndef CORE_STRATEGY_H_
-#define CORE_STRATEGY_H_
-
-#include <string>
-
-#include "platform/public/core_config.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-// Defines a copyable, comparable connection strategy type.
-// It is one of: kP2pCluster, kP2pStar, kP2pPointToPoint.
-class DLL_API Strategy {
- public:
- static const Strategy kNone;
- static const Strategy kP2pCluster;
- static const Strategy kP2pStar;
- static const Strategy kP2pPointToPoint;
- constexpr Strategy() : Strategy(kNone) {}
- constexpr Strategy(const Strategy&) = default;
- constexpr Strategy& operator=(const Strategy&) = default;
-
- // Returns true, if strategy is kNone, false otherwise.
- bool IsNone() const;
-
- // Returns true, if a strategy is one of the supported strategies,
- // false otherwise.
- bool IsValid() const;
-
- // Returns a string representing given strategy, for every valid strategy.
- std::string GetName() const;
-
- // Undefine strategy.
- void Clear() { *this = kNone; }
- friend bool operator==(const Strategy& lhs, const Strategy& rhs);
- friend bool operator!=(const Strategy& lhs, const Strategy& rhs);
-
- private:
- enum class ConnectionType {
- kNone = 0,
- kPointToPoint = 1,
- };
- enum class TopologyType {
- kUnknown = 0,
- kOneToOne = 1,
- kOneToMany = 2,
- kManyToMany = 3,
- };
- constexpr Strategy(ConnectionType connection_type, TopologyType topology_type)
- : connection_type_(connection_type), topology_type_(topology_type) {}
- ConnectionType connection_type_;
- TopologyType topology_type_;
-};
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-#endif // CORE_STRATEGY_H_
diff --git a/chromium/third_party/nearby/src/cpp/core/strategy_test.cc b/chromium/third_party/nearby/src/cpp/core/strategy_test.cc
deleted file mode 100644
index 70b74723165..00000000000
--- a/chromium/third_party/nearby/src/cpp/core/strategy_test.cc
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "core/strategy.h"
-
-#include "gtest/gtest.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-TEST(StrategyTest, IsValidWorks) {
- EXPECT_FALSE(Strategy().IsValid());
- EXPECT_TRUE(Strategy::kP2pCluster.IsValid());
- EXPECT_TRUE(Strategy::kP2pStar.IsValid());
- EXPECT_TRUE(Strategy::kP2pPointToPoint.IsValid());
-}
-
-TEST(StrategyTest, IsNoneWorks) {
- EXPECT_TRUE(Strategy().IsNone());
- EXPECT_FALSE(Strategy::kP2pCluster.IsNone());
- EXPECT_FALSE(Strategy::kP2pStar.IsNone());
- EXPECT_FALSE(Strategy::kP2pPointToPoint.IsNone());
-}
-
-TEST(StrategyTest, CompareWorks) {
- EXPECT_EQ(Strategy::kP2pCluster, Strategy::kP2pCluster);
- EXPECT_EQ(Strategy::kP2pStar, Strategy::kP2pStar);
- EXPECT_EQ(Strategy::kP2pPointToPoint, Strategy::kP2pPointToPoint);
- EXPECT_NE(Strategy::kP2pCluster, Strategy::kP2pStar);
- EXPECT_NE(Strategy::kP2pCluster, Strategy::kP2pPointToPoint);
- EXPECT_NE(Strategy::kP2pStar, Strategy::kP2pPointToPoint);
-}
-
-TEST(StrategyTest, GetNameWorks) {
- EXPECT_EQ(Strategy().GetName(), "UNKNOWN");
- EXPECT_EQ(Strategy::kP2pCluster.GetName(), "P2P_CLUSTER");
- EXPECT_EQ(Strategy::kP2pStar.GetName(), "P2P_STAR");
- EXPECT_EQ(Strategy::kP2pPointToPoint.GetName(), "P2P_POINT_TO_POINT");
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/BUILD b/chromium/third_party/nearby/src/cpp/platform/api/BUILD
deleted file mode 100644
index 61cf51cfe42..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/api/BUILD
+++ /dev/null
@@ -1,100 +0,0 @@
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# https://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-licenses(["notice"])
-
-cc_library(
- name = "types",
- hdrs = [
- "atomic_boolean.h",
- "atomic_reference.h",
- "bluetooth_adapter.h",
- "cancelable.h",
- "condition_variable.h",
- "count_down_latch.h",
- "crypto.h",
- "executor.h",
- "future.h",
- "input_file.h",
- "listenable_future.h",
- "log_message.h",
- "mutex.h",
- "output_file.h",
- "scheduled_executor.h",
- "settable_future.h",
- "submittable_executor.h",
- "system_clock.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- visibility = [
- "//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
- "//platform/base:__pkg__",
- "//platform/impl:__subpackages__",
- "//platform/public:__pkg__",
- ],
- deps = [
- "//absl/base:core_headers",
- "//absl/strings",
- "//absl/time",
- "//platform/base",
- ],
-)
-
-cc_library(
- name = "comm",
- hdrs = [
- "ble.h",
- "ble_v2.h",
- "bluetooth_adapter.h",
- "bluetooth_classic.h",
- "server_sync.h",
- "webrtc.h",
- "wifi.h",
- "wifi_lan.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- visibility = [
- "//core/internal:__subpackages__",
- "//platform/base:__pkg__",
- "//platform/impl:__subpackages__",
- "//platform/public:__pkg__",
- ],
- deps = [
- "//absl/strings",
- "//absl/types:optional",
- "//platform/base",
- "//platform/base:cancellation_flag",
- "//proto/connections:offline_wire_formats_portable_proto",
- "//webrtc/api:libjingle_peerconnection_api",
- ],
-)
-
-cc_library(
- name = "platform",
- hdrs = [
- "platform.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- visibility = [
- "//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
- "//platform/base:__pkg__",
- "//platform/impl:__subpackages__",
- "//platform/public:__pkg__",
- ],
- deps = [
- ":comm",
- ":types",
- "//absl/strings",
- "//platform/base",
- ],
-)
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/ble.h b/chromium/third_party/nearby/src/cpp/platform/api/ble.h
deleted file mode 100644
index c58df6db578..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/api/ble.h
+++ /dev/null
@@ -1,125 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_API_BLE_H_
-#define PLATFORM_API_BLE_H_
-
-#include "platform/api/bluetooth_classic.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/cancellation_flag.h"
-#include "platform/base/input_stream.h"
-#include "platform/base/output_stream.h"
-
-namespace location {
-namespace nearby {
-namespace api {
-
-// Opaque wrapper over a BLE peripheral. Must contain enough data about a
-// particular BLE device to connect to its GATT server.
-class BlePeripheral {
- public:
- virtual ~BlePeripheral() = default;
-
- virtual std::string GetName() const = 0;
-
- virtual ByteArray GetAdvertisementBytes(
- const std::string& service_id) const = 0;
-};
-
-class BleSocket {
- public:
- virtual ~BleSocket() = default;
-
- // Returns the InputStream of the BleSocket.
- // On error, returned stream will report Exception::kIo on any operation.
- //
- // The returned object is not owned by the caller, and can be invalidated once
- // the BleSocket object is destroyed.
- virtual InputStream& GetInputStream() = 0;
-
- // Returns the OutputStream of the BleSocket.
- // On error, returned stream will report Exception::kIo on any operation.
- //
- // The returned object is not owned by the caller, and can be invalidated once
- // the BleSocket object is destroyed.
- virtual OutputStream& GetOutputStream() = 0;
-
- // Conforms to the same contract as
- // https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#close().
- //
- // Returns Exception::kIo on error, Exception::kSuccess otherwise.
- virtual Exception Close() = 0;
-
- // Returns valid BlePeripheral pointer if there is a connection, and
- // nullptr otherwise.
- virtual BlePeripheral* GetRemotePeripheral() = 0;
-};
-
-// Container of operations that can be performed over the BLE medium.
-class BleMedium {
- public:
- virtual ~BleMedium() = default;
-
- virtual bool StartAdvertising(
- const std::string& service_id, const ByteArray& advertisement_bytes,
- const std::string& fast_advertisement_service_uuid) = 0;
- virtual bool StopAdvertising(const std::string& service_id) = 0;
-
- // Callback that is invoked when a discovered peripheral is found or lost.
- struct DiscoveredPeripheralCallback {
- std::function<void(BlePeripheral& peripheral, const std::string& service_id,
- bool fast_advertisement)>
- peripheral_discovered_cb =
- DefaultCallback<BlePeripheral&, const std::string&, bool>();
- std::function<void(BlePeripheral& peripheral,
- const std::string& service_id)>
- peripheral_lost_cb =
- DefaultCallback<BlePeripheral&, const std::string&>();
- };
-
- // Returns true once the BLE scan has been initiated.
- virtual bool StartScanning(const std::string& service_id,
- const std::string& fast_advertisement_service_uuid,
- DiscoveredPeripheralCallback callback) = 0;
-
- // Returns true once BLE scanning for service_id is well and truly stopped;
- // after this returns, there must be no more invocations of the
- // DiscoveredPeripheralCallback passed in to StartScanning() for service_id.
- virtual bool StopScanning(const std::string& service_id) = 0;
-
- // Callback that is invoked when a new connection is accepted.
- struct AcceptedConnectionCallback {
- std::function<void(BleSocket& socket, const std::string& service_id)>
- accepted_cb = DefaultCallback<BleSocket&, const std::string&>();
- };
-
- // Returns true once BLE socket connection requests to service_id can be
- // accepted.
- virtual bool StartAcceptingConnections(
- const std::string& service_id, AcceptedConnectionCallback callback) = 0;
- virtual bool StopAcceptingConnections(const std::string& service_id) = 0;
-
- // Connects to a BLE peripheral.
- // On success, returns a new BleSocket.
- // On error, returns nullptr.
- virtual std::unique_ptr<BleSocket> Connect(
- BlePeripheral& peripheral, const std::string& service_id,
- CancellationFlag* cancellation_flag) = 0;
-};
-
-} // namespace api
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_API_BLE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/ble_v2.h b/chromium/third_party/nearby/src/cpp/platform/api/ble_v2.h
deleted file mode 100644
index 24ee76507a0..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/api/ble_v2.h
+++ /dev/null
@@ -1,406 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_API_BLE_V2_H_
-#define PLATFORM_API_BLE_V2_H_
-
-#include <cstdint>
-#include <limits>
-#include <map>
-#include <memory>
-#include <set>
-#include <string>
-
-#include "absl/strings/string_view.h"
-#include "absl/types/optional.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/exception.h"
-
-namespace location {
-namespace nearby {
-namespace api {
-namespace ble_v2 {
-
-// https://developer.android.com/reference/android/bluetooth/le/AdvertiseData
-//
-// Bundle of data found in a BLE advertisement.
-//
-// All service UUIDs will conform to the 16-bit Bluetooth base UUID,
-// 0000xxxx-0000-1000-8000-00805F9B34FB. This makes it possible to store two
-// byte service UUIDs in the advertisement.
-struct BleAdvertisementData {
- using TxPowerLevel = int8_t;
-
- static const TxPowerLevel kUnspecifiedTxPowerLevel =
- std::numeric_limits<TxPowerLevel>::min();
-
- bool is_connectable;
- // When set to kUnspecifiedTxPowerLevel, TX power should not be included in
- // the advertisement data.
- TxPowerLevel tx_power_level;
- // When set to an empty string, local name should not be included in the
- // advertisement data.
- std::string local_name;
- // When set to an empty vector, the set of 16-bit service class UUIDs should
- // not be included in the advertisement data.
- std::set<std::string> service_uuids;
- // Maps service UUIDs to their service data.
- std::map<std::string, ByteArray> service_data;
-};
-
-// Opaque wrapper over a BLE peripheral. Must be able to uniquely identify a
-// peripheral so that we can connect to its GATT server.
-class BlePeripheral {
- public:
- virtual ~BlePeripheral() {}
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothDevice#getAddress()
- //
- // This should be the MAC address when possible. If the implementation is
- // unable to retrieve that, any unique identifier should suffice.
- virtual std::string GetId() const = 0;
-};
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic
-//
-// Representation of a GATT characteristic.
-class GattCharacteristic {
- public:
- virtual ~GattCharacteristic() {}
-
- // Possible permissions of a GATT characteristic.
- enum class Permission {
- kUnknown = 0,
- kRead = 1,
- kWrite = 2,
- kLast,
- };
-
- // Possible properties of a GATT characteristic.
- enum class Property {
- kUnknown = 0,
- kRead = 1,
- kWrite = 2,
- kIndicate = 3,
- kLast,
- };
-
- // Returns the UUID of this characteristic.
- virtual std::string GetUuid() = 0;
-
- // Returns the UUID of the containing GATT service.
- virtual std::string GetServiceUuid() = 0;
-};
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothGatt
-//
-// Representation of a client GATT connection to a remote GATT server.
-class ClientGattConnection {
- public:
- virtual ~ClientGattConnection() {}
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#getDevice()
- //
- // Retrieves the BLE peripheral that this connection is tied to.
- virtual BlePeripheral& GetPeripheral() = 0;
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#discoverServices()
- //
- // Discovers all available services and characteristics on this connection.
- // Returns whether or not discovery finished successfully.
- //
- // This function should block until discovery has finished.
- virtual bool DiscoverServices() = 0;
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#getService(java.util.UUID)
- // https://developer.android.com/reference/android/bluetooth/BluetoothGattService.html#getCharacteristic(java.util.UUID)
- //
- // Retrieves a GATT characteristic. On error, does not return a value.
- //
- // DiscoverServices() should be called before this method to fetch all
- // available services and characteristics first.
- //
- // It is okay for duplicate services to exist, as long as the specified
- // characteristic UUID is unique among all services of the same UUID.
- virtual absl::optional<GattCharacteristic> GetCharacteristic(
- absl::string_view service_uuid,
- absl::string_view characteristic_uuid) = 0;
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#readCharacteristic(android.bluetooth.BluetoothGattCharacteristic)
- // https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html#getValue()
- //
- // Reads a GATT characteristic. No value is returned upon error.
- virtual absl::optional<ByteArray> ReadCharacteristic(
- const GattCharacteristic& characteristic) = 0;
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html#setValue(byte[])
- // https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#writeCharacteristic(android.bluetooth.BluetoothGattCharacteristic)
- //
- // Sends a remote characteristic write request to the server and returns
- // whether or not it was successful.
- virtual bool WriteCharacteristic(const GattCharacteristic& characteristic,
- const ByteArray& value) = 0;
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#disconnect()
- //
- // Disconnects a GATT connection.
- virtual void Disconnect() = 0;
-};
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothGattServer
-//
-// Representation of a server GATT connection to a remote GATT client.
-class ServerGattConnection {
- public:
- virtual ~ServerGattConnection() {}
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html#setValue(byte[])
- // https://developer.android.com/reference/android/bluetooth/BluetoothGattServer.html#notifyCharacteristicChanged(android.bluetooth.BluetoothDevice,%20android.bluetooth.BluetoothGattCharacteristic,%20boolean)
- //
- // Sends a notification (via indication) to the client that a characteristic
- // has changed with the given value. Returns whether or not it was successful.
- //
- // The value sent does not have to reflect the locally stored characteristic
- // value. To update the local value, call GattServer::UpdateCharacteristic.
- virtual bool SendCharacteristic(const GattCharacteristic& characteristic,
- const ByteArray& value) = 0;
-};
-
-// Callback for asynchronous events on the client side of a GATT connection.
-class ClientGattConnectionLifeCycleCallback {
- public:
- virtual ~ClientGattConnectionLifeCycleCallback() {}
-
- // Called when the client is disconnected from the GATT server.
- virtual void OnDisconnected(ClientGattConnection* connection) = 0;
-};
-
-// Callback for asynchronous events on the server side of a GATT connection.
-class ServerGattConnectionLifeCycleCallback {
- public:
- virtual ~ServerGattConnectionLifeCycleCallback() {}
-
- // Called when a remote peripheral connected to us and subscribed to one of
- // our characteristics.
- virtual void OnCharacteristicSubscription(
- ServerGattConnection* connection,
- const GattCharacteristic& characteristic) = 0;
-
- // Called when a remote peripheral unsubscribed from one of our
- // characteristics.
- virtual void OnCharacteristicUnsubscription(
- ServerGattConnection* connection,
- const GattCharacteristic& characteristic) = 0;
-};
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothGattServer
-//
-// Representation of a BLE GATT server.
-class GattServer {
- public:
- virtual ~GattServer() {}
-
- // Creates a characteristic and adds it to the GATT server under the given
- // characteristic and service UUIDs. Returns no value upon error.
- //
- // Characteristics of the same service UUID should be put under one
- // service rather than many services with the same UUID.
- //
- // If the INDICATE property is included, the characteristic should include the
- // official Bluetooth Client Characteristic Configuration descriptor with UUID
- // 0x2902 and a WRITE permission. This allows remote clients to write to this
- // descriptor and subscribe for characteristic changes. For more information
- // about this descriptor, please go to:
- // https://www.bluetooth.com/specifications/Gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.Gatt.client_characteristic_configuration.xml
- virtual absl::optional<GattCharacteristic> CreateCharacteristic(
- absl::string_view service_uuid, absl::string_view characteristic_uuid,
- const std::set<GattCharacteristic::Permission>& permissions,
- const std::set<GattCharacteristic::Property>& properties) = 0;
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html#setValue(byte[])
- //
- // Locally updates the value of a characteristic and returns whether or not it
- // was successful.
- // Takes ownership of (and is responsible for destroying) the passed-in
- // 'value'.
- virtual bool UpdateCharacteristic(const GattCharacteristic& characteristic,
- const ByteArray& value) = 0;
-
- // Stops a GATT server.
- virtual void Stop() = 0;
-};
-
-// A BLE socket representation.
-class BleSocket {
- public:
- virtual ~BleSocket() {}
-
- // Returns the remote BLE peripheral tied to this socket.
- virtual BlePeripheral& GetRemotePeripheral() = 0;
-
- // Writes a message on the socket and blocks until finished. Returns
- // Exception::kIo upon error, and Exception::kSuccess otherwise.
- virtual Exception Write(const ByteArray& message) = 0;
-
- // Closes the socket and blocks until finished. Returns Exception::kIo upon
- // error, and Exception::kSuccess otherwise.
- virtual Exception Close() = 0;
-};
-
-// Callback for asynchronous events on a BleSocket object.
-class BleSocketLifeCycleCallback {
- public:
- virtual ~BleSocketLifeCycleCallback() {}
-
- // Called when a message arrives on a socket.
- virtual void OnMessageReceived(BleSocket* socket,
- const ByteArray& message) = 0;
-
- // Called when a socket gets disconnected.
- virtual void OnDisconnected(BleSocket* socket) = 0;
-};
-
-// Callback for asynchronous events on the server side of a BleSocket object.
-class ServerBleSocketLifeCycleCallback : public BleSocketLifeCycleCallback {
- public:
- ~ServerBleSocketLifeCycleCallback() override {}
-
- // Called when a new incoming socket has been established.
- virtual void OnSocketEstablished(BleSocket* socket) = 0;
-};
-
-// The main BLE medium used inside of Nearby. This serves as the entry point for
-// all BLE and GATT related operations.
-class BleMedium {
- public:
- using Mtu = uint32_t;
-
- virtual ~BleMedium() {}
-
- // Coarse representation of power settings throughout all BLE operations.
- enum class PowerMode {
- kUnknown = 0,
- kLow = 1,
- kHigh = 2,
- kLast,
- };
-
- // https://developer.android.com/reference/android/bluetooth/le/BluetoothLeAdvertiser.html#startAdvertising(android.bluetooth.le.AdvertiseSettings,%20android.bluetooth.le.AdvertiseData,%20android.bluetooth.le.AdvertiseData,%20android.bluetooth.le.AdvertiseCallback)
- //
- // Starts BLE advertising and returns whether or not it was successful.
- //
- // Power mode should be interpreted in the following way:
- // LOW:
- // - Advertising interval = ~1000ms
- // - TX power = low
- // HIGH:
- // - Advertising interval = ~100ms
- // - TX power = high
- virtual bool StartAdvertising(const BleAdvertisementData& advertisement_data,
- const BleAdvertisementData& scan_response,
- PowerMode power_mode) = 0;
-
- // https://developer.android.com/reference/android/bluetooth/le/BluetoothLeAdvertiser.html#stopAdvertising(android.bluetooth.le.AdvertiseCallback)
- //
- // Stops advertising.
- virtual void StopAdvertising() = 0;
-
- // https://developer.android.com/reference/android/bluetooth/le/ScanCallback
- //
- // Callback for BLE scan results.
- class ScanCallback {
- public:
- virtual ~ScanCallback() {}
-
- // https://developer.android.com/reference/android/bluetooth/le/ScanCallback.html#onScanResult(int,%20android.bluetooth.le.ScanResult)
- //
- // Called when a BLE advertisement is discovered.
- //
- // The passed in advertisement_data is the merged combination of both
- // advertisement data and scan response.
- //
- // Every discovery of an advertisement should be reported, even if the
- // advertisement was discovered before.
- //
- // Ownership of the BleAdvertisementData transfers to the caller at this
- // point.
- virtual void OnAdvertisementFound(
- BlePeripheral* peripheral,
- const BleAdvertisementData& advertisement_data) = 0;
- };
-
- // https://developer.android.com/reference/android/bluetooth/le/BluetoothLeScanner.html#startScan(java.util.List%3Candroid.bluetooth.le.ScanFilter%3E,%20android.bluetooth.le.ScanSettings,%20android.bluetooth.le.ScanCallback)
- //
- // Starts scanning and returns whether or not it was successful.
- //
- // Power mode should be interpreted in the following way:
- // LOW:
- // - Scan window = ~512ms
- // - Scan interval = ~5120ms
- // HIGH:
- // - Scan window = ~4096ms
- // - Scan interval = ~4096ms
- virtual bool StartScanning(const std::set<std::string>& service_uuids,
- PowerMode power_mode,
- const ScanCallback& scan_callback) = 0;
-
- // https://developer.android.com/reference/android/bluetooth/le/BluetoothLeScanner.html#stopScan(android.bluetooth.le.ScanCallback)
- //
- // Stops scanning.
- virtual void StopScanning() = 0;
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothManager#openGattServer(android.content.Context,%20android.bluetooth.BluetoothGattServerCallback)
- //
- // Starts a GATT server. Returns a nullptr upon error.
- virtual std::unique_ptr<GattServer> StartGattServer(
- const ServerGattConnectionLifeCycleCallback& callback) = 0;
-
- // Starts listening for incoming BLE sockets and returns false upon error.
- virtual bool StartListeningForIncomingBleSockets(
- const ServerBleSocketLifeCycleCallback& callback) = 0;
-
- // Stops listening for incoming BLE sockets.
- virtual void StopListeningForIncomingBleSockets() = 0;
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#connectGatt(android.content.Context,%20boolean,%20android.bluetooth.BluetoothGattCallback)
- // https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#requestConnectionPriority(int)
- // https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#requestMtu(int)
- //
- // Connects to a GATT server and negotiates the specified connection
- // parameters. Returns nullptr upon error.
- //
- // Both connection interval and MTU can be negotiated on a best-effort basis.
- //
- // Power mode should be interpreted in the following way:
- // LOW:
- // - Connection interval = ~11.25ms - 15ms
- // HIGH:
- // - Connection interval = ~100ms - 125ms
- virtual std::unique_ptr<ClientGattConnection> ConnectToGattServer(
- BlePeripheral* peripheral, Mtu mtu, PowerMode power_mode,
- const ClientGattConnectionLifeCycleCallback& callback) = 0;
-
- // Establishes a BLE socket to the specified remote peripheral. Returns
- // nullptr on error.
- virtual std::unique_ptr<BleSocket> EstablishBleSocket(
- BlePeripheral* peripheral,
- const BleSocketLifeCycleCallback& callback) = 0;
-};
-
-} // namespace ble_v2
-} // namespace api
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_API_BLE_V2_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/bluetooth_classic.h b/chromium/third_party/nearby/src/cpp/platform/api/bluetooth_classic.h
deleted file mode 100644
index 9536186391f..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/api/bluetooth_classic.h
+++ /dev/null
@@ -1,162 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_API_BLUETOOTH_CLASSIC_H_
-#define PLATFORM_API_BLUETOOTH_CLASSIC_H_
-
-#include <memory>
-#include <string>
-
-#include "platform/base/byte_array.h"
-#include "platform/base/cancellation_flag.h"
-#include "platform/base/exception.h"
-#include "platform/base/input_stream.h"
-#include "platform/base/listeners.h"
-#include "platform/base/output_stream.h"
-
-namespace location {
-namespace nearby {
-namespace api {
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html.
-class BluetoothDevice {
- public:
- virtual ~BluetoothDevice() = default;
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#getName()
- virtual std::string GetName() const = 0;
-
- // Returns BT MAC address assigned to this device.
- virtual std::string GetMacAddress() const = 0;
-};
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html.
-class BluetoothSocket {
- public:
- virtual ~BluetoothSocket() = default;
-
- // NOTE:
- // It is an undefined behavior if GetInputStream() or GetOutputStream() is
- // called for a not-connected BluetoothSocket, i.e. any object that is not
- // returned by BluetoothClassicMedium::ConnectToService() for client side or
- // BluetoothServerSocket::Accept() for server side of connection.
-
- // Returns the InputStream of this connected BluetoothSocket.
- virtual InputStream& GetInputStream() = 0;
-
- // Returns the OutputStream of this connected BluetoothSocket.
- virtual OutputStream& GetOutputStream() = 0;
-
- // Closes both input and output streams, marks Socket as closed.
- // After this call object should be treated as not connected.
- // Returns Exception::kIo on error, Exception::kSuccess otherwise.
- virtual Exception Close() = 0;
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#getRemoteDevice()
- // Returns valid BluetoothDevice pointer if there is a connection, and
- // nullptr otherwise.
- virtual BluetoothDevice* GetRemoteDevice() = 0;
-};
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html.
-class BluetoothServerSocket {
- public:
- virtual ~BluetoothServerSocket() = default;
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html#accept()
- //
- // Blocks until either:
- // - at least one incoming connection request is available, or
- // - ServerSocket is closed.
- // On success, returns connected socket, ready to exchange data.
- // Returns nullptr on error.
- // Once error is reported, it is permanent, and ServerSocket has to be closed.
- virtual std::unique_ptr<BluetoothSocket> Accept() = 0;
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html#close()
- //
- // Returns Exception::kIo on error, Exception::kSuccess otherwise.
- virtual Exception Close() = 0;
-};
-
-// Container of operations that can be performed over the Bluetooth Classic
-// medium.
-class BluetoothClassicMedium {
- public:
- virtual ~BluetoothClassicMedium() = default;
-
- struct DiscoveryCallback {
- // BluetoothDevice is a proxy object created as a result of BT discovery.
- // Its lifetime spans between calls to device_discovered_cb and
- // device_lost_cb.
- // It is safe to use BluetoothDevice in device_discovered_cb() callback
- // and at any time afterwards, until device_lost_cb() is called.
- // It is not safe to use BluetoothDevice after returning from
- // device_lost_cb() callback.
- std::function<void(BluetoothDevice& device)> device_discovered_cb =
- DefaultCallback<BluetoothDevice&>();
- std::function<void(BluetoothDevice& device)> device_name_changed_cb =
- DefaultCallback<BluetoothDevice&>();
- std::function<void(BluetoothDevice& device)> device_lost_cb =
- DefaultCallback<BluetoothDevice&>();
- };
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#startDiscovery()
- //
- // Returns true once the process of discovery has been initiated.
- virtual bool StartDiscovery(DiscoveryCallback discovery_callback) = 0;
- // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#cancelDiscovery()
- //
- // Returns true once discovery is well and truly stopped; after this returns,
- // there must be no more invocations of the DiscoveryCallback passed in to
- // StartDiscovery().
- virtual bool StopDiscovery() = 0;
-
- // A combination of
- // https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#createInsecureRfcommSocketToServiceRecord
- // followed by
- // https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#connect().
- //
- // service_uuid is the canonical textual representation
- // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format) of a
- // type 3 name-based
- // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based))
- // UUID.
- //
- // On success, returns a new BluetoothSocket.
- // On error, returns nullptr.
- virtual std::unique_ptr<BluetoothSocket> ConnectToService(
- BluetoothDevice& remote_device, const std::string& service_uuid,
- CancellationFlag* cancellation_flag) = 0;
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#listenUsingInsecureRfcommWithServiceRecord
- //
- // service_uuid is the canonical textual representation
- // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format) of a
- // type 3 name-based
- // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based))
- // UUID.
- //
- // Returns nullptr error.
- virtual std::unique_ptr<BluetoothServerSocket> ListenForService(
- const std::string& service_name, const std::string& service_uuid) = 0;
-
- virtual BluetoothDevice* GetRemoteDevice(const std::string& mac_address) = 0;
-};
-
-} // namespace api
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_API_BLUETOOTH_CLASSIC_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/condition_variable.h b/chromium/third_party/nearby/src/cpp/platform/api/condition_variable.h
deleted file mode 100644
index a60f813741b..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/api/condition_variable.h
+++ /dev/null
@@ -1,51 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_API_CONDITION_VARIABLE_H_
-#define PLATFORM_API_CONDITION_VARIABLE_H_
-
-#include "absl/time/clock.h"
-#include "platform/base/exception.h"
-
-namespace location {
-namespace nearby {
-namespace api {
-
-// The ConditionVariable class is a synchronization primitive that can be used
-// to block a thread, or multiple threads at the same time, until another thread
-// both modifies a shared variable (the condition), and notifies the
-// ConditionVariable.
-class ConditionVariable {
- public:
- virtual ~ConditionVariable() {}
-
- // Notifies all the waiters that condition state has changed.
- virtual void Notify() = 0;
-
- // Waits indefinitely for Notify to be called.
- // May return prematurely in case of interrupt, if supported by platform.
- // Returns kSuccess, or kInterrupted on interrupt.
- virtual Exception Wait() = 0;
-
- // Waits while timeout has not expired for Notify to be called.
- // May return prematurely in case of interrupt, if supported by platform.
- // Returns kSuccess, or kInterrupted on interrupt.
- virtual Exception Wait(absl::Duration timeout) = 0;
-};
-
-} // namespace api
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_API_CONDITION_VARIABLE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/count_down_latch.h b/chromium/third_party/nearby/src/cpp/platform/api/count_down_latch.h
deleted file mode 100644
index 9af3b9a855e..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/api/count_down_latch.h
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_API_COUNT_DOWN_LATCH_H_
-#define PLATFORM_API_COUNT_DOWN_LATCH_H_
-
-#include <cstdint>
-
-#include "absl/time/time.h"
-#include "platform/base/exception.h"
-
-namespace location {
-namespace nearby {
-namespace api {
-
-// A synchronization aid that allows one or more threads to wait until a set of
-// operations being performed in other threads completes.
-//
-// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html
-class CountDownLatch {
- public:
- virtual ~CountDownLatch() = default;
-
- virtual Exception Await() = 0; // throws Exception::kInterrupted
- virtual ExceptionOr<bool> Await(
- absl::Duration timeout) = 0; // throws Exception::kInterrupted
- virtual void CountDown() = 0;
-};
-
-} // namespace api
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_API_COUNT_DOWN_LATCH_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/crypto.h b/chromium/third_party/nearby/src/cpp/platform/api/crypto.h
deleted file mode 100644
index 365e1f84c35..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/api/crypto.h
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_API_CRYPTO_H_
-#define PLATFORM_API_CRYPTO_H_
-
-#include "absl/strings/string_view.h"
-#include "platform/base/byte_array.h"
-
-namespace location {
-namespace nearby {
-
-// A provider of standard hashing algorithms.
-class Crypto {
- public:
- // Initialize global crypto state.
- static void Init();
- // Return MD5 hash of input.
- static ByteArray Md5(absl::string_view input);
- // Return SHA256 hash of input.
- static ByteArray Sha256(absl::string_view input);
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_API_CRYPTO_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/executor.h b/chromium/third_party/nearby/src/cpp/platform/api/executor.h
deleted file mode 100644
index af96ee609f2..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/api/executor.h
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_API_EXECUTOR_H_
-#define PLATFORM_API_EXECUTOR_H_
-
-#include "platform/base/runnable.h"
-
-namespace location {
-namespace nearby {
-namespace api {
-
-int GetCurrentTid();
-
-// This abstract class is the superclass of all classes representing an
-// Executor.
-class Executor {
- public:
- // Before returning from destructor, executor must wait for all pending
- // jobs to finish.
- virtual ~Executor() = default;
- // https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-
- virtual void Execute(Runnable&& runnable) = 0;
-
- // https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#shutdown--
- virtual void Shutdown() = 0;
-};
-
-} // namespace api
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_API_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/future.h b/chromium/third_party/nearby/src/cpp/platform/api/future.h
deleted file mode 100644
index bf423c79153..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/api/future.h
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_API_FUTURE_H_
-#define PLATFORM_API_FUTURE_H_
-
-#include "absl/time/clock.h"
-#include "platform/base/exception.h"
-
-namespace location {
-namespace nearby {
-namespace api {
-
-// A Future represents the result of an asynchronous computation.
-//
-// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html
-template <typename T>
-class Future {
- public:
- virtual ~Future() = default;
-
- // throws Exception::kInterrupted, Exception::kExecution
- virtual ExceptionOr<T> Get() = 0;
-
- // throws Exception::kInterrupted, Exception::kExecution
- // throws Exception::kTimeout if timeout is exceeded while waiting for
- // result.
- virtual ExceptionOr<T> Get(absl::Duration timeout) = 0;
-};
-
-} // namespace api
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_API_FUTURE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/input_file.h b/chromium/third_party/nearby/src/cpp/platform/api/input_file.h
deleted file mode 100644
index f566e804274..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/api/input_file.h
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_API_INPUT_FILE_H_
-#define PLATFORM_API_INPUT_FILE_H_
-
-#include <cstdint>
-
-#include "platform/base/byte_array.h"
-#include "platform/base/exception.h"
-#include "platform/base/input_stream.h"
-
-namespace location {
-namespace nearby {
-namespace api {
-
-// An InputFile represents a readable file on the system.
-class InputFile : public InputStream {
- public:
- ~InputFile() override = default;
- virtual std::string GetFilePath() const = 0;
- virtual std::int64_t GetTotalSize() const = 0;
-};
-
-} // namespace api
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_API_INPUT_FILE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/listenable_future.h b/chromium/third_party/nearby/src/cpp/platform/api/listenable_future.h
deleted file mode 100644
index 17911f47f4a..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/api/listenable_future.h
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_API_LISTENABLE_FUTURE_H_
-#define PLATFORM_API_LISTENABLE_FUTURE_H_
-
-#include <functional>
-#include <memory>
-
-#include "platform/api/executor.h"
-#include "platform/api/future.h"
-#include "platform/base/exception.h"
-#include "platform/base/runnable.h"
-
-namespace location {
-namespace nearby {
-namespace api {
-
-// A Future that accepts completion listeners.
-//
-// https://guava.dev/releases/20.0/api/docs/com/google/common/util/concurrent/ListenableFuture.html
-template <typename T>
-class ListenableFuture : public Future<T> {
- public:
- ~ListenableFuture() override = default;
-
- virtual void AddListener(Runnable runnable, Executor* executor) = 0;
-};
-
-} // namespace api
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_API_LISTENABLE_FUTURE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/output_file.h b/chromium/third_party/nearby/src/cpp/platform/api/output_file.h
deleted file mode 100644
index a6176e53ca3..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/api/output_file.h
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_API_OUTPUT_FILE_H_
-#define PLATFORM_API_OUTPUT_FILE_H_
-
-#include "platform/base/byte_array.h"
-#include "platform/base/exception.h"
-#include "platform/base/output_stream.h"
-
-namespace location {
-namespace nearby {
-namespace api {
-
-// An OutputFile represents a writable file on the system.
-class OutputFile : public OutputStream {
- public:
- ~OutputFile() override = default;
-};
-
-} // namespace api
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_API_OUTPUT_FILE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/platform.h b/chromium/third_party/nearby/src/cpp/platform/api/platform.h
deleted file mode 100644
index 6cf54cae44a..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/api/platform.h
+++ /dev/null
@@ -1,111 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_API_PLATFORM_H_
-#define PLATFORM_API_PLATFORM_H_
-
-#include <cstdint>
-#include <memory>
-#include <string>
-
-#include "absl/strings/string_view.h"
-#include "platform/api/atomic_boolean.h"
-#include "platform/api/atomic_reference.h"
-#include "platform/api/ble.h"
-#include "platform/api/ble_v2.h"
-#include "platform/api/bluetooth_adapter.h"
-#include "platform/api/bluetooth_classic.h"
-#include "platform/api/condition_variable.h"
-#include "platform/api/count_down_latch.h"
-#include "platform/api/crypto.h"
-#include "platform/api/input_file.h"
-#include "platform/api/log_message.h"
-#include "platform/api/mutex.h"
-#include "platform/api/output_file.h"
-#include "platform/api/scheduled_executor.h"
-#include "platform/api/server_sync.h"
-#include "platform/api/settable_future.h"
-#include "platform/api/submittable_executor.h"
-#include "platform/api/system_clock.h"
-#include "platform/api/webrtc.h"
-#include "platform/api/wifi.h"
-#include "platform/api/wifi_lan.h"
-#include "platform/base/payload_id.h"
-
-namespace location {
-namespace nearby {
-namespace api {
-
-// API rework notes:
-// https://docs.google.com/spreadsheets/d/1erZNkX7pX8s5jWTHdxgjntxTMor3BGiY2H_fC_ldtoQ/edit#gid=381357998
-class ImplementationPlatform {
- public:
- // General platform support:
- // - atomic variables (boolean, and any other copyable type)
- // - synchronization primitives:
- // - mutex (regular, and recursive)
- // - condition variable (must work with regular mutex only)
- // - Future<T> : to synchronize on Callable<T> scheduled to execute.
- // - CountDownLatch : to ensure at least N threads are waiting.
- // - file I/O
- // - Logging
-
- // Atomics:
- // =======
-
- // Atomic boolean: special case. Uses native platform atomics.
- // Does not use locking.
- // Does not use dynamic memory allocations in operations.
- static std::unique_ptr<AtomicBoolean> CreateAtomicBoolean(bool initial_value);
-
- // Supports enums and integers up to 32-bit.
- // Does not use locking, if platform supports 32-bit atimics natively.
- // Does not use dynamic memory allocations in operations.
- static std::unique_ptr<AtomicUint32> CreateAtomicUint32(std::uint32_t value);
-
- static std::unique_ptr<CountDownLatch> CreateCountDownLatch(
- std::int32_t count);
- static std::unique_ptr<Mutex> CreateMutex(Mutex::Mode mode);
- static std::unique_ptr<ConditionVariable> CreateConditionVariable(
- Mutex* mutex);
- static std::unique_ptr<InputFile> CreateInputFile(PayloadId payload_id,
- std::int64_t total_size);
- static std::unique_ptr<OutputFile> CreateOutputFile(PayloadId payload_id);
- static std::unique_ptr<LogMessage> CreateLogMessage(
- const char* file, int line, LogMessage::Severity severity);
-
- // Java-like Executors
- static std::unique_ptr<SubmittableExecutor> CreateSingleThreadExecutor();
- static std::unique_ptr<SubmittableExecutor> CreateMultiThreadExecutor(
- std::int32_t max_concurrency);
- static std::unique_ptr<ScheduledExecutor> CreateScheduledExecutor();
-
- // Protocol implementations, domain-specific support
- static std::unique_ptr<BluetoothAdapter> CreateBluetoothAdapter();
- static std::unique_ptr<BluetoothClassicMedium> CreateBluetoothClassicMedium(
- BluetoothAdapter&);
- static std::unique_ptr<BleMedium> CreateBleMedium(BluetoothAdapter&);
- static std::unique_ptr<ble_v2::BleMedium> CreateBleV2Medium(
- BluetoothAdapter&);
- static std::unique_ptr<ServerSyncMedium> CreateServerSyncMedium();
- static std::unique_ptr<WifiMedium> CreateWifiMedium();
- static std::unique_ptr<WifiLanMedium> CreateWifiLanMedium();
- static std::unique_ptr<WebRtcMedium> CreateWebRtcMedium();
-};
-
-} // namespace api
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_API_PLATFORM_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/scheduled_executor.h b/chromium/third_party/nearby/src/cpp/platform/api/scheduled_executor.h
deleted file mode 100644
index 0a5f4843c23..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/api/scheduled_executor.h
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_API_SCHEDULED_EXECUTOR_H_
-#define PLATFORM_API_SCHEDULED_EXECUTOR_H_
-
-#include <cstdint>
-#include <functional>
-#include <memory>
-
-#include "absl/time/time.h"
-#include "platform/api/cancelable.h"
-#include "platform/api/executor.h"
-#include "platform/base/runnable.h"
-
-namespace location {
-namespace nearby {
-namespace api {
-
-// An Executor that can schedule commands to run after a given delay, or to
-// execute periodically.
-//
-// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html
-class ScheduledExecutor : public Executor {
- public:
- ~ScheduledExecutor() override = default;
- // Cancelable is kept both in the executor context, and in the caller context.
- // We want Cancelable to live until both caller and executor are done with it.
- // Exclusive ownership model does not work for this case;
- // using std:shared_ptr<> instead if std::unique_ptr<>.
- virtual std::shared_ptr<Cancelable> Schedule(Runnable&& runnable,
- absl::Duration duration) = 0;
-};
-
-} // namespace api
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_API_SCHEDULED_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/server_sync.h b/chromium/third_party/nearby/src/cpp/platform/api/server_sync.h
deleted file mode 100644
index 16861c578e7..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/api/server_sync.h
+++ /dev/null
@@ -1,76 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_API_SERVER_SYNC_H_
-#define PLATFORM_API_SERVER_SYNC_H_
-
-#include <string>
-
-#include "absl/strings/string_view.h"
-#include "platform/base/byte_array.h"
-
-namespace location {
-namespace nearby {
-namespace api {
-
-// Abstraction that represents a Nearby endpoint exchanging data through
-// ServerSync Medium.
-class ServerSyncDevice {
- public:
- virtual ~ServerSyncDevice() = default;
-
- virtual std::string GetName() const = 0;
- virtual std::string GetGuid() const = 0;
- virtual std::string GetOwnGuid() const = 0;
-};
-
-// Container of operations that can be performed over the Chrome Sync medium.
-class ServerSyncMedium {
- public:
- virtual ~ServerSyncMedium() = default;
-
- virtual bool StartAdvertising(absl::string_view service_id,
- absl::string_view endpoint_id,
- const ByteArray& endpoint_info) = 0;
- virtual void StopAdvertising(absl::string_view service_id) = 0;
-
- class DiscoveredDeviceCallback {
- public:
- virtual ~DiscoveredDeviceCallback() = default;
-
- // Called on a new ServerSyncDevice discovery.
- virtual void OnDeviceDiscovered(ServerSyncDevice* device,
- absl::string_view service_id,
- absl::string_view endpoint_id,
- const ByteArray& endpoint_info) = 0;
- // Called when ServerSyncDevice is no longer reachable.
- virtual void OnDeviceLost(ServerSyncDevice* device,
- absl::string_view service_id) = 0;
- };
-
- // Returns true once the Chrome Sync scan has been initiated.
- virtual bool StartDiscovery(
- absl::string_view service_id,
- const DiscoveredDeviceCallback& discovered_device_callback) = 0;
- // Returns true once Chrome Sync scan for service_id is well and truly
- // stopped; after this returns, there must be no more invocations of the
- // DiscoveredDeviceCallback passed in to startScanning() for service_id.
- virtual void StopDiscovery(absl::string_view service_id) = 0;
-};
-
-} // namespace api
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_API_SERVER_SYNC_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/settable_future.h b/chromium/third_party/nearby/src/cpp/platform/api/settable_future.h
deleted file mode 100644
index ebbe57cc3d6..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/api/settable_future.h
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_API_SETTABLE_FUTURE_H_
-#define PLATFORM_API_SETTABLE_FUTURE_H_
-
-#include "platform/api/listenable_future.h"
-#include "platform/base/exception.h"
-
-namespace location {
-namespace nearby {
-namespace api {
-
-// A SettableFuture is a type of Future whose result can be set.
-//
-// https://google.github.io/guava/releases/20.0/api/docs/com/google/common/util/concurrent/SettableFuture.html
-template <typename T>
-class SettableFuture : public ListenableFuture<T> {
- public:
- ~SettableFuture() override = default;
-
- // Completes the future successfully. The value is returned to any waiters.
- // Returns true, if value was set.
- // Returns false, if Future is already in "done" state.
- virtual bool Set(T value) = 0;
-
- // Completes the future unsuccessfully. The exception value is returned to any
- // waiters.
- // Returns true, if exception was set.
- // Returns false, if Future is already in "done" state.
- virtual bool SetException(Exception exception) = 0;
-};
-
-} // namespace api
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_API_SETTABLE_FUTURE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/submittable_executor.h b/chromium/third_party/nearby/src/cpp/platform/api/submittable_executor.h
deleted file mode 100644
index 0017c846240..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/api/submittable_executor.h
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_API_SUBMITTABLE_EXECUTOR_H_
-#define PLATFORM_API_SUBMITTABLE_EXECUTOR_H_
-
-#include <functional>
-#include <memory>
-
-#include "platform/api/executor.h"
-#include "platform/api/future.h"
-#include "platform/base/runnable.h"
-
-namespace location {
-namespace nearby {
-namespace api {
-
-// Main interface to be used by platform as a base class for
-// - MultiThreadExecutorWrapper
-// - SingleThreadExecutorWrapper
-// Platform must override bool submit(std::function<void()>) method.
-class SubmittableExecutor : public Executor {
- public:
- ~SubmittableExecutor() override = default;
-
- // Submit a callable (with no delay).
- // Returns true, if callable was submitted, false otherwise.
- // Callable is not submitted if shutdown is in progress.
- virtual bool DoSubmit(Runnable&& wrapped_callable) = 0;
-};
-
-} // namespace api
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_API_SUBMITTABLE_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/system_clock.h b/chromium/third_party/nearby/src/cpp/platform/api/system_clock.h
deleted file mode 100644
index a4caadaa2d7..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/api/system_clock.h
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_API_SYSTEM_CLOCK_H_
-#define PLATFORM_API_SYSTEM_CLOCK_H_
-
-#include "absl/time/clock.h"
-#include "platform/base/exception.h"
-
-namespace location {
-namespace nearby {
-
-class SystemClock final {
- public:
- // Initialize global system state.
- static void Init();
- // Returns current absolute time. It is guaranteed to be monotonic.
- static absl::Time ElapsedRealtime();
- // Pauses current thread for the specified duration.
- static Exception Sleep(absl::Duration duration);
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_API_SYSTEM_CLOCK_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/webrtc.h b/chromium/third_party/nearby/src/cpp/platform/api/webrtc.h
deleted file mode 100644
index ede07072b33..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/api/webrtc.h
+++ /dev/null
@@ -1,73 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_API_WEBRTC_H_
-#define PLATFORM_API_WEBRTC_H_
-
-#include <functional>
-#include <memory>
-#include <string>
-
-#include "absl/strings/string_view.h"
-#include "platform/base/byte_array.h"
-#include "proto/connections/offline_wire_formats.pb.h"
-#include "webrtc/api/peer_connection_interface.h"
-
-namespace location {
-namespace nearby {
-namespace api {
-
-class WebRtcSignalingMessenger {
- public:
- using OnSignalingMessageCallback = std::function<void(const ByteArray&)>;
- using OnSignalingCompleteCallback = std::function<void(bool)>;
-
- virtual ~WebRtcSignalingMessenger() = default;
-
- virtual bool SendMessage(absl::string_view peer_id,
- const ByteArray& message) = 0;
-
- virtual bool StartReceivingMessages(
- OnSignalingMessageCallback on_message_callback,
- OnSignalingCompleteCallback on_complete_callback) = 0;
- virtual void StopReceivingMessages() = 0;
-};
-
-class WebRtcMedium {
- public:
- using PeerConnectionCallback =
- std::function<void(rtc::scoped_refptr<webrtc::PeerConnectionInterface>)>;
-
- virtual ~WebRtcMedium() = default;
-
- // Gets the default two-letter country code associated with current locale.
- // For example, en_US locale resolves to "US".
- virtual const std::string GetDefaultCountryCode() = 0;
-
- // Creates and returns a new webrtc::PeerConnectionInterface object via
- // |callback|.
- virtual void CreatePeerConnection(webrtc::PeerConnectionObserver* observer,
- PeerConnectionCallback callback) = 0;
-
- // Returns a signaling messenger for sending WebRTC signaling messages.
- virtual std::unique_ptr<WebRtcSignalingMessenger> GetSignalingMessenger(
- absl::string_view self_id,
- const connections::LocationHint& location_hint) = 0;
-};
-
-} // namespace api
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_API_WEBRTC_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/wifi_lan.h b/chromium/third_party/nearby/src/cpp/platform/api/wifi_lan.h
deleted file mode 100644
index 9ba40a38c9c..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/api/wifi_lan.h
+++ /dev/null
@@ -1,153 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_API_WIFI_LAN_H_
-#define PLATFORM_API_WIFI_LAN_H_
-
-#include <string>
-
-#include "platform/base/cancellation_flag.h"
-#include "platform/base/input_stream.h"
-#include "platform/base/listeners.h"
-#include "platform/base/nsd_service_info.h"
-#include "platform/base/output_stream.h"
-
-namespace location {
-namespace nearby {
-namespace api {
-
-class WifiLanSocket {
- public:
- virtual ~WifiLanSocket() = default;
-
- // Returns the InputStream of the WifiLanSocket.
- // On error, returned stream will report Exception::kIo on any operation.
- //
- // The returned object is not owned by the caller, and can be invalidated once
- // the WifiLanSocket object is destroyed.
- virtual InputStream& GetInputStream() = 0;
-
- // Returns the OutputStream of the WifiLanSocket.
- // On error, returned stream will report Exception::kIo on any operation.
- //
- // The returned object is not owned by the caller, and can be invalidated once
- // the WifiLanSocket object is destroyed.
- virtual OutputStream& GetOutputStream() = 0;
-
- // Returns Exception::kIo on error, Exception::kSuccess otherwise.
- virtual Exception Close() = 0;
-};
-
-class WifiLanServerSocket {
- public:
- virtual ~WifiLanServerSocket() = default;
-
- // Returns ip address.
- virtual std::string GetIPAddress() const = 0;
-
- // Returns port.
- virtual int GetPort() const = 0;
-
- // Blocks until either:
- // - at least one incoming connection request is available, or
- // - ServerSocket is closed.
- // On success, returns connected socket, ready to exchange data.
- // Returns nullptr on error.
- // Once error is reported, it is permanent, and ServerSocket has to be closed.
- virtual std::unique_ptr<WifiLanSocket> Accept() = 0;
-
- // Returns Exception::kIo on error, Exception::kSuccess otherwise.
- virtual Exception Close() = 0;
-};
-
-// Container of operations that can be performed over the WifiLan medium.
-class WifiLanMedium {
- public:
- virtual ~WifiLanMedium() = default;
-
- // Starts WifiLan advertising.
- //
- // nsd_service_info - NsdServiceInfo data that's advertised through mDNS
- // service.
- // On success if the service is now advertising.
- // On error if the service cannot start to advertise or the service type in
- // NsdServiceInfo has been passed previously which StopAdvertising is not
- // been called.
- virtual bool StartAdvertising(const NsdServiceInfo& nsd_service_info) = 0;
-
- // Stops WifiLan advertising.
- //
- // nsd_service_info - NsdServiceInfo data that's advertised through mDNS
- // service.
- // On success if the service stops advertising.
- // On error if the service cannot stop advertising or the service type in
- // NsdServiceInfo cannot be found.
- virtual bool StopAdvertising(const NsdServiceInfo& nsd_service_info) = 0;
-
- // Callback that is invoked when a discovered service is found or lost.
- struct DiscoveredServiceCallback {
- std::function<void(NsdServiceInfo service_info)> service_discovered_cb =
- DefaultCallback<NsdServiceInfo>();
- std::function<void(NsdServiceInfo service_info)> service_lost_cb =
- DefaultCallback<NsdServiceInfo>();
- };
-
- // Starts the discovery of nearby WifiLan services.
- //
- // service_type - mDNS service type.
- // callback - the instance of DiscoveredServiceCallback.
- // Returns true once the WifiLan discovery has been initiated. The
- // service_type is associated with callback.
- virtual bool StartDiscovery(const std::string& service_type,
- DiscoveredServiceCallback callback) = 0;
-
- // Stops the discovery of nearby WifiLan services.
- //
- // service_type - The one assigned in StartDiscovery.
- // On success if the service_type is matched to the callback and will be
- // removed from the list. If list is empty then stops the WifiLan
- // discovery service.
- // On error if the service_type is not existed, then return immediately.
- virtual bool StopDiscovery(const std::string& service_type) = 0;
-
- // Connects to a WifiLan service.
- // On success, returns a new WifiLanSocket.
- // On error, returns nullptr.
- virtual std::unique_ptr<WifiLanSocket> ConnectToService(
- const NsdServiceInfo& remote_service_info,
- CancellationFlag* cancellation_flag) = 0;
-
- // Connects to a WifiLan service by ip address and port.
- // On success, returns a new WifiLanSocket.
- // On error, returns nullptr.
- virtual std::unique_ptr<WifiLanSocket> ConnectToService(
- const std::string& ip_address, int port,
- CancellationFlag* cancellation_flag) = 0;
-
- // Listens for incoming connection.
- //
- // port - A port number.
- // 0 : use a random port.
- // 1~65536 : open a server socket on that exact port.
- // On success, returns a new WifiLanServerSocket.
- // On error, returns nullptr.
- virtual std::unique_ptr<WifiLanServerSocket> ListenForService(
- int port = 0) = 0;
-};
-
-} // namespace api
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_API_WIFI_LAN_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/BUILD b/chromium/third_party/nearby/src/cpp/platform/base/BUILD
deleted file mode 100644
index a7cdf16c5d1..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/BUILD
+++ /dev/null
@@ -1,243 +0,0 @@
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# https://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-load("//ads/util/non_compile:non_compile.bzl", "cc_with_non_compile_test")
-
-licenses(["notice"])
-
-cc_library(
- name = "base",
- srcs = [
- "base64_utils.cc",
- "bluetooth_utils.cc",
- "input_stream.cc",
- "nsd_service_info.cc",
- "prng.cc",
- ],
- hdrs = [
- "base64_utils.h",
- "bluetooth_utils.h",
- "byte_array.h",
- "callable.h",
- "exception.h",
- "feature_flags.h",
- "input_stream.h",
- "listeners.h",
- "nsd_service_info.h",
- "output_stream.h",
- "payload_id.h",
- "prng.h",
- "runnable.h",
- "socket.h",
- "types.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- copts = ["-DCORE_ADAPTER_DLL"],
- visibility = [
- "//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
- "//analytics:__subpackages__",
- "//third_party/nearby_connections/cpp/cal:__subpackages__",
- "//core:__subpackages__",
- "//platform:__subpackages__",
- "//platform/api:__subpackages__",
- "//proto/analytics:__subpackages__",
- ],
- deps = [
- "//absl/container:flat_hash_map",
- "//absl/meta:type_traits",
- "//absl/strings",
- "//absl/strings:str_format",
- "//absl/synchronization",
- "//absl/time",
- ],
-)
-
-cc_library(
- name = "util",
- srcs = [
- "base_input_stream.cc",
- "base_pipe.cc",
- "byte_utils.cc",
- ],
- hdrs = [
- "base_input_stream.h",
- "base_mutex_lock.h",
- "base_pipe.h",
- "byte_utils.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- visibility = [
- "//core:__subpackages__",
- "//platform/impl:__subpackages__",
- "//platform/public:__pkg__",
- ],
- deps = [
- ":base",
- "//absl/base:core_headers",
- "//absl/strings:str_format",
- "//platform/api:types",
- ],
-)
-
-cc_library(
- name = "logging",
- hdrs = [
- "logging.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- visibility = [
- "//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
- "//platform:__subpackages__",
- ],
- deps = [
- "//base:logging",
- "//platform/api:platform",
- "//platform/api:types",
- ],
-)
-
-cc_library(
- name = "cancellation_flag",
- srcs = [
- "cancellation_flag.cc",
- ],
- hdrs = [
- "cancellation_flag.h",
- "cancellation_flag_listener.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- visibility = [
- "//core/internal:__subpackages__",
- "//platform/api:__subpackages__",
- "//platform/impl:__subpackages__",
- "//platform/public:__pkg__",
- ],
- deps = [
- ":base",
- ":util",
- "//absl/container:flat_hash_set",
- "//absl/synchronization",
- ],
-)
-
-cc_library(
- name = "error_code_recorder",
- srcs = [
- "error_code_recorder.cc",
- ],
- hdrs = [
- "error_code_params.h",
- "error_code_recorder.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- visibility = [
- "//analytics:__subpackages__",
- "//core/internal:__subpackages__",
- "//platform/impl:__subpackages__",
- ],
- deps = [
- ":logging",
- "//proto:connections_enums_portable_proto",
- "//proto/errorcode:error_code_enums_portable_proto",
- ],
-)
-
-cc_library(
- name = "test_util",
- testonly = True,
- srcs = [
- "medium_environment.cc",
- ],
- hdrs = [
- "medium_environment.h",
- ],
- visibility = [
- "//core:__subpackages__",
- "//platform/impl:__subpackages__",
- "//platform/public:__pkg__",
- ],
- deps = [
- ":base",
- ":logging",
- "//absl/container:flat_hash_map",
- "//absl/strings",
- "//platform/api:comm",
- "//platform/public:types",
- ],
-)
-
-cc_test(
- name = "platform_base_test",
- srcs = [
- "bluetooth_utils_test.cc",
- "byte_array_test.cc",
- "feature_flags_test.cc",
- "prng_test.cc",
- ],
- deps = [
- ":base",
- ":test_util",
- "//testing/base/public:gunit_main",
- "//platform/impl/g3", # build_cleaner: keep
- ],
-)
-
-cc_test(
- name = "platform_util_test",
- srcs = [
- "byte_utils_test.cc",
- ],
- deps = [
- ":base",
- ":util",
- "//testing/base/public:gunit_main",
- ],
-)
-
-cc_test(
- name = "cancellation_flag_test",
- srcs = [
- "cancellation_flag_test.cc",
- ],
- deps = [
- ":base",
- ":cancellation_flag",
- ":test_util",
- "//testing/base/public:gunit_main",
- "//platform/impl/g3", # build_cleaner: keep
- ],
-)
-
-cc_test(
- name = "error_code_recorder_test",
- srcs = [
- "error_code_recorder_test.cc",
- ],
- deps = [
- ":error_code_recorder",
- ":test_util",
- "//testing/base/public:gunit_main",
- "//platform/impl/g3", # build_cleaner: keep
- ],
-)
-
-cc_with_non_compile_test(
- name = "exception_test",
- srcs = [
- "exception_test.cc",
- ],
- deps = [
- ":base",
- "//testing/base/public:gunit_main",
- ],
-)
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/base64_utils.cc b/chromium/third_party/nearby/src/cpp/platform/base/base64_utils.cc
deleted file mode 100644
index a8e1e86bda7..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/base64_utils.cc
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/base/base64_utils.h"
-
-#include "absl/strings/escaping.h"
-#include "platform/base/byte_array.h"
-
-namespace location {
-namespace nearby {
-
-std::string Base64Utils::Encode(const ByteArray& bytes) {
- std::string base64_string;
-
- absl::WebSafeBase64Escape(std::string(bytes), &base64_string);
-
- return base64_string;
-}
-
-ByteArray Base64Utils::Decode(absl::string_view base64_string) {
- std::string decoded_string;
- if (!absl::WebSafeBase64Unescape(base64_string, &decoded_string)) {
- return ByteArray();
- }
-
- return ByteArray(decoded_string.data(), decoded_string.size());
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/base64_utils.h b/chromium/third_party/nearby/src/cpp/platform/base/base64_utils.h
deleted file mode 100644
index 656ef895d9f..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/base64_utils.h
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_BASE_BASE64_UTILS_H_
-#define PLATFORM_BASE_BASE64_UTILS_H_
-
-#include "absl/strings/string_view.h"
-#include "platform/base/byte_array.h"
-
-namespace location {
-namespace nearby {
-
-class Base64Utils {
- public:
- static std::string Encode(const ByteArray& bytes);
- static ByteArray Decode(absl::string_view base64_string);
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_BASE_BASE64_UTILS_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/base_input_stream.cc b/chromium/third_party/nearby/src/cpp/platform/base/base_input_stream.cc
deleted file mode 100644
index 6aedb6896c1..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/base_input_stream.cc
+++ /dev/null
@@ -1,99 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/base/base_input_stream.h"
-
-namespace location {
-namespace nearby {
-
-ExceptionOr<ByteArray> BaseInputStream::Read(std::int64_t size) {
- if (!IsAvailable(size)) {
- return ExceptionOr<ByteArray>{Exception::kIo};
- }
-
- ByteArray read_bytes{static_cast<size_t>(size)};
- if (read_bytes.CopyAt(/*offset=*/0, buffer_,
- /*source_offset=*/position_)) {
- position_ += size;
- return ExceptionOr<ByteArray>{read_bytes};
- } else {
- return ExceptionOr<ByteArray>{Exception::kIo};
- }
-}
-
-std::uint8_t BaseInputStream::ReadUint8() {
- constexpr int byte_size = sizeof(std::uint8_t);
- ByteArray read_bytes = ReadBytes(byte_size);
- if (read_bytes.Empty() || read_bytes.size() != byte_size) {
- return -1;
- }
-
- return read_bytes.data()[0];
-}
-
-std::uint16_t BaseInputStream::ReadUint16() {
- constexpr int byte_size = sizeof(std::uint16_t);
- ByteArray read_bytes = ReadBytes(byte_size);
- if (read_bytes.Empty() || read_bytes.size() != byte_size) {
- return -1;
- }
-
- // Convert from network order.
- const char *data = read_bytes.data();
- return static_cast<uint16_t>(data[0]) << 8 | static_cast<uint16_t>(data[1]);
-}
-
-std::uint32_t BaseInputStream::ReadUint32() {
- constexpr int byte_size = sizeof(std::uint32_t);
- ByteArray read_bytes = ReadBytes(byte_size);
- if (read_bytes.Empty() || read_bytes.size() != byte_size) {
- return -1;
- }
-
- // Convert from network order.
- const char *data = read_bytes.data();
- return static_cast<uint32_t>(data[0]) << 24 |
- static_cast<uint32_t>(data[1]) << 16 |
- static_cast<uint32_t>(data[2]) << 8 | static_cast<uint32_t>(data[3]);
-}
-
-std::uint64_t BaseInputStream::ReadUint64() {
- constexpr int byte_size = sizeof(std::uint64_t);
- ByteArray read_bytes = ReadBytes(byte_size);
- if (read_bytes.Empty() || read_bytes.size() != byte_size) {
- return -1;
- }
-
- // Convert from network order.
- const char *data = read_bytes.data();
- return static_cast<uint64_t>(data[0]) << 56 |
- static_cast<uint64_t>(data[1]) << 48 |
- static_cast<uint64_t>(data[2]) << 40 |
- static_cast<uint64_t>(data[3]) << 32 |
- static_cast<uint64_t>(data[4]) << 24 |
- static_cast<uint64_t>(data[5]) << 16 |
- static_cast<uint64_t>(data[6]) << 8 | static_cast<uint64_t>(data[7]);
-}
-
-ByteArray BaseInputStream::ReadBytes(int size) {
- ExceptionOr<ByteArray> read_bytes_result = Read(size);
- if (!read_bytes_result.ok()) {
- return ByteArray{};
- }
-
- return read_bytes_result.GetResult();
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/base_input_stream.h b/chromium/third_party/nearby/src/cpp/platform/base/base_input_stream.h
deleted file mode 100644
index 45c77436301..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/base_input_stream.h
+++ /dev/null
@@ -1,63 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_BASE_BASE_INPUT_STREAM_H_
-#define PLATFORM_BASE_BASE_INPUT_STREAM_H_
-
-#include "platform/base/byte_array.h"
-#include "platform/base/exception.h"
-#include "platform/base/input_stream.h"
-
-namespace location {
-namespace nearby {
-
-// A base {@link InputStream } for reading the contents of a byte array.
-class BaseInputStream : public InputStream {
- public:
- explicit BaseInputStream(ByteArray &buffer) : buffer_{buffer} {}
- BaseInputStream(const BaseInputStream &) = delete;
- BaseInputStream &operator=(const BaseInputStream &) = delete;
- ~BaseInputStream() override { Close(); }
-
- ExceptionOr<ByteArray> Read(std::int64_t size) override;
-
- ExceptionOr<size_t> Skip(size_t offset) override {
- size_t real_offset = std::min(offset, buffer_.size() - position_);
- position_ += real_offset;
- return ExceptionOr<size_t>(real_offset);
- }
-
- Exception Close() override {
- // Do nothing.
- return {Exception::kSuccess};
- }
-
- std::uint8_t ReadUint8();
- std::uint16_t ReadUint16();
- std::uint32_t ReadUint32();
- std::uint64_t ReadUint64();
- ByteArray ReadBytes(int size);
- bool IsAvailable(int size) const {
- return buffer_.size() - position_ >= size;
- }
-
- private:
- ByteArray &buffer_;
- int position_{0};
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_BASE_BASE_INPUT_STREAM_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/base_mutex_lock.h b/chromium/third_party/nearby/src/cpp/platform/base/base_mutex_lock.h
deleted file mode 100644
index c5a8f51ebd0..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/base_mutex_lock.h
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_BASE_BASE_MUTEX_LOCK_H_
-#define PLATFORM_BASE_BASE_MUTEX_LOCK_H_
-
-#include "absl/base/thread_annotations.h"
-#include "platform/api/mutex.h"
-
-namespace location {
-namespace nearby {
-
-// An RAII mechanism to acquire a Lock over a block of code.
-class ABSL_SCOPED_LOCKABLE BaseMutexLock final {
- public:
- explicit BaseMutexLock(api::Mutex* mutex) ABSL_EXCLUSIVE_LOCK_FUNCTION(mutex)
- : mutex_(mutex) {
- mutex_->Lock();
- }
- ~BaseMutexLock() ABSL_UNLOCK_FUNCTION() { mutex_->Unlock(); }
-
- private:
- api::Mutex* mutex_;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_BASE_BASE_MUTEX_LOCK_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/base_pipe.cc b/chromium/third_party/nearby/src/cpp/platform/base/base_pipe.cc
deleted file mode 100644
index 4c3e80f9b50..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/base_pipe.cc
+++ /dev/null
@@ -1,109 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/base/base_pipe.h"
-
-#include "platform/base/base_mutex_lock.h"
-#include "platform/base/input_stream.h"
-#include "platform/base/output_stream.h"
-
-namespace location {
-namespace nearby {
-
-ExceptionOr<ByteArray> BasePipe::Read(size_t size) {
- BaseMutexLock lock(mutex_.get());
-
- // We're done reading all the chunks that were written before the OutputStream
- // was closed, so there's nothing to do here other than return an empty chunk
- // to serve as an EOF indication to callers.
- if (read_all_chunks_) {
- return ExceptionOr<ByteArray>{ByteArray{}};
- }
-
- while (buffer_.empty() && !input_stream_closed_) {
- Exception wait_exception = cond_->Wait();
-
- if (wait_exception.Raised()) {
- return ExceptionOr<ByteArray>{wait_exception};
- }
- }
-
- if (input_stream_closed_) {
- return ExceptionOr<ByteArray>{Exception::kIo};
- }
-
- ByteArray first_chunk{buffer_.front()};
- buffer_.pop_front();
-
- // If we received our sentinel chunk, mark the fact that there cannot
- // possibly be any more chunks to read here on in, and return an empty chunk
- // to serve as an EOF indication to callers.
- if (first_chunk.Empty()) {
- read_all_chunks_ = true;
- return ExceptionOr<ByteArray>{ByteArray{}};
- }
-
- // If first_chunk is small enough to not overshoot the requested 'size', just
- // return that.
- if (first_chunk.size() <= size) {
- return ExceptionOr<ByteArray>{first_chunk};
- } else {
- // Break first_chunk into 2 parts -- the first one of which (next_chunk)
- // will be 'size' bytes long, and will be returned, and the second one of
- // which (overflow_chunk) will be re-inserted into buffer_, at the head of
- // the queue, to be served up in the next call to read().
- ByteArray next_chunk(first_chunk.data(), size);
- buffer_.push_front(
- ByteArray(first_chunk.data() + size, first_chunk.size() - size));
- return ExceptionOr<ByteArray>{next_chunk};
- }
-}
-
-Exception BasePipe::Write(const ByteArray& data) {
- BaseMutexLock lock(mutex_.get());
-
- return WriteLocked(data);
-}
-
-void BasePipe::MarkInputStreamClosed() {
- BaseMutexLock lock(mutex_.get());
-
- input_stream_closed_ = true;
- // Trigger cond_ to unblock a potentially-blocked call to read(), and to let
- // it know to return Exception::IO.
- cond_->Notify();
-}
-
-void BasePipe::MarkOutputStreamClosed() {
- BaseMutexLock lock(mutex_.get());
-
- // Write a sentinel null chunk before marking output_stream_closed as true.
- WriteLocked(ByteArray{});
- output_stream_closed_ = true;
-}
-
-Exception BasePipe::WriteLocked(const ByteArray& data) {
- if (input_stream_closed_ || output_stream_closed_) {
- return {Exception::kIo};
- }
-
- buffer_.push_back(data);
- // Trigger cond_ to unblock a potentially-blocked call to read(), now that
- // there's more data for it to consume.
- cond_->Notify();
- return {Exception::kSuccess};
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/base_pipe.h b/chromium/third_party/nearby/src/cpp/platform/base/base_pipe.h
deleted file mode 100644
index 88d0b756c51..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/base_pipe.h
+++ /dev/null
@@ -1,138 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_BASE_BASE_PIPE_H_
-#define PLATFORM_BASE_BASE_PIPE_H_
-
-#include <cstdint>
-#include <deque>
-#include <memory>
-
-#include "absl/base/thread_annotations.h"
-#include "platform/api/condition_variable.h"
-#include "platform/api/mutex.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/exception.h"
-#include "platform/base/input_stream.h"
-#include "platform/base/output_stream.h"
-
-namespace location {
-namespace nearby {
-
-// Common Pipe implenentation.
-// It does not depend on platform implementation, and this allows it to
-// be used in the platform implementation itself.
-// Concrete class must be derived from it, as follows:
-//
-// class DerivedPipe : public BasePipe {
-// public:
-// DerivedPipe() {
-// auto mutex = /* construct platform-dependent mutex */;
-// auto cond = /* construct platform-dependent condition variable */;
-// Setup(std::move(mutex), std::move(cond));
-// }
-// ~DerivedPipe() override = default;
-// DerivedPipe(DerivedPipe&&) = default;
-// DerivedPipe& operator=(DerivedPipe&&) = default;
-// };
-class BasePipe {
- public:
- static constexpr const size_t kChunkSize = 64 * 1024;
- virtual ~BasePipe() = default;
-
- // Pipe is not copyable or movable, because copy/move will invalidate
- // references to input and output streams.
- // If move is required, Pipe could be wrapped with std::unique_ptr<>.
- BasePipe(BasePipe&&) = delete;
- BasePipe& operator=(BasePipe&&) = delete;
-
- // Get...() methods return references to input and output steam facades.
- // It is safe to call Get...() methods multiple times.
- InputStream& GetInputStream() { return input_stream_; }
- OutputStream& GetOutputStream() { return output_stream_; }
-
- protected:
- BasePipe() = default;
-
- void Setup(std::unique_ptr<api::Mutex> mutex,
- std::unique_ptr<api::ConditionVariable> cond) {
- mutex_ = std::move(mutex);
- cond_ = std::move(cond);
- }
-
- private:
- class BasePipeInputStream : public InputStream {
- public:
- explicit BasePipeInputStream(BasePipe* pipe) : pipe_(pipe) {}
- ~BasePipeInputStream() override { DoClose(); }
-
- ExceptionOr<ByteArray> Read(std::int64_t size) override {
- return pipe_->Read(size);
- }
- Exception Close() override { return DoClose(); }
-
- private:
- Exception DoClose() {
- pipe_->MarkInputStreamClosed();
- return {Exception::kSuccess};
- }
- BasePipe* pipe_;
- };
- class BasePipeOutputStream : public OutputStream {
- public:
- explicit BasePipeOutputStream(BasePipe* pipe) : pipe_(pipe) {}
- ~BasePipeOutputStream() override { DoClose(); }
-
- Exception Write(const ByteArray& data) override {
- return pipe_->Write(data);
- }
- Exception Flush() override { return {Exception::kSuccess}; }
- Exception Close() override { return DoClose(); }
-
- private:
- Exception DoClose() {
- pipe_->MarkOutputStreamClosed();
- return {Exception::kSuccess};
- }
- BasePipe* pipe_;
- };
-
- ExceptionOr<ByteArray> Read(size_t size) ABSL_LOCKS_EXCLUDED(mutex_);
- Exception Write(const ByteArray& data) ABSL_LOCKS_EXCLUDED(mutex_);
-
- void MarkInputStreamClosed() ABSL_LOCKS_EXCLUDED(mutex_);
- void MarkOutputStreamClosed() ABSL_LOCKS_EXCLUDED(mutex_);
-
- Exception WriteLocked(const ByteArray& data)
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Order of declaration matters:
- // - mutex must be defined before condvar;
- // - input & output streams must be after both mutex and condvar.
- bool input_stream_closed_ ABSL_GUARDED_BY(mutex_) = false;
- bool output_stream_closed_ ABSL_GUARDED_BY(mutex_) = false;
- bool read_all_chunks_ ABSL_GUARDED_BY(mutex_) = false;
-
- std::deque<ByteArray> ABSL_GUARDED_BY(mutex_) buffer_;
- std::unique_ptr<api::Mutex> mutex_;
- std::unique_ptr<api::ConditionVariable> cond_;
-
- BasePipeInputStream input_stream_{this};
- BasePipeOutputStream output_stream_{this};
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_BASE_BASE_PIPE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/bluetooth_utils.cc b/chromium/third_party/nearby/src/cpp/platform/base/bluetooth_utils.cc
deleted file mode 100644
index b547c8dfa75..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/bluetooth_utils.cc
+++ /dev/null
@@ -1,75 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/base/bluetooth_utils.h"
-
-#include "absl/strings/escaping.h"
-#include "absl/strings/str_format.h"
-
-namespace location {
-namespace nearby {
-
-std::string BluetoothUtils::ToString(const ByteArray& bluetooth_mac_address) {
- std::string colon_delimited_string;
-
- if (bluetooth_mac_address.size() != kBluetoothMacAddressLength)
- return colon_delimited_string;
-
- if (IsBluetoothMacAddressUnset(bluetooth_mac_address))
- return colon_delimited_string;
-
- for (auto byte : std::string(bluetooth_mac_address)) {
- if (!colon_delimited_string.empty())
- absl::StrAppend(&colon_delimited_string, ":");
- absl::StrAppend(&colon_delimited_string, absl::StrFormat("%02X", byte));
- }
- return colon_delimited_string;
-}
-
-ByteArray BluetoothUtils::FromString(absl::string_view bluetooth_mac_address) {
- std::string bt_mac_address(bluetooth_mac_address);
-
- // Remove the colon delimiters.
- bt_mac_address.erase(
- std::remove(bt_mac_address.begin(), bt_mac_address.end(), ':'),
- bt_mac_address.end());
-
- // If the bluetooth mac address is invalid (wrong size), return a null byte
- // array.
- if (bt_mac_address.length() != kBluetoothMacAddressLength * 2) {
- return ByteArray();
- }
-
- // Convert to bytes. If MAC Address bytes are unset, return a null byte array.
- auto bt_mac_address_string(absl::HexStringToBytes(bt_mac_address));
- auto bt_mac_address_bytes =
- ByteArray(bt_mac_address_string.data(), bt_mac_address_string.size());
- if (IsBluetoothMacAddressUnset(bt_mac_address_bytes)) {
- return ByteArray();
- }
- return bt_mac_address_bytes;
-}
-
-bool BluetoothUtils::IsBluetoothMacAddressUnset(
- const ByteArray& bluetooth_mac_address_bytes) {
- for (int i = 0; i < bluetooth_mac_address_bytes.size(); i++) {
- if (bluetooth_mac_address_bytes.data()[i] != 0) {
- return false;
- }
- }
- return true;
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/bluetooth_utils.h b/chromium/third_party/nearby/src/cpp/platform/base/bluetooth_utils.h
deleted file mode 100644
index 11134509a94..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/bluetooth_utils.h
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_BASE_BLUETOOTH_UTILS_H_
-#define PLATFORM_BASE_BLUETOOTH_UTILS_H_
-
-#include "absl/strings/string_view.h"
-#include "platform/base/byte_array.h"
-
-namespace location {
-namespace nearby {
-
-class BluetoothUtils {
- public:
- static constexpr int kBluetoothMacAddressLength = 6;
-
- // Converts a Bluetooth MAC address from byte array to String format. Returns
- // empty if input byte array is not of correct format.
- // e.g. {-84, 55, 67, -68, -87, 40} -> "AC:37:43:BC:A9:28".
- static std::string ToString(const ByteArray& bluetooth_mac_address);
-
- // Converts a Bluetooth MAC address from String format to byte array. Returns
- // empty if input string is not of correct format.
- // e.g. "AC:37:43:BC:A9:28" -> {-84, 55, 67, -68, -87, 40}.
- static ByteArray FromString(absl::string_view bluetooth_mac_address);
-
- // Checks if a Bluetooth MAC address is zero for every byte.
- static bool IsBluetoothMacAddressUnset(
- const ByteArray& bluetooth_mac_address);
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_BASE_BLUETOOTH_UTILS_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/bluetooth_utils_test.cc b/chromium/third_party/nearby/src/cpp/platform/base/bluetooth_utils_test.cc
deleted file mode 100644
index bff14ae25f1..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/bluetooth_utils_test.cc
+++ /dev/null
@@ -1,89 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/base/bluetooth_utils.h"
-
-#include "gtest/gtest.h"
-
-namespace location {
-namespace nearby {
-
-constexpr absl::string_view kBluetoothMacAddress{"00:00:E6:88:64:13"};
-constexpr char kBluetoothMacAddressBytes[] = {0x00, 0x00, 0xe6,
- 0x88, 0x64, 0x13};
-
-TEST(BluetoothUtilsTest, ToStringWorks) {
- ByteArray bt_mac_address_bytes{kBluetoothMacAddressBytes,
- sizeof(kBluetoothMacAddressBytes)};
-
- auto bt_mac_address = BluetoothUtils::ToString(bt_mac_address_bytes);
-
- EXPECT_EQ(kBluetoothMacAddress, bt_mac_address);
-}
-
-TEST(BluetoothUtilsTest, FromStringWorks) {
- ByteArray bt_mac_address_bytes{kBluetoothMacAddressBytes,
- sizeof(kBluetoothMacAddressBytes)};
-
- auto bt_mac_address_bytes_result =
- BluetoothUtils::FromString(kBluetoothMacAddress);
-
- EXPECT_EQ(bt_mac_address_bytes, bt_mac_address_bytes_result);
-}
-
-TEST(BluetoothUtilsTest, InvalidBytesReturnsEmptyString) {
- std::string string_result;
-
- char bad_bt_mac_address_1[] = {0x02, 0x20, 0x00};
- ByteArray bad_bt_mac_address_bytes_1{bad_bt_mac_address_1,
- sizeof(bad_bt_mac_address_1)};
- string_result = BluetoothUtils::ToString(bad_bt_mac_address_bytes_1);
- EXPECT_TRUE(string_result.empty());
-
- char bad_bt_mac_address_2[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
- ByteArray bad_bt_mac_address_bytes_2{bad_bt_mac_address_2,
- sizeof(bad_bt_mac_address_2)};
- string_result = BluetoothUtils::ToString(bad_bt_mac_address_bytes_2);
- EXPECT_TRUE(string_result.empty());
-
- char bad_bt_mac_address_3[] = {0x11, 0x22, 0x33, 0x44, 0x55,
- 0x66, 0x77, 0x88, 0x99};
- ByteArray bad_bt_mac_address_bytes_3{bad_bt_mac_address_3,
- sizeof(bad_bt_mac_address_3)};
- string_result = BluetoothUtils::ToString(bad_bt_mac_address_bytes_3);
- EXPECT_TRUE(string_result.empty());
-}
-
-TEST(BluetoothUtilsTest, InvalidStringReturnsEmptyByteArray) {
- ByteArray bytes_result;
-
- std::string bad_bt_mac_address_1 = "022:00";
- bytes_result = BluetoothUtils::FromString(bad_bt_mac_address_1);
- EXPECT_TRUE(bytes_result.Empty());
-
- std::string bad_bt_mac_address_2 = "22:00:11:33:77:aa::bb::99";
- bytes_result = BluetoothUtils::FromString(bad_bt_mac_address_2);
- EXPECT_TRUE(bytes_result.Empty());
-
- std::string bad_bt_mac_address_3 = "00:00:00:00:00:00";
- bytes_result = BluetoothUtils::FromString(bad_bt_mac_address_3);
- EXPECT_TRUE(bytes_result.Empty());
-
- std::string bad_bt_mac_address_4 = "BLUETOOTHCHIP";
- bytes_result = BluetoothUtils::FromString(bad_bt_mac_address_4);
- EXPECT_TRUE(bytes_result.Empty());
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/byte_array_test.cc b/chromium/third_party/nearby/src/cpp/platform/base/byte_array_test.cc
deleted file mode 100644
index 7f13aa8bd7a..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/byte_array_test.cc
+++ /dev/null
@@ -1,90 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/base/byte_array.h"
-
-#include <cstring>
-
-#include "gtest/gtest.h"
-
-namespace {
-
-using location::nearby::ByteArray;
-
-TEST(ByteArrayTest, DefaultSizeIsZero) {
- ByteArray bytes;
- EXPECT_EQ(0, bytes.size());
-}
-
-TEST(ByteArrayTest, DefaultIsEmpty) {
- ByteArray bytes;
- EXPECT_TRUE(bytes.Empty());
-}
-
-TEST(ByteArrayTest, NullArrayIsEmpty) {
- ByteArray bytes{nullptr, 5};
- EXPECT_TRUE(bytes.Empty());
-}
-
-TEST(ByteArrayTest, CopyAtDoesNotExtendArray) {
- ByteArray v1("12345");
- ByteArray v2("ABCDEFGH");
- EXPECT_TRUE(v2.CopyAt(/*offset=*/5, v1));
- EXPECT_TRUE(v2.CopyAt(/*offset=*/1, v1, /*source_offset=*/3));
- EXPECT_EQ(v2, ByteArray("A45DE123"));
-}
-
-TEST(ByteArrayTest, CopyAtOutOfBoundsIsIgnored) {
- ByteArray v1("12345");
- ByteArray v2("ABCDEFGH");
- // Try to do an out-of-bounds read.
- EXPECT_FALSE(v2.CopyAt(/* offset=*/5, v1, /*source_offset=*/10));
- // Try to do an out-of-bounds write.
- EXPECT_FALSE(v2.CopyAt(/* offset=*/9, v1));
- EXPECT_EQ(v2, ByteArray("ABCDEFGH"));
-}
-
-TEST(ByteArrayTest, SetFromString) {
- std::string setup("setup_test");
- ByteArray bytes{setup}; // array initialized with a copy of string.
- EXPECT_EQ(setup.size(), bytes.size());
- EXPECT_EQ(std::string(bytes), setup);
-}
-
-TEST(ByteArrayTest, SetExplicitSize) {
- constexpr size_t kArraySize = 10;
- char reference[kArraySize]{};
- ByteArray bytes{kArraySize}; // array of size 10, zero-initialized.
- EXPECT_EQ(kArraySize, bytes.size());
- EXPECT_EQ(0, memcmp(bytes.data(), reference, kArraySize));
-}
-
-TEST(ByteArrayTest, SetExplicitData) {
- constexpr static const char message[]{"test_message"};
- constexpr size_t kMessageSize = sizeof(message);
- ByteArray bytes{message, kMessageSize};
- EXPECT_EQ(kMessageSize, bytes.size());
- EXPECT_NE(message, bytes.data());
- EXPECT_EQ(0, memcmp(message, bytes.data(), kMessageSize));
-}
-
-TEST(ByteArrayTest, CreateFromNonNullTerminatedStdArray) {
- constexpr static const std::array data{'a', '\x00', 'b'};
- ByteArray bytes{data};
- EXPECT_EQ(bytes.size(), 3);
- EXPECT_EQ(bytes.size(), std::string(bytes).size());
- EXPECT_EQ(std::string(bytes), std::string(data.data(), data.size()));
-}
-
-} // namespace
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/byte_utils.cc b/chromium/third_party/nearby/src/cpp/platform/base/byte_utils.cc
deleted file mode 100644
index 931d09b98d0..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/byte_utils.cc
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/base/byte_utils.h"
-
-#include <cstdlib>
-
-#include "absl/strings/str_format.h"
-#include "platform/base/base_input_stream.h"
-
-namespace location {
-namespace nearby {
-
-std::string ByteUtils::ToFourDigitString(ByteArray& bytes) {
- int multiplier = 1;
- int hashCode = 0;
-
- BaseInputStream base_input_stream{bytes};
- while (base_input_stream.IsAvailable(1)) {
- auto byte = static_cast<int>(base_input_stream.ReadUint8());
- hashCode = (hashCode + byte * multiplier) % kHashBasePrime;
- multiplier = multiplier * kHashBaseMultiplier % kHashBasePrime;
- }
- return absl::StrFormat("%04d", abs(hashCode));
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/byte_utils.h b/chromium/third_party/nearby/src/cpp/platform/base/byte_utils.h
deleted file mode 100644
index e603a5fda68..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/byte_utils.h
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_BASE_BYTE_UTILS_H_
-#define PLATFORM_BASE_BYTE_UTILS_H_
-
-#include "platform/base/byte_array.h"
-
-namespace location {
-namespace nearby {
-
-class ByteUtils {
- public:
- static std::string ToFourDigitString(ByteArray& bytes);
-
- private:
- // The biggest prime number under 10000, used as a mod base to trim integers
- // into 4 digits.
- static constexpr int kHashBasePrime = 9973;
- // The hash multiplier.
- static constexpr int kHashBaseMultiplier = 31;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_BASE_BYTE_UTILS_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/byte_utils_test.cc b/chromium/third_party/nearby/src/cpp/platform/base/byte_utils_test.cc
deleted file mode 100644
index 41deee1e252..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/byte_utils_test.cc
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/base/byte_utils.h"
-
-#include "gtest/gtest.h"
-#include "platform/base/byte_array.h"
-
-namespace location {
-namespace nearby {
-
-constexpr absl::string_view kFooBytes{"rawABCDE"};
-constexpr absl::string_view kFooFourDigitsToken{"0392"};
-constexpr absl::string_view kEmptyFourDigitsToken{"0000"};
-
-TEST(ByteUtilsTest, ToFourDigitStringCorrect) {
- ByteArray bytes{std::string(kFooBytes)};
-
- auto four_digit_string = ByteUtils::ToFourDigitString(bytes);
-
- EXPECT_EQ(std::string(kFooFourDigitsToken), four_digit_string);
-}
-
-TEST(ByteUtilsTest, TestEmptyByteArrayCorrect) {
- ByteArray bytes;
-
- auto four_digit_string = ByteUtils::ToFourDigitString(bytes);
-
- EXPECT_EQ(std::string(kEmptyFourDigitsToken), four_digit_string);
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/callable.h b/chromium/third_party/nearby/src/cpp/platform/base/callable.h
deleted file mode 100644
index 167be58a870..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/callable.h
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_BASE_CALLABLE_H_
-#define PLATFORM_BASE_CALLABLE_H_
-
-#include <functional>
-
-#include "platform/base/exception.h"
-
-namespace location {
-namespace nearby {
-
-// The Callable is and object intended to be executed by a thread, that is able
-// to return a value of specified type T.
-// It must be invokable without arguments. It must return a value implicitly
-// convertible to ExceptionOr<T>.
-//
-// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Callable.html
-template <typename T>
-using Callable = std::function<ExceptionOr<T>()>;
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_BASE_CALLABLE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/cancellation_flag.cc b/chromium/third_party/nearby/src/cpp/platform/base/cancellation_flag.cc
deleted file mode 100644
index 6443a4c08e1..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/cancellation_flag.cc
+++ /dev/null
@@ -1,80 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/base/cancellation_flag.h"
-
-#include "platform/base/feature_flags.h"
-
-namespace location {
-namespace nearby {
-
-CancellationFlag::CancellationFlag() {
- mutex_ = std::make_unique<absl::Mutex>();
-}
-
-CancellationFlag::CancellationFlag(bool cancelled) {
- mutex_ = std::make_unique<absl::Mutex>();
- cancelled_ = cancelled;
-}
-
-CancellationFlag::~CancellationFlag() { listeners_.clear(); }
-
-void CancellationFlag::Cancel() {
- // Return immediately as no-op if feature flag is not enabled.
- if (!FeatureFlags::GetInstance().GetFlags().enable_cancellation_flag) {
- return;
- }
-
- absl::flat_hash_set<CancelListener *> listeners;
- {
- absl::MutexLock lock(mutex_.get());
- if (cancelled_) {
- // Someone already cancelled. Return immediately.
- return;
- }
- cancelled_ = true;
-
- listeners = listeners_;
- }
-
- for (const auto *listener : listeners) {
- (*listener)();
- }
-}
-
-bool CancellationFlag::Cancelled() const {
- absl::MutexLock lock(mutex_.get());
-
- // Return false as no-op if feature flag is not enabled.
- if (!FeatureFlags::GetInstance().GetFlags().enable_cancellation_flag) {
- return false;
- }
-
- return cancelled_;
-}
-
-void CancellationFlag::RegisterOnCancelListener(CancelListener *listener) {
- absl::MutexLock lock(mutex_.get());
-
- listeners_.emplace(listener);
-}
-
-void CancellationFlag::UnregisterOnCancelListener(CancelListener *listener) {
- absl::MutexLock lock(mutex_.get());
-
- listeners_.erase(listener);
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/cancellation_flag_listener.h b/chromium/third_party/nearby/src/cpp/platform/base/cancellation_flag_listener.h
deleted file mode 100644
index 8a5d9d37794..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/cancellation_flag_listener.h
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_BASE_CANCELLATION_FLAG_LISTENER_H_
-#define PLATFORM_BASE_CANCELLATION_FLAG_LISTENER_H_
-
-#include "platform/base/cancellation_flag.h"
-
-namespace location {
-namespace nearby {
-
-// An RAII mechanism to register CancelListener over a life cycle of medium
-// class.
-class CancellationFlagListener {
- public:
- CancellationFlagListener(CancellationFlag* flag,
- std::function<void()> listener)
- : flag_(flag), listener_(std::move(listener)) {
- flag_->RegisterOnCancelListener(&listener_);
- }
-
- ~CancellationFlagListener() { flag_->UnregisterOnCancelListener(&listener_); }
-
- private:
- CancellationFlag* flag_;
- std::function<void()> listener_;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_BASE_CANCELLATION_FLAG_LISTENER_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/cancellation_flag_test.cc b/chromium/third_party/nearby/src/cpp/platform/base/cancellation_flag_test.cc
deleted file mode 100644
index a8a2dcbd8ac..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/cancellation_flag_test.cc
+++ /dev/null
@@ -1,212 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/base/cancellation_flag.h"
-
-#include <memory>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "platform/base/cancellation_flag_listener.h"
-#include "platform/base/feature_flags.h"
-#include "platform/base/medium_environment.h"
-
-namespace location {
-namespace nearby {
-
-class CancellationFlagPeer {
- public:
- explicit CancellationFlagPeer(CancellationFlag* cancellation_flag)
- : cancellation_flag_(cancellation_flag) {}
- void RegisterOnCancelListener(CancellationFlag::CancelListener* listener) {
- cancellation_flag_->RegisterOnCancelListener(listener);
- }
- void UnregisterOnCancelListener(CancellationFlag::CancelListener* listener) {
- cancellation_flag_->UnregisterOnCancelListener(listener);
- }
- int CancelListenersSize() const {
- return cancellation_flag_->CancelListenersSize();
- }
-
- private:
- CancellationFlag* cancellation_flag_; // Not owned by CancellationFlagPeer.
-};
-
-namespace {
-
-using FeatureFlags = FeatureFlags::Flags;
-using ::testing::MockFunction;
-using ::testing::StrictMock;
-
-constexpr FeatureFlags kTestCases[] = {
- FeatureFlags{
- .enable_cancellation_flag = true,
- },
- FeatureFlags{
- .enable_cancellation_flag = false,
- },
-};
-
-class CancellationFlagTest : public ::testing::TestWithParam<FeatureFlags> {
- protected:
- void SetUp() override {
- feature_flags_ = GetParam();
- env_.SetFeatureFlags(feature_flags_);
- }
-
- FeatureFlags feature_flags_;
- MediumEnvironment& env_{MediumEnvironment::Instance()};
-};
-
-TEST_P(CancellationFlagTest, InitialValueIsFalse) {
- CancellationFlag flag;
-
- // No matter FeatureFlag is enabled or not, Cancelled is always false.
- EXPECT_FALSE(flag.Cancelled());
-}
-
-TEST_P(CancellationFlagTest, InitialValueAsTrue) {
- CancellationFlag flag{true};
-
- // If FeatureFlag is disabled, Cancelled is false as no-op.
- if (!feature_flags_.enable_cancellation_flag) {
- EXPECT_FALSE(flag.Cancelled());
- return;
- }
-
- EXPECT_TRUE(flag.Cancelled());
-}
-
-TEST_P(CancellationFlagTest, CanCancel) {
- StrictMock<MockFunction<void()>> mock_cancel_callback;
- CancellationFlag::CancelListener cancel_callback =
- mock_cancel_callback.AsStdFunction();
- EXPECT_CALL(mock_cancel_callback, Call)
- .Times(feature_flags_.enable_cancellation_flag ? 1 : 0);
- CancellationFlag flag;
- CancellationFlagListener cancellation_flag_listener(&flag, cancel_callback);
- flag.Cancel();
-
- // If FeatureFlag is disabled, return as no-op immediately and
- // Cancelled is always false.
- if (!feature_flags_.enable_cancellation_flag) {
- EXPECT_FALSE(flag.Cancelled());
- return;
- }
-
- EXPECT_TRUE(flag.Cancelled());
-}
-
-TEST_P(CancellationFlagTest, ShouldOnlyCancelOnce) {
- StrictMock<MockFunction<void()>> mock_cancel_callback;
- CancellationFlag::CancelListener cancel_callback =
- mock_cancel_callback.AsStdFunction();
- EXPECT_CALL(mock_cancel_callback, Call)
- .Times(feature_flags_.enable_cancellation_flag ? 1 : 0);
-
- CancellationFlag flag;
- CancellationFlagListener cancellation_flag_listener(&flag, cancel_callback);
- flag.Cancel();
- flag.Cancel();
- flag.Cancel();
-
- // If FeatureFlag is disabled, return as no-op immediately and
- // Cancelled is always false.
- if (!feature_flags_.enable_cancellation_flag) {
- EXPECT_FALSE(flag.Cancelled());
- return;
- }
-
- EXPECT_TRUE(flag.Cancelled());
-}
-
-TEST_P(CancellationFlagTest, CannotCancelAfterUnregister) {
- StrictMock<MockFunction<void()>> mock_cancel_callback;
- CancellationFlag::CancelListener cancel_callback =
- mock_cancel_callback.AsStdFunction();
- EXPECT_CALL(mock_cancel_callback, Call).Times(0);
-
- CancellationFlag flag;
- auto cancellation_flag_listener =
- std::make_unique<CancellationFlagListener>(&flag, cancel_callback);
- // Release immediately.
- cancellation_flag_listener.reset();
- flag.Cancel();
-}
-
-INSTANTIATE_TEST_SUITE_P(ParametrisedCancellationFlagTest, CancellationFlagTest,
- ::testing::ValuesIn(kTestCases));
-
-} // namespace
-
-TEST(CancellationFlagTest,
- CancelMultiplesIfMultiplePointersToTheSameFunctionRegistered) {
- location::nearby::FeatureFlags::Flags feature_flags_ =
- location::nearby::FeatureFlags::Flags{
- .enable_cancellation_flag = true,
- };
- MediumEnvironment::Instance().SetFeatureFlags(feature_flags_);
-
- StrictMock<MockFunction<void()>> mock_cancel_callback;
- CancellationFlag::CancelListener cancel_callback =
- mock_cancel_callback.AsStdFunction();
-
- CancellationFlag::CancelListener* callback_pointer_1 = &cancel_callback;
- auto callback_pointer_2 =
- std::make_unique<CancellationFlag::CancelListener>();
- *callback_pointer_2 = cancel_callback;
-
- EXPECT_NE(callback_pointer_1, callback_pointer_2.get());
- EXPECT_CALL(mock_cancel_callback, Call).Times(2);
-
- CancellationFlag flag;
- CancellationFlagPeer flag_peer(&flag);
- flag_peer.RegisterOnCancelListener(callback_pointer_1);
- flag_peer.RegisterOnCancelListener(callback_pointer_2.get());
-
- flag.Cancel();
-
- flag_peer.UnregisterOnCancelListener(callback_pointer_2.get());
- EXPECT_EQ(1, flag_peer.CancelListenersSize());
- flag_peer.UnregisterOnCancelListener(callback_pointer_1);
- EXPECT_EQ(0, flag_peer.CancelListenersSize());
-}
-
-TEST(CancellationFlagTest, RegisteredMultuipleTimesOnlyCancelOnce) {
- location::nearby::FeatureFlags::Flags feature_flags_ =
- location::nearby::FeatureFlags::Flags{
- .enable_cancellation_flag = true,
- };
- MediumEnvironment::Instance().SetFeatureFlags(feature_flags_);
-
- StrictMock<MockFunction<void()>> mock_cancel_callback;
- CancellationFlag::CancelListener cancel_callback =
- mock_cancel_callback.AsStdFunction();
- EXPECT_CALL(mock_cancel_callback, Call).Times(1);
-
- CancellationFlag flag;
- CancellationFlagPeer flag_peer(&flag);
- flag_peer.RegisterOnCancelListener(&cancel_callback);
- flag_peer.RegisterOnCancelListener(&cancel_callback);
- EXPECT_EQ(1, flag_peer.CancelListenersSize());
-
- flag.Cancel();
-
- flag_peer.UnregisterOnCancelListener(&cancel_callback);
- EXPECT_EQ(0, flag_peer.CancelListenersSize());
- flag_peer.UnregisterOnCancelListener(&cancel_callback);
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/error_code_params.h b/chromium/third_party/nearby/src/cpp/platform/base/error_code_params.h
deleted file mode 100644
index 73709a77c7e..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/error_code_params.h
+++ /dev/null
@@ -1,64 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_BASE_ERROR_CORE_PARAMS_H_
-#define PLATFORM_BASE_ERROR_CORE_PARAMS_H_
-
-#include "proto/connections_enums.pb.h"
-#include "proto/errorcode/error_code_enums.pb.h"
-
-namespace location {
-namespace nearby {
-
-// A struct to consturct error code parameters for the analytics recorder.
-struct ErrorCodeParams {
- location::nearby::proto::connections::Medium medium =
- location::nearby::proto::connections::UNKNOWN_MEDIUM;
- location::nearby::errorcode::proto::Event event =
- location::nearby::errorcode::proto::UNKNOWN_EVENT;
- location::nearby::errorcode::proto::Description description =
- location::nearby::errorcode::proto::UNKNOWN;
- std::string pii_message = {};
- bool is_common_error = false;
- location::nearby::errorcode::proto::CommonError common_error =
- location::nearby::errorcode::proto::UNKNOWN_ERROR;
- location::nearby::errorcode::proto::ConnectError connect_error =
- location::nearby::errorcode::proto::UNKNOWN_CONNECT_ERROR;
- location::nearby::errorcode::proto::DisconnectError disconnect_error =
- location::nearby::errorcode::proto::UNKNOWN_DISCONNECT_ERROR;
- location::nearby::errorcode::proto::StartAdvertisingError
- start_advertising_error =
- location::nearby::errorcode::proto::UNKNOWN_START_ADVERTISING_ERROR;
- location::nearby::errorcode::proto::StopAdvertisingError
- stop_advertising_error =
- location::nearby::errorcode::proto::UNKNOWN_STOP_ADVERTISING_ERROR;
- location::nearby::errorcode::proto::StartDiscoveringError
- start_discovering_error =
- location::nearby::errorcode::proto::UNKNOWN_START_DISCOVERING_ERROR;
- location::nearby::errorcode::proto::StopDiscoveringError
- stop_discovering_error =
- location::nearby::errorcode::proto::UNKNOWN_STOP_DISCOVERING_ERROR;
- location::nearby::errorcode::proto::StartListeningIncomingConnectionError
- start_listening_incoming_connection_error = location::nearby::errorcode::
- proto::UNKNOWN_START_LISTENING_INCOMING_CONNECTION_ERROR;
- location::nearby::errorcode::proto::StopListeningIncomingConnectionError
- stop_listening_incoming_connection_error = location::nearby::errorcode::
- proto::UNKNOWN_STOP_LISTENING_INCOMING_CONNECTION_ERROR;
- std::string connection_token = {};
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_BASE_ERROR_CORE_PARAMS_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/error_code_recorder.cc b/chromium/third_party/nearby/src/cpp/platform/base/error_code_recorder.cc
deleted file mode 100644
index b85017f5e78..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/error_code_recorder.cc
+++ /dev/null
@@ -1,116 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/base/error_code_recorder.h"
-
-#include "platform/base/logging.h"
-#include "proto/errorcode/error_code_enums.pb.h"
-
-namespace location {
-namespace nearby {
-
-using ::location::nearby::errorcode::proto::CommonError;
-using ::location::nearby::errorcode::proto::CONNECT;
-using ::location::nearby::errorcode::proto::ConnectError;
-using ::location::nearby::errorcode::proto::Description;
-using ::location::nearby::errorcode::proto::DISCONNECT;
-using ::location::nearby::errorcode::proto::DisconnectError;
-using ::location::nearby::errorcode::proto::Event;
-using ::location::nearby::errorcode::proto::START_ADVERTISING;
-using ::location::nearby::errorcode::proto::START_DISCOVERING;
-using ::location::nearby::errorcode::proto::START_LISTENING_INCOMING_CONNECTION;
-using ::location::nearby::errorcode::proto::StartAdvertisingError;
-using ::location::nearby::errorcode::proto::StartDiscoveringError;
-using ::location::nearby::errorcode::proto::
- StartListeningIncomingConnectionError;
-using ::location::nearby::errorcode::proto::STOP_ADVERTISING;
-using ::location::nearby::errorcode::proto::STOP_DISCOVERING;
-using ::location::nearby::errorcode::proto::STOP_LISTENING_INCOMING_CONNECTION;
-using ::location::nearby::errorcode::proto::StopAdvertisingError;
-using ::location::nearby::errorcode::proto::StopDiscoveringError;
-using ::location::nearby::errorcode::proto::
- StopListeningIncomingConnectionError;
-using ::location::nearby::proto::connections::Medium;
-
-// Default static no-op listener
-ErrorCodeRecorder::ErrorCodeListener ErrorCodeRecorder::listener_ =
- [](const ErrorCodeParams&) {};
-
-void ErrorCodeRecorder::LogErrorCode(Medium medium, Event event, int error,
- Description description,
- const std::string& pii_message,
- const std::string& connection_token) {
- NEARBY_LOGS(INFO) << "ErrorCodeRecorder LogErrorCode";
- ErrorCodeParams params = BuildErrorCodeParams(
- medium, event, error, description, pii_message, connection_token);
- listener_(params);
-}
-
-ErrorCodeParams ErrorCodeRecorder::BuildErrorCodeParams(
- Medium medium, Event event, int error, Description description,
- const std::string& pii_message, const std::string& connection_token) {
- ErrorCodeParams params = {.medium = medium,
- .event = event,
- .description = description,
- .pii_message = pii_message,
- .connection_token = connection_token};
-
- if (errorcode::proto::CommonError_IsValid(error)) {
- params.common_error = static_cast<CommonError>(error);
- params.is_common_error = true;
- } else {
- params.is_common_error = false;
- switch (event) {
- case START_ADVERTISING:
- params.start_advertising_error =
- static_cast<StartAdvertisingError>(error);
- break;
- case STOP_ADVERTISING:
- params.stop_advertising_error =
- static_cast<StopAdvertisingError>(error);
- break;
- case START_LISTENING_INCOMING_CONNECTION:
- params.start_listening_incoming_connection_error =
- static_cast<StartListeningIncomingConnectionError>(error);
- break;
- case STOP_LISTENING_INCOMING_CONNECTION:
- params.stop_listening_incoming_connection_error =
- static_cast<StopListeningIncomingConnectionError>(error);
- break;
- case START_DISCOVERING:
- params.start_discovering_error =
- static_cast<StartDiscoveringError>(error);
- break;
- case STOP_DISCOVERING:
- params.stop_discovering_error =
- static_cast<StopDiscoveringError>(error);
- break;
- case CONNECT:
- params.connect_error = static_cast<ConnectError>(error);
- break;
- case DISCONNECT:
- params.disconnect_error = static_cast<DisconnectError>(error);
- break;
- // Set the error as unknown if undefined event passed in.
- default:
- params.common_error = errorcode::proto::UNKNOWN_ERROR;
- params.is_common_error = true;
- break;
- }
- }
- return params;
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/error_code_recorder.h b/chromium/third_party/nearby/src/cpp/platform/base/error_code_recorder.h
deleted file mode 100644
index bd1c4b845f3..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/error_code_recorder.h
+++ /dev/null
@@ -1,86 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_BASE_ERROR_CODE_RECORDER_H_
-#define PLATFORM_BASE_ERROR_CODE_RECORDER_H_
-
-#include <functional>
-
-#include "platform/base/error_code_params.h"
-
-namespace location {
-namespace nearby {
-
-// Deploys the error code of the platform medium to the analytics recorder.
-//
-// The usage is to call static method ErrorCode::LogErrorCode(...) in each
-// medium platform supported whenever error occurred.
-class ErrorCodeRecorder {
- public:
- using ErrorCodeListener = std::function<void(const ErrorCodeParams&)>;
-
- explicit ErrorCodeRecorder(ErrorCodeListener listener) {
- listener_ = std::move(listener);
- }
- ErrorCodeRecorder(const ErrorCodeRecorder&) = delete;
- ErrorCodeRecorder& operator=(const ErrorCodeRecorder&) = delete;
-
- // Logs error code when medium error occurred.
- //
- // Caller should pass the exact matched event and error enum value except
- // the common error.
- // e.g.
- // - START_ADVERTISING_FAILED(43) in StartAdvertisingError =>
- // START_ADVERTISING event.
- // - DISCONNECT_NETWORK_FAILED(31) in Disconnect_error => DISCONNECT event.
- // - INVALID_PARAMETER(1) for Common_error, and the event will be kept as it
- // is passed in.
- //
- // medium - An enum defined in proto::connections::Medium.
- // event - An enum defined in errorcode::proto::Event.
- // error - An enum integer value in the range from 0..30 defined
- // in errorcode::proto::CommonError and the range from 31..
- // nn defined among
- // errorcode::proto::StartAdvertisingError to
- // errorcode::proto::DisconnectError.
- // description - A description defiend in errorcode::proto::description.
- // pii_message - A pii info defiend in errorcode::proto::pii_message. An
- // empty string won't be recorded.
- // connection_token - connection token string.
- static void LogErrorCode(
- location::nearby::proto::connections::Medium medium,
- location::nearby::errorcode::proto::Event event, int error,
- location::nearby::errorcode::proto::Description description,
- const std::string& pii_message, const std::string& connection_token);
-
- // An auxiliary funciton for LogError() to assemble the ErrorCodeParams
- // struct.
- //
- // See `LogErrorCode` for reference on the parameters.
- static ErrorCodeParams BuildErrorCodeParams(
- location::nearby::proto::connections::Medium medium,
- location::nearby::errorcode::proto::Event event, int error,
- location::nearby::errorcode::proto::Description description,
- const std::string& pii_message, const std::string& connection_token);
-
- private:
- // A listener to call back to AnlayticsRecorder.OnErrorCode() by building
- // error_code_params.
- static ErrorCodeListener listener_;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_BASE_ERROR_CODE_RECORDER_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/error_code_recorder_test.cc b/chromium/third_party/nearby/src/cpp/platform/base/error_code_recorder_test.cc
deleted file mode 100644
index f0f84b93afc..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/error_code_recorder_test.cc
+++ /dev/null
@@ -1,136 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/base/error_code_recorder.h"
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-
-namespace location {
-namespace nearby {
-
-using ::testing::Field;
-using ::testing::MockFunction;
-using ::testing::StrictMock;
-
-TEST(ErrorCodeRecorderTest, TestListenerWork) {
- StrictMock<MockFunction<void(const ErrorCodeParams& params)>> mock_listener;
- ErrorCodeRecorder::ErrorCodeListener listener = mock_listener.AsStdFunction();
- EXPECT_CALL(mock_listener, Call).Times(1);
- ErrorCodeRecorder error_code_recorder(listener);
-
- ErrorCodeRecorder::LogErrorCode(
- proto::connections::BLE, errorcode::proto::START_ADVERTISING,
- errorcode::proto::MULTIPLE_FAST_ADVERTISEMENT_NOT_ALLOWED,
- errorcode::proto::FEATURE_BLUETOOTH_NOT_SUPPORTED, "pii_message",
- "connection_token");
-}
-
-TEST(ErrorCodeRecorderTest, TestBuildErrorCodeParamsWork) {
- std::string pii_message = "pii_message";
- std::string connection_token = "connection_token";
-
- ErrorCodeParams error_code_params;
- ErrorCodeRecorder error_recorder(
- [&error_code_params](const ErrorCodeParams& params) {
- error_code_params = std::move(params);
- });
-
- ErrorCodeRecorder::LogErrorCode(
- proto::connections::BLE, errorcode::proto::START_ADVERTISING,
- errorcode::proto::MULTIPLE_FAST_ADVERTISEMENT_NOT_ALLOWED,
- errorcode::proto::FEATURE_BLUETOOTH_NOT_SUPPORTED, pii_message,
- connection_token);
-
- EXPECT_THAT(
- error_code_params,
- AllOf(Field("medium", &ErrorCodeParams::medium, proto::connections::BLE),
- Field("event", &ErrorCodeParams::event,
- errorcode::proto::START_ADVERTISING),
- Field("description", &ErrorCodeParams::description,
- errorcode::proto::FEATURE_BLUETOOTH_NOT_SUPPORTED),
- Field("pii_message", &ErrorCodeParams::pii_message, pii_message),
- Field("is_common_error", &ErrorCodeParams::is_common_error, false),
- Field("start_advertising_error",
- &ErrorCodeParams::start_advertising_error,
- errorcode::proto::MULTIPLE_FAST_ADVERTISEMENT_NOT_ALLOWED),
- Field("connection_token", &ErrorCodeParams::connection_token,
- connection_token)));
-}
-
-TEST(ErrorCodeRecorderTest, TestBuildErrorCodeParamsWorkForCommonError) {
- std::string pii_message = "pii_message";
- std::string connection_token = "connection_token";
-
- ErrorCodeParams error_code_params;
- ErrorCodeRecorder error_recorder(
- [&error_code_params](const ErrorCodeParams& params) {
- error_code_params = std::move(params);
- });
-
- ErrorCodeRecorder::LogErrorCode(
- proto::connections::BLE, errorcode::proto::START_ADVERTISING,
- errorcode::proto::INVALID_PARAMETER, errorcode::proto::NULL_SERVICE_ID,
- pii_message, connection_token);
-
- EXPECT_THAT(
- error_code_params,
- AllOf(Field("medium", &ErrorCodeParams::medium, proto::connections::BLE),
- Field("event", &ErrorCodeParams::event,
- errorcode::proto::START_ADVERTISING),
- Field("description", &ErrorCodeParams::description,
- errorcode::proto::NULL_SERVICE_ID),
- Field("pii_message", &ErrorCodeParams::pii_message, pii_message),
- Field("is_common_error", &ErrorCodeParams::is_common_error, true),
- Field("common_error", &ErrorCodeParams::common_error,
- errorcode::proto::INVALID_PARAMETER),
- Field("connection_token", &ErrorCodeParams::connection_token,
- connection_token)));
-}
-
-TEST(ErrorCodeRecorderTest, TestBuildErrorCodeParamsWorkForUnknownEvent) {
- std::string pii_message = "pii_message";
- std::string connection_token = "connection_token";
-
- ErrorCodeParams error_code_params;
- ErrorCodeRecorder error_recorder(
- [&error_code_params](const ErrorCodeParams& params) {
- error_code_params = std::move(params);
- });
-
- // If event is UNKNOWN_EVENT and the error is not Common_Error then the error
- // will be set to UNKNOWN_ERROR.
- ErrorCodeRecorder::LogErrorCode(
- proto::connections::BLE, errorcode::proto::UNKNOWN_EVENT,
- errorcode::proto::MULTIPLE_FAST_ADVERTISEMENT_NOT_ALLOWED,
- errorcode::proto::FEATURE_BLUETOOTH_NOT_SUPPORTED, pii_message,
- connection_token);
-
- EXPECT_THAT(
- error_code_params,
- AllOf(Field("medium", &ErrorCodeParams::medium, proto::connections::BLE),
- Field("event", &ErrorCodeParams::event,
- errorcode::proto::UNKNOWN_EVENT),
- Field("description", &ErrorCodeParams::description,
- errorcode::proto::FEATURE_BLUETOOTH_NOT_SUPPORTED),
- Field("pii_message", &ErrorCodeParams::pii_message, pii_message),
- Field("is_common_error", &ErrorCodeParams::is_common_error, true),
- Field("common_error", &ErrorCodeParams::common_error,
- errorcode::proto::UNKNOWN_ERROR),
- Field("connection_token", &ErrorCodeParams::connection_token,
- connection_token)));
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/exception_test.cc b/chromium/third_party/nearby/src/cpp/platform/base/exception_test.cc
deleted file mode 100644
index 7916f06d5fa..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/exception_test.cc
+++ /dev/null
@@ -1,120 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/base/exception.h"
-
-#include <vector>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "platform/base/exception_test.nc.h"
-
-namespace location::nearby {
-
-TEST(ExceptionOr, Result_Copy_NonConst) {
- ExceptionOr<std::vector<int>> exception_or_vector({1, 2, 3});
- EXPECT_FALSE(exception_or_vector.result().empty());
-
- // Expect a copy when not explicitly moving the result.
- std::vector<int> copy = exception_or_vector.result();
- EXPECT_FALSE(copy.empty());
- EXPECT_FALSE(exception_or_vector.result().empty());
-
- // Modifying |exception_or_vector| should not affect the copy.
- exception_or_vector.result().clear();
- EXPECT_FALSE(copy.empty());
-}
-
-TEST(ExceptionOr, Result_Copy_Const) {
- const ExceptionOr<std::vector<int>> exception_or_vector({1, 2, 3});
- EXPECT_FALSE(exception_or_vector.result().empty());
-
- // Expect a copy when not explicitly moving the result.
- const std::vector<int>& copy = exception_or_vector.result();
- EXPECT_FALSE(copy.empty());
- EXPECT_FALSE(exception_or_vector.result().empty());
-}
-
-TEST(ExceptionOr, Result_Reference_NonConst) {
- ExceptionOr<std::vector<int>> exception_or_vector({1, 2, 3});
- EXPECT_FALSE(exception_or_vector.result().empty());
-
- // Getting a reference should not modify the source.
- std::vector<int>& reference = exception_or_vector.result();
- EXPECT_FALSE(reference.empty());
- EXPECT_FALSE(exception_or_vector.result().empty());
-
- // Modifying |exception_or_vector| should reflect in the reference.
- exception_or_vector.result().clear();
- EXPECT_TRUE(reference.empty());
-}
-
-TEST(ExceptionOr, Result_Reference_Const) {
- const ExceptionOr<std::vector<int>> exception_or_vector({1, 2, 3});
- EXPECT_FALSE(exception_or_vector.result().empty());
-
- // Getting a reference should not modify the source.
- const std::vector<int>& reference = exception_or_vector.result();
- EXPECT_FALSE(reference.empty());
- EXPECT_FALSE(exception_or_vector.result().empty());
-}
-
-TEST(ExceptionOr, Result_Move_NonConst) {
- ExceptionOr<std::vector<int>> exception_or_vector({1, 2, 3});
- EXPECT_FALSE(exception_or_vector.result().empty());
-
- // Moving the result should clear the source.
- std::vector<int> moved = std::move(exception_or_vector).result();
- EXPECT_FALSE(moved.empty());
-}
-
-TEST(ExceptionOr, Result_Move_Const) {
- const ExceptionOr<std::vector<int>> exception_or_vector({1, 2, 3});
- EXPECT_FALSE(exception_or_vector.result().empty());
-
- // Moving const rvalue reference will result in a copy.
- std::vector<int> moved = std::move(exception_or_vector).result();
- EXPECT_FALSE(moved.empty());
-}
-
-TEST(ExceptionOr, ExplicitConversionWorks) {
- class A {
- public:
- A() = default;
- };
- class B {
- public:
- B() = default;
- explicit B(A) {}
- };
- ExceptionOr<A> a(A{});
- ExceptionOr<B> b(a);
- EXPECT_TRUE(a.ok());
- EXPECT_TRUE(b.ok());
-}
-
-TEST(ExceptionOr, ExplicitConversionFailsToCompile) {
- class A {
- public:
- A() = default;
- };
- class B {
- public:
- B() = default;
- };
- ExceptionOr<A> a(A{});
- EXPECT_NON_COMPILE("no matching constructor", { ExceptionOr<B> b(a); });
-}
-
-} // namespace location::nearby
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/feature_flags_test.cc b/chromium/third_party/nearby/src/cpp/platform/base/feature_flags_test.cc
deleted file mode 100644
index 42456e282fa..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/feature_flags_test.cc
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/base/feature_flags.h"
-
-#include "gtest/gtest.h"
-#include "platform/base/medium_environment.h"
-
-namespace location {
-namespace nearby {
-namespace {
-
-constexpr FeatureFlags::Flags kTestFeatureFlags{
- .enable_cancellation_flag = true,
- .keep_alive_interval_millis = 5000,
- .keep_alive_timeout_millis = 30000};
-
-TEST(FeatureFlagsTest, ToSetFeatureWorks) {
- const FeatureFlags& features = FeatureFlags::GetInstance();
- EXPECT_FALSE(features.GetFlags().enable_cancellation_flag);
-
- EXPECT_EQ(5000, features.GetFlags().keep_alive_interval_millis);
- EXPECT_EQ(30000, features.GetFlags().keep_alive_timeout_millis);
-
- MediumEnvironment& medium_environment = MediumEnvironment::Instance();
- medium_environment.SetFeatureFlags(kTestFeatureFlags);
- EXPECT_TRUE(features.GetFlags().enable_cancellation_flag);
-
- const FeatureFlags& another_features_ref = FeatureFlags::GetInstance();
- EXPECT_TRUE(another_features_ref.GetFlags().enable_cancellation_flag);
-}
-
-} // namespace
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/input_stream.cc b/chromium/third_party/nearby/src/cpp/platform/base/input_stream.cc
deleted file mode 100644
index c3d75693171..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/input_stream.cc
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/base/input_stream.h"
-
-#include <algorithm>
-#include <cstddef>
-#include <cstdint>
-
-#include "platform/base/byte_array.h"
-#include "platform/base/exception.h"
-
-namespace location {
-namespace nearby {
-namespace {
-constexpr size_t kSkipBufferSize = 64 * 1024;
-} // namespace
-
-ExceptionOr<size_t> InputStream::Skip(size_t offset) {
- size_t bytes_left = offset;
- while (bytes_left > 0) {
- size_t chunk_size = std::min(bytes_left, kSkipBufferSize);
- ExceptionOr<ByteArray> result = Read(chunk_size);
- if (!result.ok()) {
- return result.GetException();
- }
- bytes_left -= chunk_size;
- }
- return ExceptionOr<size_t>(offset);
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/input_stream.h b/chromium/third_party/nearby/src/cpp/platform/base/input_stream.h
deleted file mode 100644
index 94b8550bbb1..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/input_stream.h
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_BASE_INPUT_STREAM_H_
-#define PLATFORM_BASE_INPUT_STREAM_H_
-
-#include <cstdint>
-
-#include "platform/base/byte_array.h"
-#include "platform/base/exception.h"
-
-namespace location {
-namespace nearby {
-
-// An InputStream represents an input stream of bytes.
-//
-// https://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html
-class InputStream {
- public:
- virtual ~InputStream() = default;
-
- // throws Exception::kIo
- virtual ExceptionOr<ByteArray> Read(std::int64_t size) = 0;
-
- // throws Exception::kIo
- virtual ExceptionOr<size_t> Skip(size_t offset);
-
- // throws Exception::kIo
- virtual Exception Close() = 0;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_BASE_INPUT_STREAM_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/logging.h b/chromium/third_party/nearby/src/cpp/platform/base/logging.h
deleted file mode 100644
index 70d988b91ae..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/logging.h
+++ /dev/null
@@ -1,84 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_BASE_LOGGING_H_
-#define PLATFORM_BASE_LOGGING_H_
-
-// base/logging.h is only included to allow logging clients to include CHECK's.
-// In Chrome this will be translated to base/check.h. See crbug/1212611.
-#include "base/check.h"
-#include "platform/api/log_message.h"
-#include "platform/api/platform.h"
-
-namespace location {
-namespace nearby {
-
-// This class is used to explicitly ignore values in the conditional
-// logging macros. This avoids compiler warnings like "value computed
-// is not used" and "statement has no effect".
-class LogMessageVoidify {
- public:
- LogMessageVoidify() = default;
- // This has to be an operator with a precedence lower than << but
- // higher than ?:
- void operator&(std::ostream&) {}
-};
-
-} // namespace nearby
-} // namespace location
-
-// Severity enum conversion
-#define NEARBY_SEVERITY_VERBOSE \
- location::nearby::api::LogMessage::Severity::kVerbose
-#define NEARBY_SEVERITY_INFO location::nearby::api::LogMessage::Severity::kInfo
-#define NEARBY_SEVERITY_WARNING \
- location::nearby::api::LogMessage::Severity::kWarning
-#define NEARBY_SEVERITY_ERROR \
- location::nearby::api::LogMessage::Severity::kError
-#define NEARBY_SEVERITY_FATAL \
- location::nearby::api::LogMessage::Severity::kFatal
-#if defined(_WIN32)
-// wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets substituted
-// with 0, and it expands to NEARBY_SEVERITY_0. To allow us to keep using this
-// syntax, we define this macro to do the same thing as NEARBY_SEVERITY_ERROR.
-#define NEARBY_SEVERITY_0 location::nearby::api::LogMessage::Severity::kError
-#endif // defined(_WIN32)
-#define NEARBY_SEVERITY(severity) NEARBY_SEVERITY_##severity
-
-// Log enabling
-#define NEARBY_LOG_IS_ON(severity) \
- location::nearby::api::LogMessage::ShouldCreateLogMessage( \
- NEARBY_SEVERITY(severity))
-
-#define NEARBY_LOG_SET_SEVERITY(severity) \
- location::nearby::api::LogMessage::SetMinLogSeverity( \
- NEARBY_SEVERITY(severity))
-
-// Log message creation
-#define NEARBY_LOG_MESSAGE(severity) \
- location::nearby::api::ImplementationPlatform::CreateLogMessage( \
- __FILE__, __LINE__, NEARBY_SEVERITY(severity))
-
-// Public APIs
-// The stream statement must come last or otherwise it won't compile.
-#define NEARBY_LOGS(severity) \
- !(NEARBY_LOG_IS_ON(severity)) ? (void)0 \
- : location::nearby::LogMessageVoidify() & \
- NEARBY_LOG_MESSAGE(severity)->Stream()
-
-#define NEARBY_LOG(severity, ...) \
- NEARBY_LOG_IS_ON(severity) \
- ? NEARBY_LOG_MESSAGE(severity)->Print(__VA_ARGS__) : (void)0
-
-#endif // PLATFORM_BASE_LOGGING_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/medium_environment.cc b/chromium/third_party/nearby/src/cpp/platform/base/medium_environment.cc
deleted file mode 100644
index b0f527ad705..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/medium_environment.cc
+++ /dev/null
@@ -1,676 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/base/medium_environment.h"
-
-#include <atomic>
-#include <cinttypes>
-#include <functional>
-#include <new>
-#include <string>
-#include <type_traits>
-#include <utility>
-
-#include "platform/base/feature_flags.h"
-#include "platform/base/logging.h"
-#include "platform/base/prng.h"
-#include "platform/public/count_down_latch.h"
-
-namespace location {
-namespace nearby {
-
-MediumEnvironment& MediumEnvironment::Instance() {
- static std::aligned_storage_t<sizeof(MediumEnvironment),
- alignof(MediumEnvironment)>
- storage;
- static MediumEnvironment* env = new (&storage) MediumEnvironment();
- return *env;
-}
-
-void MediumEnvironment::Start(EnvironmentConfig config) {
- if (!enabled_.exchange(true)) {
- NEARBY_LOGS(INFO) << "MediumEnvironment::Start()";
- config_ = std::move(config);
- Reset();
- }
-}
-
-void MediumEnvironment::Stop() {
- if (enabled_.exchange(false)) {
- NEARBY_LOGS(INFO) << "MediumEnvironment::Stop()";
- Sync(false);
- }
-}
-
-void MediumEnvironment::Reset() {
- RunOnMediumEnvironmentThread([this]() {
- NEARBY_LOGS(INFO) << "MediumEnvironment::Reset()";
- bluetooth_adapters_.clear();
- bluetooth_mediums_.clear();
- ble_mediums_.clear();
- webrtc_signaling_message_callback_.clear();
- webrtc_signaling_complete_callback_.clear();
- wifi_lan_mediums_.clear();
- use_valid_peer_connection_ = true;
- peer_connection_latency_ = absl::ZeroDuration();
- });
- Sync();
-}
-
-void MediumEnvironment::Sync(bool enable_notifications) {
- enable_notifications_ = enable_notifications;
- NEARBY_LOGS(INFO) << "MediumEnvironment::sync=" << enable_notifications;
- int count = 0;
- do {
- CountDownLatch latch(1);
- count = job_count_ + 1;
- // We are about to schedule one last job.
- // When it is done, counter must be equal to count.
- // However, if pending jobs schedule anything else,
- // it will be pending after us.
- // If we want to ensure we are completely idle, then we have to
- // repeat sync, until this becomes true.
- RunOnMediumEnvironmentThread([&latch]() { latch.CountDown(); });
- latch.Await();
- } while (count < job_count_);
- NEARBY_LOGS(INFO) << "MediumEnvironment::Sync(): done [count=" << count
- << "]";
-}
-
-const EnvironmentConfig& MediumEnvironment::GetEnvironmentConfig() {
- return config_;
-}
-
-void MediumEnvironment::OnBluetoothAdapterChangedState(
- api::BluetoothAdapter& adapter, api::BluetoothDevice& adapter_device,
- std::string name, bool enabled, api::BluetoothAdapter::ScanMode mode) {
- if (!enabled_) return;
- CountDownLatch latch(1);
- RunOnMediumEnvironmentThread([this, &adapter, &adapter_device,
- name = std::move(name), enabled, mode,
- &latch]() {
- NEARBY_LOGS(INFO) << "[adapter=" << &adapter
- << ", device=" << &adapter_device << "] update: name="
- << ", enabled=" << enabled << ", mode=" << int32_t(mode);
- for (auto& medium_info : bluetooth_mediums_) {
- auto& info = medium_info.second;
- // Do not send notification to medium that owns this adapter.
- if (info.adapter == &adapter) continue;
- NEARBY_LOGS(INFO) << "[adapter=" << &adapter
- << ", device=" << &adapter_device
- << "] notify: adapter=" << info.adapter;
- OnBluetoothDeviceStateChanged(info, adapter_device, name, mode, enabled);
- }
- // We don't care if there is an adapter already since all we store is a
- // pointer. Pointer must remain valid for the duration of a Core session
- // (since it is owned by the correspoinding Medium, and mediums lifetime
- // matches Core lifetime).
- if (enabled) {
- bluetooth_adapters_.emplace(&adapter, &adapter_device);
- } else {
- bluetooth_adapters_.erase(&adapter);
- }
- latch.CountDown();
- });
- latch.Await();
-}
-
-void MediumEnvironment::OnBluetoothDeviceStateChanged(
- BluetoothMediumContext& info, api::BluetoothDevice& device,
- const std::string& name, api::BluetoothAdapter::ScanMode mode,
- bool enabled) {
- if (!enabled_) return;
- auto item = info.devices.find(&device);
- if (item == info.devices.end()) {
- NEARBY_LOGS(INFO) << "G3 OnBluetoothDeviceStateChanged [device impl="
- << &device << "]: new device; notify="
- << enable_notifications_.load();
- if (mode == api::BluetoothAdapter::ScanMode::kConnectableDiscoverable &&
- enabled) {
- // New device is turned on, and is in discoverable state.
- // Store device name, and report it as discovered.
- info.devices.emplace(&device, name);
- if (enable_notifications_) {
- RunOnMediumEnvironmentThread(
- [&info, &device]() { info.callback.device_discovered_cb(device); });
- }
- }
- } else {
- NEARBY_LOGS(INFO) << "G3 OnBluetoothDeviceStateChanged [device impl="
- << &device << "]: existing device; notify="
- << enable_notifications_.load();
- auto& discovered_name = item->second;
- if (mode == api::BluetoothAdapter::ScanMode::kConnectableDiscoverable &&
- enabled) {
- if (name != discovered_name) {
- // Known device is turned on, and is in discoverable state.
- // Store device name, and report it as renamed.
- item->second = name;
- if (enable_notifications_) {
- RunOnMediumEnvironmentThread([&info, &device]() {
- info.callback.device_name_changed_cb(device);
- });
- }
- } else {
- // Device is in discovery mode, so we are reporting it anyway.
- if (enable_notifications_) {
- RunOnMediumEnvironmentThread([&info, &device]() {
- info.callback.device_discovered_cb(device);
- });
- }
- }
- }
- if (!enabled) {
- // Known device is turned off.
- // Erase it from the map, and report as lost.
- if (enable_notifications_) {
- RunOnMediumEnvironmentThread(
- [&info, &device]() { info.callback.device_lost_cb(device); });
- }
- info.devices.erase(item);
- }
- }
-}
-
-api::BluetoothDevice* MediumEnvironment::FindBluetoothDevice(
- const std::string& mac_address) {
- api::BluetoothDevice* device = nullptr;
- CountDownLatch latch(1);
- RunOnMediumEnvironmentThread([this, &device, &latch, &mac_address]() {
- for (auto& item : bluetooth_mediums_) {
- auto* adapter = item.second.adapter;
- if (!adapter) continue;
- if (adapter->GetMacAddress() == mac_address) {
- device = bluetooth_adapters_[adapter];
- break;
- }
- }
- latch.CountDown();
- });
- latch.Await();
- return device;
-}
-
-void MediumEnvironment::OnBlePeripheralStateChanged(
- BleMediumContext& info, api::BlePeripheral& peripheral,
- const std::string& service_id, bool fast_advertisement, bool enabled) {
- if (!enabled_) return;
- NEARBY_LOGS(INFO) << "G3 OnBleServiceStateChanged [peripheral impl="
- << &peripheral << "]; context=" << &info
- << "; service_id=" << service_id
- << "; notify=" << enable_notifications_.load();
- if (!enable_notifications_) return;
- RunOnMediumEnvironmentThread([&info, enabled, &peripheral, service_id,
- fast_advertisement]() {
- NEARBY_LOGS(INFO) << "G3 [Run] OnBleServiceStateChanged [peripheral impl="
- << &peripheral << "]; context=" << &info
- << "; service_id=" << service_id
- << "; notify=" << enabled;
- if (enabled) {
- info.discovery_callback.peripheral_discovered_cb(peripheral, service_id,
- fast_advertisement);
- } else {
- info.discovery_callback.peripheral_lost_cb(peripheral, service_id);
- }
- });
-}
-
-void MediumEnvironment::OnWifiLanServiceStateChanged(
- WifiLanMediumContext& info, const NsdServiceInfo& service_info,
- bool enabled) {
- if (!enabled_) return;
- std::string service_type = service_info.GetServiceType();
- auto item = info.discovered_services.find(service_type);
- if (item == info.discovered_services.end()) {
- NEARBY_LOGS(INFO) << "G3 OnWifiLanServiceStateChanged; context=" << &info
- << "; service_type=" << service_type
- << "; enabled=" << enabled
- << "; notify=" << enable_notifications_.load();
- if (enabled) {
- // Find advertising service with matched service_type. Report it as
- // discovered.
- NsdServiceInfo discovered_service_info(service_info);
- info.discovered_services.insert({service_type, discovered_service_info});
- if (enable_notifications_) {
- RunOnMediumEnvironmentThread(
- [&info, discovered_service_info, service_type]() {
- auto item = info.discovered_callbacks.find(service_type);
- if (item != info.discovered_callbacks.end()) {
- item->second.service_discovered_cb(discovered_service_info);
- }
- });
- }
- }
- } else {
- NEARBY_LOGS(INFO)
- << "G3 OnWifiLanServiceStateChanged: exisitng service; context="
- << &info << "; service_type=" << service_type << "; enabled=" << enabled
- << "; notify=" << enable_notifications_.load();
- if (enabled) {
- if (enable_notifications_) {
- RunOnMediumEnvironmentThread(
- [&info, service_info = service_info, service_type]() {
- auto item = info.discovered_callbacks.find(service_type);
- if (item != info.discovered_callbacks.end()) {
- item->second.service_discovered_cb(service_info);
- }
- });
- }
- } else {
- // Known service is off.
- // Erase it from the map, and report as lost.
- if (enable_notifications_) {
- RunOnMediumEnvironmentThread(
- [&info, service_info = service_info, service_type]() {
- auto item = info.discovered_callbacks.find(service_type);
- if (item != info.discovered_callbacks.end()) {
- item->second.service_lost_cb(service_info);
- }
- });
- }
- info.discovered_services.erase(item);
- }
- }
-}
-
-void MediumEnvironment::RunOnMediumEnvironmentThread(
- std::function<void()> runnable) {
- job_count_++;
- executor_.Execute(std::move(runnable));
-}
-
-void MediumEnvironment::RegisterBluetoothMedium(
- api::BluetoothClassicMedium& medium,
- api::BluetoothAdapter& medium_adapter) {
- if (!enabled_) return;
- RunOnMediumEnvironmentThread([this, &medium, &medium_adapter]() {
- auto& context = bluetooth_mediums_
- .insert({&medium,
- BluetoothMediumContext{
- .adapter = &medium_adapter,
- }})
- .first->second;
- auto* owned_adapter = context.adapter;
- NEARBY_LOGS(INFO) << "Registered: medium=" << &medium
- << "; adapter=" << owned_adapter;
- for (auto& adapter_device : bluetooth_adapters_) {
- auto& adapter = adapter_device.first;
- auto& device = adapter_device.second;
- if (adapter == nullptr) continue;
- OnBluetoothDeviceStateChanged(context, *device, adapter->GetName(),
- adapter->GetScanMode(),
- adapter->IsEnabled());
- }
- });
-}
-
-void MediumEnvironment::UpdateBluetoothMedium(
- api::BluetoothClassicMedium& medium, BluetoothDiscoveryCallback callback) {
- if (!enabled_) return;
- RunOnMediumEnvironmentThread(
- [this, &medium, callback = std::move(callback)]() {
- auto item = bluetooth_mediums_.find(&medium);
- if (item == bluetooth_mediums_.end()) return;
- auto& context = item->second;
- context.callback = std::move(callback);
- auto* owned_adapter = context.adapter;
- NEARBY_LOGS(INFO) << "Updated: this=" << this << "; medium=" << &medium
- << "; adapter=" << owned_adapter
- << "; name=" << owned_adapter->GetName()
- << "; enabled=" << owned_adapter->IsEnabled()
- << "; mode=" << int32_t(owned_adapter->GetScanMode());
- for (auto& adapter_device : bluetooth_adapters_) {
- auto& adapter = adapter_device.first;
- auto& device = adapter_device.second;
- if (adapter == nullptr) continue;
- OnBluetoothDeviceStateChanged(context, *device, adapter->GetName(),
- adapter->GetScanMode(),
- adapter->IsEnabled());
- }
- });
-}
-
-void MediumEnvironment::UnregisterBluetoothMedium(
- api::BluetoothClassicMedium& medium) {
- if (!enabled_) return;
- RunOnMediumEnvironmentThread([this, &medium]() {
- auto item = bluetooth_mediums_.extract(&medium);
- if (item.empty()) return;
- NEARBY_LOGS(INFO) << "Unregistered Bluetooth medium:" << &medium;
- });
-}
-
-void MediumEnvironment::RegisterBleMedium(api::BleMedium& medium) {
- if (!enabled_) return;
- RunOnMediumEnvironmentThread([this, &medium]() {
- ble_mediums_.insert({&medium, BleMediumContext{}});
- NEARBY_LOGS(INFO) << "Registered: medium:" << &medium;
- });
-}
-
-void MediumEnvironment::UpdateBleMediumForAdvertising(
- api::BleMedium& medium, api::BlePeripheral& peripheral,
- const std::string& service_id, bool fast_advertisement, bool enabled) {
- if (!enabled_) return;
- RunOnMediumEnvironmentThread([this, &medium, &peripheral, service_id,
- fast_advertisement, enabled]() {
- auto item = ble_mediums_.find(&medium);
- if (item == ble_mediums_.end()) {
- NEARBY_LOGS(INFO) << "UpdateBleMediumForAdvertising failed. There is no "
- "medium registered.";
- return;
- }
- auto& context = item->second;
- context.ble_peripheral = &peripheral;
- context.advertising = enabled;
- context.fast_advertisement = fast_advertisement;
- NEARBY_LOGS(INFO) << "Update Ble medium for advertising: this=" << this
- << "; medium=" << &medium << "; service_id=" << service_id
- << "; name=" << peripheral.GetName()
- << "; fast_advertisement=" << fast_advertisement
- << "; enabled=" << enabled;
- for (auto& medium_info : ble_mediums_) {
- auto& local_medium = medium_info.first;
- auto& info = medium_info.second;
- // Do not send notification to the same medium.
- if (local_medium == &medium) continue;
- OnBlePeripheralStateChanged(info, peripheral, service_id,
- fast_advertisement, enabled);
- }
- });
-}
-
-void MediumEnvironment::UpdateBleMediumForScanning(
- api::BleMedium& medium, const std::string& service_id,
- const std::string& fast_advertisement_service_uuid,
- BleDiscoveredPeripheralCallback callback, bool enabled) {
- if (!enabled_) return;
- RunOnMediumEnvironmentThread(
- [this, &medium, service_id, fast_advertisement_service_uuid,
- callback = std::move(callback), enabled]() {
- auto item = ble_mediums_.find(&medium);
- if (item == ble_mediums_.end()) {
- NEARBY_LOGS(INFO)
- << "UpdateBleMediumFoScanning failed. There is no medium "
- "registered.";
- return;
- }
- auto& context = item->second;
- context.discovery_callback = std::move(callback);
- NEARBY_LOGS(INFO) << "Update Ble medium for scanning: this=" << this
- << "; medium=" << &medium
- << "; service_id=" << service_id
- << "; fast_advertisement_service_uuid="
- << fast_advertisement_service_uuid
- << "; enabled=" << enabled;
- for (auto& medium_info : ble_mediums_) {
- auto& local_medium = medium_info.first;
- auto& info = medium_info.second;
- // Do not send notification to the same medium.
- if (local_medium == &medium) continue;
- // Search advertising mediums and send notification.
- if (info.advertising && enabled) {
- OnBlePeripheralStateChanged(context, *(info.ble_peripheral),
- service_id, info.fast_advertisement,
- enabled);
- }
- }
- });
-}
-
-void MediumEnvironment::UpdateBleMediumForAcceptedConnection(
- api::BleMedium& medium, const std::string& service_id,
- BleAcceptedConnectionCallback callback) {
- if (!enabled_) return;
- RunOnMediumEnvironmentThread(
- [this, &medium, service_id, callback = std::move(callback)]() {
- auto item = ble_mediums_.find(&medium);
- if (item == ble_mediums_.end()) {
- NEARBY_LOGS(INFO)
- << "Update Ble medium failed. There is no medium registered.";
- return;
- }
- auto& context = item->second;
- context.accepted_connection_callback = std::move(callback);
- NEARBY_LOGS(INFO) << "Update Ble medium for accepted callback: this="
- << this << "; medium=" << &medium
- << "; service_id=" << service_id;
- });
-}
-
-void MediumEnvironment::UnregisterBleMedium(api::BleMedium& medium) {
- if (!enabled_) return;
- RunOnMediumEnvironmentThread([this, &medium]() {
- auto item = ble_mediums_.extract(&medium);
- if (item.empty()) return;
- NEARBY_LOGS(INFO) << "Unregistered Ble medium";
- });
-}
-
-void MediumEnvironment::CallBleAcceptedConnectionCallback(
- api::BleMedium& medium, api::BleSocket& socket,
- const std::string& service_id) {
- if (!enabled_) return;
- RunOnMediumEnvironmentThread(
- [this, &medium, &socket, service_id]() {
- auto item = ble_mediums_.find(&medium);
- if (item == ble_mediums_.end()) {
- NEARBY_LOGS(INFO)
- << "Call AcceptedConnectionCallback failed. There is no medium "
- "registered.";
- return;
- }
- auto& info = item->second;
- info.accepted_connection_callback.accepted_cb(socket, service_id);
- });
-}
-
-void MediumEnvironment::RegisterWebRtcSignalingMessenger(
- absl::string_view self_id, OnSignalingMessageCallback message_callback,
- OnSignalingCompleteCallback complete_callback) {
- if (!enabled_) return;
- RunOnMediumEnvironmentThread([this, self_id{std::string(self_id)},
- message_callback{std::move(message_callback)},
- complete_callback{
- std::move(complete_callback)}]() {
- webrtc_signaling_message_callback_[self_id] = std::move(message_callback);
- webrtc_signaling_complete_callback_[self_id] = std::move(complete_callback);
- NEARBY_LOGS(INFO) << "Registered signaling message callback for id = "
- << self_id;
- });
-}
-
-void MediumEnvironment::UnregisterWebRtcSignalingMessenger(
- absl::string_view self_id) {
- if (!enabled_) return;
- RunOnMediumEnvironmentThread([this, self_id{std::string(self_id)}]() {
- auto message_callback_item =
- webrtc_signaling_message_callback_.extract(self_id);
- auto complete_callback_item =
- webrtc_signaling_complete_callback_.extract(self_id);
- NEARBY_LOGS(INFO) << "Unregistered signaling message callback for id = "
- << self_id;
- });
-}
-
-void MediumEnvironment::SendWebRtcSignalingMessage(absl::string_view peer_id,
- const ByteArray& message) {
- if (!enabled_) return;
- RunOnMediumEnvironmentThread(
- [this, peer_id{std::string(peer_id)}, message]() {
- auto item = webrtc_signaling_message_callback_.find(peer_id);
- if (item == webrtc_signaling_message_callback_.end()) {
- NEARBY_LOGS(WARNING)
- << "No callback registered for peer id = " << peer_id;
- return;
- }
-
- item->second(message);
- });
-}
-
-void MediumEnvironment::SendWebRtcSignalingComplete(absl::string_view peer_id,
- bool success) {
- if (!enabled_) return;
- RunOnMediumEnvironmentThread(
- [this, peer_id{std::string(peer_id)}, success]() {
- auto item = webrtc_signaling_complete_callback_.find(peer_id);
- if (item == webrtc_signaling_complete_callback_.end()) {
- NEARBY_LOGS(WARNING)
- << "No callback registered for peer id = " << peer_id;
- return;
- }
-
- item->second(success);
- });
-}
-
-void MediumEnvironment::SetUseValidPeerConnection(
- bool use_valid_peer_connection) {
- use_valid_peer_connection_ = use_valid_peer_connection;
-}
-
-bool MediumEnvironment::GetUseValidPeerConnection() {
- return use_valid_peer_connection_;
-}
-
-void MediumEnvironment::SetPeerConnectionLatency(
- absl::Duration peer_connection_latency) {
- peer_connection_latency_ = peer_connection_latency;
-}
-
-absl::Duration MediumEnvironment::GetPeerConnectionLatency() {
- return peer_connection_latency_;
-}
-
-std::string MediumEnvironment::GetFakeIPAddress() const {
- std::string ip_address;
- ip_address.resize(4);
- uint32_t raw_ip_addr = Prng().NextUint32();
- ip_address[0] = static_cast<char>(raw_ip_addr >> 24);
- ip_address[1] = static_cast<char>(raw_ip_addr >> 16);
- ip_address[2] = static_cast<char>(raw_ip_addr >> 8);
- ip_address[3] = static_cast<char>(raw_ip_addr >> 0);
-
- return ip_address;
-}
-
-int MediumEnvironment::GetFakePort() const {
- uint16_t port = Prng().NextUint32();
-
- return port;
-}
-
-void MediumEnvironment::RegisterWifiLanMedium(api::WifiLanMedium& medium) {
- if (!enabled_) return;
- RunOnMediumEnvironmentThread([this, &medium]() {
- wifi_lan_mediums_.insert({&medium, WifiLanMediumContext{}});
- NEARBY_LOG(INFO, "Registered: medium=%p", &medium);
- });
-}
-
-void MediumEnvironment::UpdateWifiLanMediumForAdvertising(
- api::WifiLanMedium& medium, const NsdServiceInfo& service_info,
- bool enabled) {
- if (!enabled_) return;
- RunOnMediumEnvironmentThread([this, &medium, service_info = service_info,
- enabled]() {
- std::string service_type = service_info.GetServiceType();
- NEARBY_LOGS(INFO) << "Update WifiLan medium for advertising: this=" << this
- << "; medium=" << &medium
- << "; service_name=" << service_info.GetServiceName()
- << "; service_type=" << service_type
- << ", enabled=" << enabled;
- for (auto& medium_info : wifi_lan_mediums_) {
- auto& local_medium = medium_info.first;
- auto& info = medium_info.second;
- // Do not send notification to the same medium but update
- // service info map.
- if (local_medium == &medium) {
- if (enabled) {
- info.advertising_services.insert({service_type, service_info});
- } else {
- info.advertising_services.erase(service_type);
- }
- continue;
- }
- OnWifiLanServiceStateChanged(info, service_info, enabled);
- }
- });
-}
-
-void MediumEnvironment::UpdateWifiLanMediumForDiscovery(
- api::WifiLanMedium& medium, WifiLanDiscoveredServiceCallback callback,
- const std::string& service_type, bool enabled) {
- if (!enabled_) return;
- RunOnMediumEnvironmentThread([this, &medium, callback = std::move(callback),
- service_type, enabled]() {
- auto item = wifi_lan_mediums_.find(&medium);
- if (item == wifi_lan_mediums_.end()) {
- NEARBY_LOGS(INFO)
- << "UpdateWifiLanMediumForDiscovery failed. There is no medium "
- "registered.";
- return;
- }
- auto& context = item->second;
- context.discovered_callbacks.insert({service_type, std::move(callback)});
- NEARBY_LOGS(INFO) << "Update WifiLan medium for discovery: this=" << this
- << "; medium=" << &medium
- << "; service_type=" << service_type
- << "; enabled=" << enabled;
- for (auto& medium_info : wifi_lan_mediums_) {
- auto& local_medium = medium_info.first;
- auto& info = medium_info.second;
- // Do not send notification to the same medium.
- if (local_medium == &medium) continue;
- // Search advertising services and send notification.
- for (auto& advertising_service : info.advertising_services) {
- auto& service_info = advertising_service.second;
- OnWifiLanServiceStateChanged(context, service_info, /*enabled=*/true);
- }
- }
- });
-}
-
-void MediumEnvironment::UnregisterWifiLanMedium(api::WifiLanMedium& medium) {
- if (!enabled_) return;
- RunOnMediumEnvironmentThread([this, &medium]() {
- auto item = wifi_lan_mediums_.extract(&medium);
- if (item.empty()) return;
- NEARBY_LOGS(INFO) << "Unregistered WifiLan medium";
- });
-}
-
-api::WifiLanMedium* MediumEnvironment::GetWifiLanMedium(
- const std::string& ip_address, int port) {
- for (auto& medium_info : wifi_lan_mediums_) {
- auto* medium_found = medium_info.first;
- auto& info = medium_info.second;
- for (auto& advertising_service : info.advertising_services) {
- auto& service_info = advertising_service.second;
- if (ip_address == service_info.GetIPAddress() &&
- port == service_info.GetPort()) {
- return medium_found;
- }
- }
- }
- return nullptr;
-}
-
-void MediumEnvironment::SetFeatureFlags(const FeatureFlags::Flags& flags) {
- const_cast<FeatureFlags&>(FeatureFlags::GetInstance()).SetFlags(flags);
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/medium_environment.h b/chromium/third_party/nearby/src/cpp/platform/base/medium_environment.h
deleted file mode 100644
index 3924b6e611f..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/medium_environment.h
+++ /dev/null
@@ -1,321 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_BASE_MEDIUM_ENVIRONMENT_H_
-#define PLATFORM_BASE_MEDIUM_ENVIRONMENT_H_
-
-#include <atomic>
-#include <memory>
-
-#include "absl/container/flat_hash_map.h"
-#include "absl/strings/string_view.h"
-#include "platform/api/ble.h"
-#include "platform/api/bluetooth_adapter.h"
-#include "platform/api/bluetooth_classic.h"
-#include "platform/api/webrtc.h"
-#include "platform/api/wifi_lan.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/feature_flags.h"
-#include "platform/base/listeners.h"
-#include "platform/base/nsd_service_info.h"
-#include "platform/public/single_thread_executor.h"
-
-namespace location {
-namespace nearby {
-
-// Environment config that can control availability of certain mediums for
-// testing.
-struct EnvironmentConfig {
- // Control whether WEB_RTC medium is enabled in the environment.
- // This is currently set to false, due to http://b/139734036 that would lead
- // to flaky tests.
- bool webrtc_enabled = false;
-};
-
-// MediumEnvironment is a simulated environment which allows multiple instances
-// of simulated HW devices to "work" together as if they are physical.
-// For each medium type it provides necessary methods to implement
-// advertising, discovery and establishment of a data link.
-// NOTE: this code depends on public:types target.
-class MediumEnvironment {
- public:
- using BluetoothDiscoveryCallback =
- api::BluetoothClassicMedium::DiscoveryCallback;
- using BleDiscoveredPeripheralCallback =
- api::BleMedium::DiscoveredPeripheralCallback;
- using BleAcceptedConnectionCallback =
- api::BleMedium::AcceptedConnectionCallback;
- using OnSignalingMessageCallback =
- api::WebRtcSignalingMessenger::OnSignalingMessageCallback;
- using OnSignalingCompleteCallback =
- api::WebRtcSignalingMessenger::OnSignalingCompleteCallback;
- using WifiLanDiscoveredServiceCallback =
- api::WifiLanMedium::DiscoveredServiceCallback;
-
- MediumEnvironment(const MediumEnvironment&) = delete;
- MediumEnvironment& operator=(const MediumEnvironment&) = delete;
-
- // Creates and returns a reference to the global test environment instance.
- static MediumEnvironment& Instance();
-
- // Global ON/OFF switch for medium environment.
- // Start & Stop work as On/Off switch for this object.
- // Default state (after creation) is ON, to make it compatible with early
- // tests that are already using it and relying on it being ON.
-
- // Enables Medium environment.
- void Start(EnvironmentConfig config = EnvironmentConfig());
- // Disables Medium environment.
- void Stop();
-
- // Clears state. No notifications are sent.
- void Reset();
-
- // Waits for all previously scheduled jobs to finish.
- // This method works as a barrier that guarantees that after it returns, all
- // the activities that started before it was called, or while it was running
- // are ended. This means that system is at the state of relaxation when this
- // code returns. It requires external stimulus to get out of relaxation state.
- //
- // If enable_notifications is true (default), simulation environment
- // will send all future notification events to all registered objects,
- // whenever protocol requires that. This is expected behavior.
- // If enabled_notifications is false, future event notifications will not be
- // sent to registered instances. This is useful for protocol shutdown,
- // where we no longer care about notifications, and where notifications may
- // otherwise be delivered after the notification source or target lifeteme has
- // ended, and cause undefined behavior.
- void Sync(bool enable_notifications = true);
-
- // Adds an adapter to internal container.
- // Notify BluetoothClassicMediums if any that adapter state has changed.
- void OnBluetoothAdapterChangedState(api::BluetoothAdapter& adapter,
- api::BluetoothDevice& adapter_device,
- std::string name, bool enabled,
- api::BluetoothAdapter::ScanMode mode);
-
- // Adds medium-related info to allow for adapter discovery to work.
- // This provides acccess to this medium from other mediums, when protocol
- // expects they should communicate.
- void RegisterBluetoothMedium(api::BluetoothClassicMedium& medium,
- api::BluetoothAdapter& medium_adapter);
-
- // Updates callback info to allow for dispatch of discovery events.
- //
- // Invokes callback asynchronously when any changes happen to discoverable
- // devices, or if the defice is turned off, whether or not it is discoverable,
- // if it was ever reported as discoverable.
- //
- // This should be called when discoverable state changes.
- // with user-specified callback when discovery is enabled, and with default
- // (empty) callback otherwise.
- void UpdateBluetoothMedium(api::BluetoothClassicMedium& medium,
- BluetoothDiscoveryCallback callback);
-
- // Removes medium-related info. This should correspond to device power off.
- void UnregisterBluetoothMedium(api::BluetoothClassicMedium& medium);
-
- // Returns a Bluetooth Device object matching given mac address to nullptr.
- api::BluetoothDevice* FindBluetoothDevice(const std::string& mac_address);
-
- const EnvironmentConfig& GetEnvironmentConfig();
-
- // Registers |message_callback| to receive messages sent to device with id
- // |self_id|, and |complete_callback| to notify when signaling is complete.
- void RegisterWebRtcSignalingMessenger(
- absl::string_view self_id, OnSignalingMessageCallback message_callback,
- OnSignalingCompleteCallback complete_callback);
-
- // Unregisters the callback listening to incoming messages for |self_id|.
- void UnregisterWebRtcSignalingMessenger(absl::string_view self_id);
-
- // Simulates sending a signaling message |message| to device with id
- // |peer_id|.
- void SendWebRtcSignalingMessage(absl::string_view peer_id,
- const ByteArray& message);
-
- // Simulates sending an "signaling complete" signal to the WebRTC medium.
- void SendWebRtcSignalingComplete(absl::string_view peer_id, bool success);
-
- // Used to set if WebRtcMedium should use a valid peer connection or nullptr
- // in tests.
- void SetUseValidPeerConnection(bool use_valid_peer_connection);
-
- bool GetUseValidPeerConnection();
-
- // Used to set latency when creating the peer connection in tests.
- void SetPeerConnectionLatency(absl::Duration peer_connection_latency);
-
- absl::Duration GetPeerConnectionLatency();
-
- // Adds medium-related info to allow for scanning/advertising to work.
- // This provides acccess to this medium from other mediums, when protocol
- // expects they should communicate.
- void RegisterBleMedium(api::BleMedium& medium);
-
- // Updates advertising info to indicate the current medium is exposing
- // advertising event.
- void UpdateBleMediumForAdvertising(api::BleMedium& medium,
- api::BlePeripheral& peripheral,
- const std::string& service_id,
- bool fast_advertisement, bool enabled);
-
- // Updates discovery callback info to allow for dispatch of discovery events.
- //
- // Invokes callback asynchronously when any changes happen to discoverable
- // devices, or if the defice is turned off, whether or not it is discoverable,
- // if it was ever reported as discoverable.
- //
- // This should be called when discoverable state changes.
- // with user-specified callback when discovery is enabled, and with default
- // (empty) callback otherwise.
- void UpdateBleMediumForScanning(
- api::BleMedium& medium, const std::string& service_id,
- const std::string& fast_advertisement_service_uuid,
- BleDiscoveredPeripheralCallback callback, bool enabled);
-
- // Updates Accepted connection callback info to allow for dispatch of
- // advertising events.
- void UpdateBleMediumForAcceptedConnection(
- api::BleMedium& medium, const std::string& service_id,
- BleAcceptedConnectionCallback callback);
-
- // Removes medium-related info. This should correspond to device power off.
- void UnregisterBleMedium(api::BleMedium& medium);
-
- // Call back when advertising has created the server socket and is ready for
- // connect.
- void CallBleAcceptedConnectionCallback(api::BleMedium& medium,
- api::BleSocket& socket,
- const std::string& service_id);
-
- // Adds medium-related info to allow for discovery/advertising to work.
- // This provides acccess to this medium from other mediums, when protocol
- // expects they should communicate.
- void RegisterWifiLanMedium(api::WifiLanMedium& medium);
-
- // Updates advertising info to indicate the current medium is exposing
- // advertising event.
- void UpdateWifiLanMediumForAdvertising(api::WifiLanMedium& medium,
- const NsdServiceInfo& nsd_service_info,
- bool enabled);
-
- // Updates discovery callback info to allow for dispatch of discovery events.
- //
- // This should be called when discoverable state changes.
- // with user-specified callback when discovery is enabled, and with default
- // (empty) callback otherwise.
- void UpdateWifiLanMediumForDiscovery(
- api::WifiLanMedium& medium, WifiLanDiscoveredServiceCallback callback,
- const std::string& service_type, bool enabled);
-
- // Gets Fake IP address for WifiLan medium.
- std::string GetFakeIPAddress() const;
-
- // Gets Fake port number for WifiLan medium.
- int GetFakePort() const;
-
- // Removes medium-related info. This should correspond to device power off.
- void UnregisterWifiLanMedium(api::WifiLanMedium& medium);
-
- // Returns WifiLan medium whose advertising service matching IP address and
- // port, or nullptr.
- api::WifiLanMedium* GetWifiLanMedium(const std::string& ip_address, int port);
-
- void SetFeatureFlags(const FeatureFlags::Flags& flags);
-
- private:
- struct BluetoothMediumContext {
- BluetoothDiscoveryCallback callback;
- api::BluetoothAdapter* adapter = nullptr;
- // discovered device vs device name map.
- absl::flat_hash_map<api::BluetoothDevice*, std::string> devices;
- };
-
- struct BleMediumContext {
- BleDiscoveredPeripheralCallback discovery_callback;
- BleAcceptedConnectionCallback accepted_connection_callback;
- api::BlePeripheral* ble_peripheral = nullptr;
- bool advertising = false;
- bool fast_advertisement = false;
- };
-
- struct WifiLanMediumContext {
- // advertising service type vs NsdServiceInfo map.
- absl::flat_hash_map<std::string, NsdServiceInfo> advertising_services;
- // discovered service type vs callback map.
- absl::flat_hash_map<std::string, WifiLanDiscoveredServiceCallback>
- discovered_callbacks;
- // discovered service vs service type map.
- absl::flat_hash_map<std::string, NsdServiceInfo> discovered_services;
- };
-
- // This is a singleton object, for which destructor will never be called.
- // Constructor will be invoked once from Instance() static method.
- // Object is create in-place (with a placement new) to guarantee that
- // destructor is not scheduled for execution at exit.
- MediumEnvironment() = default;
- ~MediumEnvironment() = default;
-
- void OnBluetoothDeviceStateChanged(BluetoothMediumContext& info,
- api::BluetoothDevice& device,
- const std::string& name,
- api::BluetoothAdapter::ScanMode mode,
- bool enabled);
-
- void OnBlePeripheralStateChanged(BleMediumContext& info,
- api::BlePeripheral& peripheral,
- const std::string& service_id,
- bool fast_advertisement, bool enabled);
-
- void OnWifiLanServiceStateChanged(WifiLanMediumContext& info,
- const NsdServiceInfo& service_info,
- bool enabled);
-
- void RunOnMediumEnvironmentThread(std::function<void()> runnable);
-
- std::atomic_bool enabled_ = true;
- std::atomic_int job_count_ = 0;
- std::atomic_bool enable_notifications_ = false;
- SingleThreadExecutor executor_;
- EnvironmentConfig config_;
-
- // The following data members are accessed in the context of a private
- // executor_ thread.
- absl::flat_hash_map<api::BluetoothAdapter*, api::BluetoothDevice*>
- bluetooth_adapters_;
- absl::flat_hash_map<api::BluetoothClassicMedium*, BluetoothMediumContext>
- bluetooth_mediums_;
-
- absl::flat_hash_map<api::BleMedium*, BleMediumContext> ble_mediums_;
-
- // Maps peer id to callback for receiving signaling messages.
- absl::flat_hash_map<std::string, OnSignalingMessageCallback>
- webrtc_signaling_message_callback_;
-
- // Maps peer id to callback for signaling complete events.
- absl::flat_hash_map<std::string, OnSignalingCompleteCallback>
- webrtc_signaling_complete_callback_;
-
- absl::flat_hash_map<api::WifiLanMedium*, WifiLanMediumContext>
- wifi_lan_mediums_;
-
- bool use_valid_peer_connection_ = true;
- absl::Duration peer_connection_latency_ = absl::ZeroDuration();
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_BASE_MEDIUM_ENVIRONMENT_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/nsd_service_info.cc b/chromium/third_party/nearby/src/cpp/platform/base/nsd_service_info.cc
deleted file mode 100644
index e5c401a9399..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/nsd_service_info.cc
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright 2021 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/base/nsd_service_info.h"
-
-namespace location {
-namespace nearby {
-
-constexpr absl::string_view NsdServiceInfo::kNsdTypeFormat;
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/output_stream.h b/chromium/third_party/nearby/src/cpp/platform/base/output_stream.h
deleted file mode 100644
index 7048419da2e..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/output_stream.h
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_BASE_OUTPUT_STREAM_H_
-#define PLATFORM_BASE_OUTPUT_STREAM_H_
-
-#include "platform/base/byte_array.h"
-#include "platform/base/exception.h"
-
-namespace location {
-namespace nearby {
-
-// An OutputStream represents an output stream of bytes.
-//
-// https://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html
-class OutputStream {
- public:
- virtual ~OutputStream() = default;
-
- virtual Exception Write(const ByteArray& data) = 0; // throws Exception::kIo
- virtual Exception Flush() = 0; // throws Exception::kIo
- virtual Exception Close() = 0; // throws Exception::kIo
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_BASE_OUTPUT_STREAM_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/prng.cc b/chromium/third_party/nearby/src/cpp/platform/base/prng.cc
deleted file mode 100644
index 9ae71abf09e..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/prng.cc
+++ /dev/null
@@ -1,59 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/base/prng.h"
-
-#include <limits>
-
-#include "absl/time/clock.h"
-
-namespace location {
-namespace nearby {
-
-#define UNSIGNED_INT_BITMASK (std::numeric_limits<unsigned int>::max())
-
-Prng::Prng() {
- // absl::GetCurrentTimeNanos() returns 64 bits, but srand() wants an unsigned
- // int, so we may have to lose some of those 64 bits.
- //
- // The lower bits of the current-time-in-nanos are likely to have more entropy
- // than the upper bits, so choose the former.
- srand(static_cast<unsigned int>(absl::GetCurrentTimeNanos() &
- UNSIGNED_INT_BITMASK));
-}
-
-Prng::~Prng() {
- // Nothing to do.
-}
-
-#define RANDOM_BYTE (rand() & 0x0FF) // NOLINT
-
-std::int32_t Prng::NextInt32() {
- return (static_cast<std::int32_t>(RANDOM_BYTE) << 24) |
- (static_cast<std::int32_t>(RANDOM_BYTE) << 16) |
- (static_cast<std::int32_t>(RANDOM_BYTE) << 8) |
- (static_cast<std::int32_t>(RANDOM_BYTE));
-}
-
-std::uint32_t Prng::NextUint32() {
- return static_cast<std::uint32_t>(NextInt32());
-}
-
-std::int64_t Prng::NextInt64() {
- return (static_cast<std::int64_t>(NextInt32()) << 32) |
- (static_cast<std::int64_t>(NextUint32()));
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/prng_test.cc b/chromium/third_party/nearby/src/cpp/platform/base/prng_test.cc
deleted file mode 100644
index ec15e4a49a2..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/prng_test.cc
+++ /dev/null
@@ -1,87 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/base/prng.h"
-
-#include "gtest/gtest.h"
-
-namespace location {
-namespace nearby {
-
-enum class TestMode {
- kUpperHalfOfInt64,
- kLowerHalfOfInt64,
- kInt32,
- kUint32,
-};
-
-TEST(PrngTest, NextInt32) {
- std::int32_t i = Prng().NextInt32();
- EXPECT_LE(i, std::numeric_limits<std::int32_t>::max());
- EXPECT_GE(i, std::numeric_limits<std::int32_t>::min());
-}
-
-TEST(PrngTest, NextUInt32) {
- std::uint32_t i = Prng().NextUint32();
- EXPECT_LE(i, std::numeric_limits<std::uint32_t>::max());
- EXPECT_GE(i, std::numeric_limits<std::uint32_t>::min());
-}
-
-TEST(PrngTest, NextInt64) {
- std::int64_t i = Prng().NextInt64();
- EXPECT_LE(i, std::numeric_limits<std::int64_t>::max());
- EXPECT_GE(i, std::numeric_limits<std::int64_t>::min());
-}
-
-void ValidateRandom(TestMode mode) {
- int count_all_zeros = 0;
- int count_all_ones = 0;
- std::uint32_t i;
- Prng prng;
- for (int count = 0; count < 100; ++count) {
- switch (mode) {
- case TestMode::kUpperHalfOfInt64:
- i = static_cast<std::uint32_t>(prng.NextInt64() >> 32);
- break;
- case TestMode::kLowerHalfOfInt64:
- i = static_cast<std::uint32_t>(prng.NextInt64());
- break;
- case TestMode::kInt32:
- i = static_cast<std::uint32_t>(prng.NextInt32());
- break;
- case TestMode::kUint32:
- i = static_cast<std::uint32_t>(prng.NextUint32());
- break;
- }
- if (!i) count_all_zeros++;
- if (i == 0xFFFFFFFF) count_all_ones++;
- }
- EXPECT_LE(count_all_zeros, 1);
- EXPECT_LE(count_all_ones, 1);
-}
-
-TEST(PrngTest, ValidateUpperHalfOfInt64) {
- ValidateRandom(TestMode::kUpperHalfOfInt64);
-}
-
-TEST(PrngTest, ValidateLowerHalfOfInt64) {
- ValidateRandom(TestMode::kLowerHalfOfInt64);
-}
-
-TEST(PrngTest, ValidateInt32) { ValidateRandom(TestMode::kInt32); }
-
-TEST(PrngTest, ValidateUint32) { ValidateRandom(TestMode::kUint32); }
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/socket.h b/chromium/third_party/nearby/src/cpp/platform/base/socket.h
deleted file mode 100644
index 09211c15d43..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/base/socket.h
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_BASE_SOCKET_H_
-#define PLATFORM_BASE_SOCKET_H_
-
-#include "platform/base/input_stream.h"
-#include "platform/base/output_stream.h"
-
-namespace location {
-namespace nearby {
-
-// A socket is an endpoint for communication between two machines.
-//
-// https://docs.oracle.com/javase/8/docs/api/java/net/Socket.html
-class Socket {
- public:
- virtual ~Socket() = default;
-
- virtual InputStream& GetInputStream() = 0;
- virtual OutputStream& GetOutputStream() = 0;
- virtual void Close() = 0;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_BASE_SOCKET_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/g3/BUILD b/chromium/third_party/nearby/src/cpp/platform/impl/g3/BUILD
deleted file mode 100644
index 264ee471f55..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/g3/BUILD
+++ /dev/null
@@ -1,131 +0,0 @@
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# https://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-licenses(["notice"])
-
-cc_library(
- name = "types",
- testonly = True,
- srcs = [
- "log_message.cc",
- "scheduled_executor.cc",
- "system_clock.cc",
- ],
- hdrs = [
- "atomic_boolean.h",
- "atomic_reference.h",
- "condition_variable.h",
- "log_message.h",
- "multi_thread_executor.h",
- "mutex.h",
- "pipe.h",
- "scheduled_executor.h",
- "single_thread_executor.h",
- ],
- visibility = ["//visibility:private"],
- deps = [
- "//base",
- "//absl/base:core_headers",
- "//absl/synchronization",
- "//absl/time",
- "//platform/api:platform",
- "//platform/api:types",
- "//platform/base",
- "//platform/base:util",
- "//platform/impl/shared:count_down_latch",
- "//platform/impl/shared:posix_mutex",
- "//thread",
- ],
-)
-
-cc_library(
- name = "comm",
- testonly = True,
- srcs = [
- "ble.cc",
- "bluetooth_adapter.cc",
- "bluetooth_classic.cc",
- "webrtc.cc",
- "wifi_lan.cc",
- ],
- hdrs = [
- "ble.h",
- "bluetooth_adapter.h",
- "bluetooth_classic.h",
- "webrtc.h",
- "wifi_lan.h",
- ],
- visibility = ["//visibility:private"],
- deps = [
- ":types",
- "//absl/base:core_headers",
- "//absl/container:flat_hash_map",
- "//absl/container:flat_hash_set",
- "//absl/strings",
- "//absl/strings:str_format",
- "//absl/synchronization",
- "//platform/api:comm",
- "//platform/base",
- "//platform/base:cancellation_flag",
- "//platform/base:logging",
- "//platform/base:test_util",
- "//platform/impl/shared:count_down_latch",
- "//webrtc/api:create_peerconnection_factory", #buildcleaner: keep
- "//webrtc/api:libjingle_peerconnection_api",
- "//webrtc/api/task_queue:default_task_queue_factory",
- ],
-)
-
-cc_library(
- name = "crypto",
- testonly = True,
- srcs = [
- "crypto.cc",
- ],
- visibility = ["//visibility:private"],
- deps = [
- "//absl/strings",
- "//platform/api:types",
- "//platform/base",
- "//openssl:crypto",
- ],
-)
-
-cc_library(
- name = "g3",
- testonly = True,
- srcs = [
- "platform.cc",
- ],
- visibility = [
- "//analytics:__subpackages__",
- "//core:__subpackages__",
- "//platform:__subpackages__",
- "//proto/analytics:__subpackages__",
- ],
- deps = [
- ":comm",
- ":crypto", # build_cleaner: keep
- ":types",
- "//absl/base:core_headers",
- "//absl/memory",
- "//absl/strings",
- "//absl/time",
- "//platform/api:comm",
- "//platform/api:platform",
- "//platform/api:types",
- "//platform/base:test_util",
- "//platform/impl/shared:count_down_latch",
- "//platform/impl/shared:file",
- ],
-)
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/g3/atomic_boolean.h b/chromium/third_party/nearby/src/cpp/platform/impl/g3/atomic_boolean.h
deleted file mode 100644
index 68f7407e8c5..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/g3/atomic_boolean.h
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_G3_ATOMIC_BOOLEAN_H_
-#define PLATFORM_IMPL_G3_ATOMIC_BOOLEAN_H_
-
-#include <atomic>
-
-#include "platform/api/atomic_boolean.h"
-
-namespace location {
-namespace nearby {
-namespace g3 {
-
-// See documentation in
-// cpp/platform/api/atomic_boolean.h
-class AtomicBoolean : public api::AtomicBoolean {
- public:
- explicit AtomicBoolean(bool initial_value) : value_(initial_value) {}
- ~AtomicBoolean() override = default;
-
- bool Get() const override { return value_.load(); }
- bool Set(bool value) override { return value_.exchange(value); }
-
- private:
- std::atomic_bool value_;
-};
-
-} // namespace g3
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_G3_ATOMIC_BOOLEAN_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/g3/atomic_reference.h b/chromium/third_party/nearby/src/cpp/platform/impl/g3/atomic_reference.h
deleted file mode 100644
index e854ffadfec..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/g3/atomic_reference.h
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_G3_ATOMIC_REFERENCE_H_
-#define PLATFORM_IMPL_G3_ATOMIC_REFERENCE_H_
-
-#include <atomic>
-#include <cstdint>
-
-#include "platform/api/atomic_reference.h"
-
-namespace location {
-namespace nearby {
-namespace g3 {
-
-class AtomicUint32 : public api::AtomicUint32 {
- public:
- explicit AtomicUint32(std::int32_t value) : value_(value) {}
- ~AtomicUint32() override = default;
-
- std::uint32_t Get() const override { return value_; }
- void Set(std::uint32_t value) override { value_ = value; }
-
- private:
- std::atomic<std::uint32_t> value_;
-};
-
-} // namespace g3
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_G3_ATOMIC_REFERENCE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/g3/ble.cc b/chromium/third_party/nearby/src/cpp/platform/impl/g3/ble.cc
deleted file mode 100644
index dd1a368f3c7..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/g3/ble.cc
+++ /dev/null
@@ -1,378 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/g3/ble.h"
-
-#include <iostream>
-#include <memory>
-#include <string>
-
-#include "absl/synchronization/mutex.h"
-#include "platform/api/ble.h"
-#include "platform/base/cancellation_flag_listener.h"
-#include "platform/base/logging.h"
-#include "platform/base/medium_environment.h"
-#include "platform/impl/shared/count_down_latch.h"
-
-namespace location {
-namespace nearby {
-namespace g3 {
-
-BleSocket::~BleSocket() {
- absl::MutexLock lock(&mutex_);
- DoClose();
-}
-
-void BleSocket::Connect(BleSocket& other) {
- absl::MutexLock lock(&mutex_);
- remote_socket_ = &other;
- input_ = other.output_;
-}
-
-InputStream& BleSocket::GetInputStream() {
- auto* remote_socket = GetRemoteSocket();
- CHECK(remote_socket != nullptr);
- return remote_socket->GetLocalInputStream();
-}
-
-OutputStream& BleSocket::GetOutputStream() { return GetLocalOutputStream(); }
-
-BleSocket* BleSocket::GetRemoteSocket() {
- absl::MutexLock lock(&mutex_);
- return remote_socket_;
-}
-
-bool BleSocket::IsConnected() const {
- absl::MutexLock lock(&mutex_);
- return IsConnectedLocked();
-}
-
-bool BleSocket::IsClosed() const {
- absl::MutexLock lock(&mutex_);
- return closed_;
-}
-
-Exception BleSocket::Close() {
- absl::MutexLock lock(&mutex_);
- DoClose();
- return {Exception::kSuccess};
-}
-
-BlePeripheral* BleSocket::GetRemotePeripheral() {
- absl::MutexLock lock(&mutex_);
- return peripheral_;
-}
-
-void BleSocket::DoClose() {
- if (!closed_) {
- remote_socket_ = nullptr;
- output_->GetOutputStream().Close();
- output_->GetInputStream().Close();
- if (IsConnectedLocked()) {
- input_->GetOutputStream().Close();
- input_->GetInputStream().Close();
- }
- closed_ = true;
- }
-}
-
-bool BleSocket::IsConnectedLocked() const { return input_ != nullptr; }
-
-InputStream& BleSocket::GetLocalInputStream() {
- absl::MutexLock lock(&mutex_);
- return output_->GetInputStream();
-}
-
-OutputStream& BleSocket::GetLocalOutputStream() {
- absl::MutexLock lock(&mutex_);
- return output_->GetOutputStream();
-}
-
-std::unique_ptr<api::BleSocket> BleServerSocket::Accept(
- BlePeripheral* peripheral) {
- absl::MutexLock lock(&mutex_);
- if (closed_) return {};
- while (pending_sockets_.empty()) {
- cond_.Wait(&mutex_);
- if (closed_) break;
- }
- if (closed_) return {};
- auto* remote_socket =
- pending_sockets_.extract(pending_sockets_.begin()).value();
- CHECK(remote_socket);
- auto local_socket = std::make_unique<BleSocket>(peripheral);
- local_socket->Connect(*remote_socket);
- remote_socket->Connect(*local_socket);
- cond_.SignalAll();
- return local_socket;
-}
-
-bool BleServerSocket::Connect(BleSocket& socket) {
- absl::MutexLock lock(&mutex_);
- if (closed_) return false;
- if (socket.IsConnected()) {
- NEARBY_LOG(ERROR,
- "Failed to connect to Ble server socket: already connected");
- return true; // already connected.
- }
- // add client socket to the pending list
- pending_sockets_.emplace(&socket);
- cond_.SignalAll();
- while (!socket.IsConnected()) {
- cond_.Wait(&mutex_);
- if (closed_) return false;
- }
- return true;
-}
-
-void BleServerSocket::SetCloseNotifier(std::function<void()> notifier) {
- absl::MutexLock lock(&mutex_);
- close_notifier_ = std::move(notifier);
-}
-
-BleServerSocket::~BleServerSocket() {
- absl::MutexLock lock(&mutex_);
- DoClose();
-}
-
-Exception BleServerSocket::Close() {
- absl::MutexLock lock(&mutex_);
- return DoClose();
-}
-
-Exception BleServerSocket::DoClose() {
- bool should_notify = !closed_;
- closed_ = true;
- if (should_notify) {
- cond_.SignalAll();
- if (close_notifier_) {
- auto notifier = std::move(close_notifier_);
- mutex_.Unlock();
- // Notifier may contain calls to public API, and may cause deadlock, if
- // mutex_ is held during the call.
- notifier();
- mutex_.Lock();
- }
- }
- return {Exception::kSuccess};
-}
-
-BleMedium::BleMedium(api::BluetoothAdapter& adapter)
- : adapter_(static_cast<BluetoothAdapter*>(&adapter)) {
- adapter_->SetBleMedium(this);
- auto& env = MediumEnvironment::Instance();
- env.RegisterBleMedium(*this);
-}
-
-BleMedium::~BleMedium() {
- adapter_->SetBleMedium(nullptr);
- auto& env = MediumEnvironment::Instance();
- env.UnregisterBleMedium(*this);
-
- StopAdvertising(advertising_info_.service_id);
- StopScanning(scanning_info_.service_id);
-
- accept_loops_runner_.Shutdown();
- NEARBY_LOG(INFO, "BleMedium dtor advertising_accept_thread_running_ = %d",
- acceptance_thread_running_.load());
- // If acceptance thread is still running, wait to finish.
- if (acceptance_thread_running_) {
- while (acceptance_thread_running_) {
- shared::CountDownLatch latch(1);
- close_accept_loops_runner_.Execute([&latch]() { latch.CountDown(); });
- latch.Await();
- }
- }
-}
-
-bool BleMedium::StartAdvertising(
- const std::string& service_id, const ByteArray& advertisement_bytes,
- const std::string& fast_advertisement_service_uuid) {
- NEARBY_LOGS(INFO) << "G3 Ble StartAdvertising: service_id=" << service_id
- << ", advertisement bytes=" << advertisement_bytes.data()
- << "(" << advertisement_bytes.size() << "),"
- << " fast advertisement service uuid="
- << fast_advertisement_service_uuid;
- auto& env = MediumEnvironment::Instance();
- auto& peripheral = adapter_->GetPeripheral();
- peripheral.SetAdvertisementBytes(service_id, advertisement_bytes);
- bool fast_advertisement = !fast_advertisement_service_uuid.empty();
- env.UpdateBleMediumForAdvertising(*this, peripheral, service_id,
- fast_advertisement, true);
-
- absl::MutexLock lock(&mutex_);
- if (server_socket_ != nullptr) server_socket_.release();
- server_socket_ = std::make_unique<BleServerSocket>();
-
- acceptance_thread_running_.exchange(true);
- accept_loops_runner_.Execute([&env, this, service_id]() mutable {
- if (!accept_loops_runner_.InShutdown()) {
- while (true) {
- auto client_socket =
- server_socket_->Accept(&(this->adapter_->GetPeripheral()));
- if (client_socket == nullptr) break;
- env.CallBleAcceptedConnectionCallback(*this, *(client_socket.release()),
- service_id);
- }
- }
- acceptance_thread_running_.exchange(false);
- });
- advertising_info_.service_id = service_id;
- return true;
-}
-
-bool BleMedium::StopAdvertising(const std::string& service_id) {
- NEARBY_LOGS(INFO) << "G3 Ble StopAdvertising: service_id=" << service_id;
- {
- absl::MutexLock lock(&mutex_);
- if (advertising_info_.Empty()) {
- NEARBY_LOGS(INFO) << "G3 Ble StopAdvertising: Can't stop advertising "
- "because we never started advertising.";
- return false;
- }
- advertising_info_.Clear();
- }
-
- auto& env = MediumEnvironment::Instance();
- env.UpdateBleMediumForAdvertising(*this, adapter_->GetPeripheral(),
- service_id, /*fast_advertisement=*/false,
- /*enabled=*/false);
- accept_loops_runner_.Shutdown();
- if (server_socket_ == nullptr) {
- NEARBY_LOGS(ERROR) << "G3 Ble StopAdvertising: Failed to find Ble Server "
- "socket: service_id="
- << service_id;
- // Fall through for server socket not found.
- return true;
- }
-
- if (!server_socket_->Close().Ok()) {
- NEARBY_LOGS(INFO)
- << "G3 Ble StopAdvertising: Failed to close Ble server socket for "
- << service_id;
- return false;
- }
- return true;
-}
-
-bool BleMedium::StartScanning(
- const std::string& service_id,
- const std::string& fast_advertisement_service_uuid,
- DiscoveredPeripheralCallback callback) {
- NEARBY_LOGS(INFO) << "G3 Ble StartScanning: service_id=" << service_id;
- auto& env = MediumEnvironment::Instance();
- env.UpdateBleMediumForScanning(*this, service_id,
- fast_advertisement_service_uuid,
- std::move(callback), true);
- {
- absl::MutexLock lock(&mutex_);
- scanning_info_.service_id = service_id;
- }
- return true;
-}
-
-bool BleMedium::StopScanning(const std::string& service_id) {
- NEARBY_LOGS(INFO) << "G3 Ble StopScanning: service_id=" << service_id;
- {
- absl::MutexLock lock(&mutex_);
- if (scanning_info_.Empty()) {
- NEARBY_LOGS(INFO) << "G3 Ble StopDiscovery: Can't stop scanning because "
- "we never started scanning.";
- return false;
- }
- scanning_info_.Clear();
- }
-
- auto& env = MediumEnvironment::Instance();
- env.UpdateBleMediumForScanning(*this, service_id, {}, {}, false);
- return true;
-}
-
-bool BleMedium::StartAcceptingConnections(const std::string& service_id,
- AcceptedConnectionCallback callback) {
- NEARBY_LOGS(INFO) << "G3 Ble StartAcceptingConnections: service_id="
- << service_id;
- auto& env = MediumEnvironment::Instance();
- env.UpdateBleMediumForAcceptedConnection(*this, service_id, callback);
- return true;
-}
-
-bool BleMedium::StopAcceptingConnections(const std::string& service_id) {
- NEARBY_LOGS(INFO) << "G3 Ble StopAcceptingConnections: service_id="
- << service_id;
- auto& env = MediumEnvironment::Instance();
- env.UpdateBleMediumForAcceptedConnection(*this, service_id, {});
- return true;
-}
-
-std::unique_ptr<api::BleSocket> BleMedium::Connect(
- api::BlePeripheral& remote_peripheral, const std::string& service_id,
- CancellationFlag* cancellation_flag) {
- NEARBY_LOG(INFO,
- "G3 Ble Connect [self]: medium=%p, adapter=%p, peripheral=%p, "
- "service_id=%s",
- this, &GetAdapter(), &GetAdapter().GetPeripheral(),
- service_id.c_str());
- // First, find an instance of remote medium, that exposed this peripheral.
- auto& adapter = static_cast<BlePeripheral&>(remote_peripheral).GetAdapter();
- auto* medium = static_cast<BleMedium*>(adapter.GetBleMedium());
-
- if (!medium) return {}; // Can't find medium. Bail out.
-
- BleServerSocket* remote_server_socket = nullptr;
- NEARBY_LOG(INFO,
- "G3 Ble Connect [peer]: medium=%p, adapter=%p, peripheral=%p, "
- "service_id=%s",
- medium, &adapter, &remote_peripheral, service_id.c_str());
- // Then, find our server socket context in this medium.
- {
- absl::MutexLock medium_lock(&medium->mutex_);
- remote_server_socket = medium->server_socket_.get();
- if (remote_server_socket == nullptr) {
- NEARBY_LOGS(ERROR)
- << "G3 Ble Connect: Failed to find Ble Server socket: service_id="
- << service_id;
- return {};
- }
- }
-
- if (cancellation_flag->Cancelled()) {
- NEARBY_LOGS(ERROR) << "G3 BLE Connect: Has been cancelled: "
- "service_id="
- << service_id;
- return {};
- }
-
- CancellationFlagListener listener(cancellation_flag, [this]() {
- NEARBY_LOGS(INFO) << "G3 BLE Cancel Connect.";
- if (server_socket_ != nullptr) server_socket_->Close();
- });
-
- BlePeripheral peripheral = static_cast<BlePeripheral&>(remote_peripheral);
- auto socket = std::make_unique<BleSocket>(&peripheral);
- // Finally, Request to connect to this socket.
- if (!remote_server_socket->Connect(*socket)) {
- NEARBY_LOGS(ERROR) << "G3 Ble Connect: Failed to connect to existing Ble "
- "Server socket: service_id="
- << service_id;
- return {};
- }
-
- NEARBY_LOG(INFO, "G3 Ble Connect: connected: socket=%p", socket.get());
- return socket;
-}
-
-} // namespace g3
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/g3/ble.h b/chromium/third_party/nearby/src/cpp/platform/impl/g3/ble.h
deleted file mode 100644
index 95954445b0e..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/g3/ble.h
+++ /dev/null
@@ -1,228 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_G3_BLE_H_
-#define PLATFORM_IMPL_G3_BLE_H_
-
-#include <memory>
-#include <string>
-
-#include "absl/container/flat_hash_map.h"
-#include "absl/container/flat_hash_set.h"
-#include "absl/strings/escaping.h"
-#include "absl/synchronization/mutex.h"
-#include "platform/api/ble.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/input_stream.h"
-#include "platform/base/output_stream.h"
-#include "platform/impl/g3/bluetooth_adapter.h"
-#include "platform/impl/g3/bluetooth_classic.h"
-#include "platform/impl/g3/multi_thread_executor.h"
-#include "platform/impl/g3/pipe.h"
-
-namespace location {
-namespace nearby {
-namespace g3 {
-
-class BleMedium;
-
-class BleSocket : public api::BleSocket {
- public:
- BleSocket() = default;
- explicit BleSocket(BlePeripheral* peripheral) : peripheral_(peripheral) {}
- ~BleSocket() override;
-
- // Connect to another BleSocket, to form a functional low-level channel.
- // from this point on, and until Close is called, connection exists.
- void Connect(BleSocket& other) ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns the InputStream of this connected BleSocket.
- InputStream& GetInputStream() override ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns the OutputStream of this connected BleSocket.
- // This stream is for local side to write.
- OutputStream& GetOutputStream() override ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns address of a remote BleSocket or nullptr.
- BleSocket* GetRemoteSocket() ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns true if connection exists to the (possibly closed) remote socket.
- bool IsConnected() const ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns true if socket is closed.
- bool IsClosed() const ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns Exception::kIo on error, Exception::kSuccess otherwise.
- Exception Close() override ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns valid BlePeripheral pointer if there is a connection, and
- // nullptr otherwise.
- BlePeripheral* GetRemotePeripheral() override ABSL_LOCKS_EXCLUDED(mutex_);
-
- private:
- void DoClose() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Returns true if connection exists to the (possibly closed) remote socket.
- bool IsConnectedLocked() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Returns InputStream of our side of a connection.
- // This is what the remote side is supposed to read from.
- // This is a helper for GetInputStream() method.
- InputStream& GetLocalInputStream() ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns OutputStream of our side of a connection.
- // This is what the local size is supposed to write to.
- // This is a helper for GetOutputStream() method.
- OutputStream& GetLocalOutputStream() ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Output pipe is initialized by constructor, it remains always valid, until
- // it is closed. it represents output part of a local socket. Input part of a
- // local socket comes from the peer socket, after connection.
- std::shared_ptr<Pipe> output_{new Pipe};
- std::shared_ptr<Pipe> input_;
- mutable absl::Mutex mutex_;
- BlePeripheral* peripheral_;
- BleSocket* remote_socket_ ABSL_GUARDED_BY(mutex_) = nullptr;
- bool closed_ ABSL_GUARDED_BY(mutex_) = false;
-};
-
-class BleServerSocket {
- public:
- ~BleServerSocket();
-
- // Blocks until either:
- // - at least one incoming connection request is available, or
- // - ServerSocket is closed.
- // On success, returns connected socket, ready to exchange data.
- // Returns nullptr on error.
- // Once error is reported, it is permanent, and ServerSocket has to be closed.
- //
- // Called by the server side of a connection.
- // Returns BleSocket to the server side.
- // If not null, returned socket is connected to its remote (client-side) peer.
- std::unique_ptr<api::BleSocket> Accept(BlePeripheral* peripheral)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Blocks until either:
- // - connection is available, or
- // - server socket is closed, or
- // - error happens.
- //
- // Called by the client side of a connection.
- // Returns true, if socket is successfully connected.
- bool Connect(BleSocket& socket) ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Called by the server side of a connection before passing ownership of
- // BleServerSocker to user, to track validity of a pointer to this
- // server socket,
- void SetCloseNotifier(std::function<void()> notifier)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns Exception::kIo on error, Exception::kSuccess otherwise.
- // Calls close_notifier if it was previously set, and marks socket as closed.
- Exception Close() ABSL_LOCKS_EXCLUDED(mutex_);
-
- private:
- Exception DoClose() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- absl::Mutex mutex_;
- absl::CondVar cond_;
- absl::flat_hash_set<BleSocket*> pending_sockets_ ABSL_GUARDED_BY(mutex_);
- std::function<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
- bool closed_ ABSL_GUARDED_BY(mutex_) = false;
-};
-
-// Container of operations that can be performed over the BLE medium.
-class BleMedium : public api::BleMedium {
- public:
- explicit BleMedium(api::BluetoothAdapter& adapter);
- ~BleMedium() override;
-
- // Returns true once the Ble advertising has been initiated.
- bool StartAdvertising(
- const std::string& service_id, const ByteArray& advertisement_bytes,
- const std::string& fast_advertisement_service_uuid) override
- ABSL_LOCKS_EXCLUDED(mutex_);
- bool StopAdvertising(const std::string& service_id) override
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns true once the Ble scanning has been initiated.
- bool StartScanning(const std::string& service_id,
- const std::string& fast_advertisement_service_uuid,
- DiscoveredPeripheralCallback callback) override
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns true once Ble scanning for service_id is well and truly
- // stopped; after this returns, there must be no more invocations of the
- // DiscoveredPeripheralCallback passed in to StartScanning() for service_id.
- bool StopScanning(const std::string& service_id) override
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns true once Ble socket connection requests to service_id can be
- // accepted.
- bool StartAcceptingConnections(const std::string& service_id,
- AcceptedConnectionCallback callback) override
- ABSL_LOCKS_EXCLUDED(mutex_);
- bool StopAcceptingConnections(const std::string& service_id) override
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Connects to existing remote Ble peripheral.
- //
- // On success, returns a new BleSocket.
- // On error, returns nullptr.
- std::unique_ptr<api::BleSocket> Connect(
- api::BlePeripheral& remote_peripheral, const std::string& service_id,
- CancellationFlag* cancellation_flag) override ABSL_LOCKS_EXCLUDED(mutex_);
-
- BluetoothAdapter& GetAdapter() { return *adapter_; }
-
- private:
- static constexpr int kMaxConcurrentAcceptLoops = 5;
-
- struct AdvertisingInfo {
- bool Empty() const { return service_id.empty(); }
- void Clear() { service_id.clear(); }
-
- std::string service_id;
- };
-
- struct ScanningInfo {
- bool Empty() const { return service_id.empty(); }
- void Clear() { service_id.clear(); }
-
- std::string service_id;
- };
-
- absl::Mutex mutex_;
- BluetoothAdapter* adapter_; // Our device adapter; read-only.
-
- // A thread pool dedicated to running all the accept loops from
- // StartAdvertising().
- MultiThreadExecutor accept_loops_runner_{kMaxConcurrentAcceptLoops};
- std::atomic_bool acceptance_thread_running_ = false;
-
- // A thread pool dedicated to wait to complete the accept_loops_runner_.
- MultiThreadExecutor close_accept_loops_runner_{kMaxConcurrentAcceptLoops};
-
- // A server socket is established when start advertising.
- std::unique_ptr<BleServerSocket> server_socket_;
- AdvertisingInfo advertising_info_ ABSL_GUARDED_BY(mutex_);
- ScanningInfo scanning_info_ ABSL_GUARDED_BY(mutex_);
-};
-
-} // namespace g3
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_G3_BLE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/g3/bluetooth_adapter.cc b/chromium/third_party/nearby/src/cpp/platform/impl/g3/bluetooth_adapter.cc
deleted file mode 100644
index ff526d5268f..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/g3/bluetooth_adapter.cc
+++ /dev/null
@@ -1,135 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/g3/bluetooth_adapter.h"
-
-#include <string>
-
-#include "platform/base/medium_environment.h"
-#include "platform/base/prng.h"
-#include "platform/impl/g3/bluetooth_classic.h"
-
-namespace location {
-namespace nearby {
-namespace g3 {
-
-BlePeripheral::BlePeripheral(BluetoothAdapter* adapter) : adapter_(*adapter) {}
-
-std::string BlePeripheral::GetName() const { return adapter_.GetName(); }
-
-ByteArray BlePeripheral::GetAdvertisementBytes(
- const std::string& service_id) const {
- return advertisement_bytes_;
-}
-
-void BlePeripheral::SetAdvertisementBytes(
- const std::string& service_id, const ByteArray& advertisement_bytes) {
- advertisement_bytes_ = advertisement_bytes;
-}
-
-BluetoothDevice::BluetoothDevice(BluetoothAdapter* adapter)
- : adapter_(*adapter) {}
-
-std::string BluetoothDevice::GetName() const { return adapter_.GetName(); }
-std::string BluetoothDevice::GetMacAddress() const {
- return adapter_.GetMacAddress();
-}
-
-BluetoothAdapter::BluetoothAdapter() {
- std::string mac_address;
- mac_address.resize(6);
- int64_t raw_mac_addr = Prng().NextInt64();
- mac_address[0] = static_cast<char>(raw_mac_addr >> 40);
- mac_address[1] = static_cast<char>(raw_mac_addr >> 32);
- mac_address[2] = static_cast<char>(raw_mac_addr >> 24);
- mac_address[3] = static_cast<char>(raw_mac_addr >> 16);
- mac_address[4] = static_cast<char>(raw_mac_addr >> 8);
- mac_address[5] = static_cast<char>(raw_mac_addr >> 0);
- SetMacAddress(mac_address);
-}
-
-BluetoothAdapter::~BluetoothAdapter() { SetStatus(Status::kDisabled); }
-
-void BluetoothAdapter::SetBluetoothClassicMedium(
- api::BluetoothClassicMedium* medium) {
- bluetooth_classic_medium_ = medium;
-}
-
-void BluetoothAdapter::SetBleMedium(api::BleMedium* medium) {
- ble_medium_ = medium;
-}
-
-bool BluetoothAdapter::SetStatus(Status status) {
- BluetoothAdapter::ScanMode mode;
- bool enabled = status == Status::kEnabled;
- std::string name;
- {
- absl::MutexLock lock(&mutex_);
- enabled_ = enabled;
- name = name_;
- mode = mode_;
- }
- auto& env = MediumEnvironment::Instance();
- env.OnBluetoothAdapterChangedState(*this, device_, name, enabled, mode);
- return true;
-}
-
-bool BluetoothAdapter::IsEnabled() const {
- absl::MutexLock lock(&mutex_);
- return enabled_;
-}
-
-BluetoothAdapter::ScanMode BluetoothAdapter::GetScanMode() const {
- absl::MutexLock lock(&mutex_);
- return mode_;
-}
-
-bool BluetoothAdapter::SetScanMode(BluetoothAdapter::ScanMode mode) {
- bool enabled;
- std::string name;
- {
- absl::MutexLock lock(&mutex_);
- mode_ = mode;
- name = name_;
- enabled = enabled_;
- }
- auto& env = MediumEnvironment::Instance();
- env.OnBluetoothAdapterChangedState(*this, device_, std::move(name), enabled,
- mode);
- return true;
-}
-
-std::string BluetoothAdapter::GetName() const {
- absl::MutexLock lock(&mutex_);
- return name_;
-}
-
-bool BluetoothAdapter::SetName(absl::string_view name) {
- BluetoothAdapter::ScanMode mode;
- bool enabled;
- {
- absl::MutexLock lock(&mutex_);
- name_ = name;
- enabled = enabled_;
- mode = mode_;
- }
- auto& env = MediumEnvironment::Instance();
- env.OnBluetoothAdapterChangedState(*this, device_, std::string(name), enabled,
- mode);
- return true;
-}
-
-} // namespace g3
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/g3/bluetooth_adapter.h b/chromium/third_party/nearby/src/cpp/platform/impl/g3/bluetooth_adapter.h
deleted file mode 100644
index e95333bf739..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/g3/bluetooth_adapter.h
+++ /dev/null
@@ -1,142 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_G3_BLUETOOTH_ADAPTER_H_
-#define PLATFORM_IMPL_G3_BLUETOOTH_ADAPTER_H_
-
-#include <string>
-
-#include "absl/base/thread_annotations.h"
-#include "absl/strings/string_view.h"
-#include "absl/synchronization/mutex.h"
-#include "platform/api/ble.h"
-#include "platform/api/bluetooth_adapter.h"
-#include "platform/api/bluetooth_classic.h"
-#include "platform/impl/g3/single_thread_executor.h"
-
-namespace location {
-namespace nearby {
-namespace g3 {
-
-// BluetoothDevice and BluetoothAdapter have a mutual dependency.
-class BluetoothAdapter;
-
-// Opaque wrapper over a Ble peripheral. Must contain enough data about a
-// particular Ble device to connect to its GATT server.
-class BlePeripheral : public api::BlePeripheral {
- public:
- ~BlePeripheral() override = default;
-
- std::string GetName() const override;
- ByteArray GetAdvertisementBytes(const std::string& service_id) const override;
- void SetAdvertisementBytes(const std::string& service_id,
- const ByteArray& advertisement_bytes);
- BluetoothAdapter& GetAdapter() { return adapter_; }
-
- private:
- // Only BluetoothAdapter may instantiate BlePeripheral.
- friend class BluetoothAdapter;
-
- explicit BlePeripheral(BluetoothAdapter* adapter);
-
- BluetoothAdapter& adapter_;
- ByteArray advertisement_bytes_;
-};
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html.
-class BluetoothDevice : public api::BluetoothDevice {
- public:
- ~BluetoothDevice() override = default;
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#getName()
- std::string GetName() const override;
- std::string GetMacAddress() const override;
- BluetoothAdapter& GetAdapter() { return adapter_; }
-
- private:
- // Only BluetoothAdapter may instantiate BluetoothDevice.
- friend class BluetoothAdapter;
-
- explicit BluetoothDevice(BluetoothAdapter* adapter);
-
- BluetoothAdapter& adapter_;
-};
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html
-class BluetoothAdapter : public api::BluetoothAdapter {
- public:
- using Status = api::BluetoothAdapter::Status;
- using ScanMode = api::BluetoothAdapter::ScanMode;
-
- BluetoothAdapter();
- ~BluetoothAdapter() override;
-
- // Synchronously sets the status of the BluetoothAdapter to 'status', and
- // returns true if the operation was a success.
- bool SetStatus(Status status) override ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns true if the BluetoothAdapter's current status is
- // Status::Value::kEnabled.
- bool IsEnabled() const override ABSL_LOCKS_EXCLUDED(mutex_);
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getScanMode()
- //
- // Returns ScanMode::kUnknown on error.
- ScanMode GetScanMode() const override ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Synchronously sets the scan mode of the adapter, and returns true if the
- // operation was a success.
- bool SetScanMode(ScanMode mode) override ABSL_LOCKS_EXCLUDED(mutex_);
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getName()
- // Returns an empty string on error
- std::string GetName() const override ABSL_LOCKS_EXCLUDED(mutex_);
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#setName(java.lang.String)
- bool SetName(absl::string_view name) override ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns BT MAC address assigned to this adapter.
- std::string GetMacAddress() const override { return mac_address_; }
-
- BluetoothDevice& GetDevice() { return device_; }
-
- void SetBluetoothClassicMedium(api::BluetoothClassicMedium* medium);
- api::BluetoothClassicMedium* GetBluetoothClassicMedium() {
- return bluetooth_classic_medium_;
- }
-
- BlePeripheral& GetPeripheral() { return peripheral_; }
-
- void SetBleMedium(api::BleMedium* medium);
- api::BleMedium* GetBleMedium() { return ble_medium_; }
-
- void SetMacAddress(std::string& mac_address) { mac_address_ = mac_address; }
-
- private:
- mutable absl::Mutex mutex_;
- BluetoothDevice device_{this};
- BlePeripheral peripheral_{this};
- api::BluetoothClassicMedium* bluetooth_classic_medium_ = nullptr;
- api::BleMedium* ble_medium_ = nullptr;
- std::string mac_address_;
- ScanMode mode_ ABSL_GUARDED_BY(mutex_) = ScanMode::kNone;
- std::string name_ ABSL_GUARDED_BY(mutex_) = "unknown G3 BT device";
- bool enabled_ ABSL_GUARDED_BY(mutex_) = false;
-};
-
-} // namespace g3
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_G3_BLUETOOTH_ADAPTER_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/g3/bluetooth_classic.cc b/chromium/third_party/nearby/src/cpp/platform/impl/g3/bluetooth_classic.cc
deleted file mode 100644
index 831848669c5..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/g3/bluetooth_classic.cc
+++ /dev/null
@@ -1,278 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/g3/bluetooth_classic.h"
-
-#include <memory>
-#include <string>
-
-#include "absl/synchronization/mutex.h"
-#include "platform/api/bluetooth_classic.h"
-#include "platform/base/cancellation_flag_listener.h"
-#include "platform/base/logging.h"
-#include "platform/base/medium_environment.h"
-#include "platform/impl/g3/bluetooth_adapter.h"
-
-namespace location {
-namespace nearby {
-namespace g3 {
-
-BluetoothSocket::~BluetoothSocket() {
- absl::MutexLock lock(&mutex_);
- DoClose();
-}
-
-void BluetoothSocket::Connect(BluetoothSocket& other) {
- absl::MutexLock lock(&mutex_);
- remote_socket_ = &other;
- input_ = other.output_;
-}
-
-bool BluetoothSocket::IsConnected() const {
- absl::MutexLock lock(&mutex_);
- return IsConnectedLocked();
-}
-
-bool BluetoothSocket::IsClosed() const {
- absl::MutexLock lock(&mutex_);
- return closed_;
-}
-
-bool BluetoothSocket::IsConnectedLocked() const { return input_ != nullptr; }
-
-InputStream& BluetoothSocket::GetInputStream() {
- auto* remote_socket = GetRemoteSocket();
- CHECK(remote_socket != nullptr);
- return remote_socket->GetLocalInputStream();
-}
-
-OutputStream& BluetoothSocket::GetOutputStream() {
- return GetLocalOutputStream();
-}
-
-InputStream& BluetoothSocket::GetLocalInputStream() {
- absl::MutexLock lock(&mutex_);
- return output_->GetInputStream();
-}
-
-OutputStream& BluetoothSocket::GetLocalOutputStream() {
- absl::MutexLock lock(&mutex_);
- return output_->GetOutputStream();
-}
-
-Exception BluetoothSocket::Close() {
- absl::MutexLock lock(&mutex_);
- DoClose();
- return {Exception::kSuccess};
-}
-
-void BluetoothSocket::DoClose() {
- if (!closed_) {
- remote_socket_ = nullptr;
- output_->GetOutputStream().Close();
- output_->GetInputStream().Close();
- input_->GetOutputStream().Close();
- input_->GetInputStream().Close();
- closed_ = true;
- }
-}
-
-BluetoothSocket* BluetoothSocket::GetRemoteSocket() {
- absl::MutexLock lock(&mutex_);
- return remote_socket_;
-}
-
-BluetoothDevice* BluetoothSocket::GetRemoteDevice() {
- BluetoothAdapter* remote_adapter = nullptr;
- {
- absl::MutexLock lock(&mutex_);
- if (remote_socket_ == nullptr || remote_socket_->adapter_ == nullptr) {
- return nullptr;
- }
- remote_adapter = remote_socket_->adapter_;
- }
- return remote_adapter ? &remote_adapter->GetDevice() : nullptr;
-}
-
-std::unique_ptr<api::BluetoothSocket> BluetoothServerSocket::Accept() {
- absl::MutexLock lock(&mutex_);
- while (!closed_ && pending_sockets_.empty()) {
- cond_.Wait(&mutex_);
- }
- // whether or not we were running in the wait loop, return early if closed.
- if (closed_) return {};
- auto* remote_socket =
- pending_sockets_.extract(pending_sockets_.begin()).value();
- CHECK(remote_socket);
- auto local_socket = std::make_unique<BluetoothSocket>(adapter_);
- local_socket->Connect(*remote_socket);
- remote_socket->Connect(*local_socket);
- cond_.SignalAll();
- return local_socket;
-}
-
-bool BluetoothServerSocket::Connect(BluetoothSocket& socket) {
- absl::MutexLock lock(&mutex_);
- if (closed_) return false;
- if (socket.IsConnected()) {
- NEARBY_LOGS(ERROR)
- << "Failed to connect to BT server socket: already connected";
- return true; // already connected.
- }
- // add client socket to the pending list
- pending_sockets_.emplace(&socket);
- cond_.SignalAll();
- while (!socket.IsConnected()) {
- cond_.Wait(&mutex_);
- if (closed_) return false;
- }
- return true;
-}
-
-void BluetoothServerSocket::SetCloseNotifier(std::function<void()> notifier) {
- absl::MutexLock lock(&mutex_);
- close_notifier_ = std::move(notifier);
-}
-
-BluetoothServerSocket::~BluetoothServerSocket() {
- absl::MutexLock lock(&mutex_);
- DoClose();
-}
-
-Exception BluetoothServerSocket::Close() {
- absl::MutexLock lock(&mutex_);
- return DoClose();
-}
-
-Exception BluetoothServerSocket::DoClose() {
- bool should_notify = !closed_;
- closed_ = true;
- if (should_notify) {
- cond_.SignalAll();
- if (close_notifier_) {
- auto notifier = std::move(close_notifier_);
- mutex_.Unlock();
- // Notifier may contain calls to public API, and may cause deadlock, if
- // mutex_ is held during the call.
- notifier();
- mutex_.Lock();
- }
- }
- return {Exception::kSuccess};
-}
-
-BluetoothClassicMedium::BluetoothClassicMedium(api::BluetoothAdapter& adapter)
- // TODO(apolyudov): implement and use downcast<> with static assertions.
- : adapter_(static_cast<BluetoothAdapter*>(&adapter)) {
- adapter_->SetBluetoothClassicMedium(this);
- auto& env = MediumEnvironment::Instance();
- env.RegisterBluetoothMedium(*this, GetAdapter());
-}
-
-BluetoothClassicMedium::~BluetoothClassicMedium() {
- adapter_->SetBluetoothClassicMedium(nullptr);
- auto& env = MediumEnvironment::Instance();
- env.UnregisterBluetoothMedium(*this);
-}
-
-bool BluetoothClassicMedium::StartDiscovery(DiscoveryCallback callback) {
- auto& env = MediumEnvironment::Instance();
- env.UpdateBluetoothMedium(*this, std::move(callback));
- return true;
-}
-
-bool BluetoothClassicMedium::StopDiscovery() {
- auto& env = MediumEnvironment::Instance();
- env.UpdateBluetoothMedium(*this, {});
- return true;
-}
-
-std::unique_ptr<api::BluetoothSocket> BluetoothClassicMedium::ConnectToService(
- api::BluetoothDevice& remote_device, const std::string& service_uuid,
- CancellationFlag* cancellation_flag) {
- NEARBY_LOGS(INFO) << "G3 ConnectToService [self]: medium=" << this
- << ", adapter=" << &GetAdapter()
- << ", device=" << &GetAdapter().GetDevice();
- // First, find an instance of remote medium, that exposed this device.
- auto& adapter = static_cast<BluetoothDevice&>(remote_device).GetAdapter();
- auto* medium =
- static_cast<BluetoothClassicMedium*>(adapter.GetBluetoothClassicMedium());
-
- if (!medium) return {}; // Adapter is not bound to medium. Bail out.
-
- BluetoothServerSocket* server_socket = nullptr;
- NEARBY_LOGS(INFO) << "G3 ConnectToService [peer]: medium=" << medium
- << ", adapter=" << &adapter << ", device=" << &remote_device
- << ", uuid=" << service_uuid.c_str();
- // Then, find our server socket context in this medium.
- {
- absl::MutexLock medium_lock(&medium->mutex_);
- auto item = medium->sockets_.find(service_uuid);
- server_socket = item != sockets_.end() ? item->second : nullptr;
- if (server_socket == nullptr) {
- NEARBY_LOGS(ERROR) << "Failed to find BT Server socket: uuid="
- << service_uuid;
- return {};
- }
- }
-
- if (cancellation_flag->Cancelled()) {
- NEARBY_LOGS(ERROR) << "G3 Bluetooth Connect: Has been cancelled: "
- "service_uuid="
- << service_uuid;
- return {};
- }
-
- CancellationFlagListener listener(cancellation_flag, [&server_socket]() {
- NEARBY_LOGS(INFO) << "G3 Bluetooth Cancel Connect.";
- if (server_socket != nullptr) server_socket->Close();
- });
-
- auto socket = std::make_unique<BluetoothSocket>(&GetAdapter());
- // Finally, Request to connect to this socket.
- if (!server_socket->Connect(*socket)) {
- NEARBY_LOGS(ERROR)
- << "Failed to connect to existing BT Server socket: uuid="
- << service_uuid;
- return {};
- }
- NEARBY_LOGS(INFO) << "G3 ConnectToService: connected: socket="
- << socket.get();
- return socket;
-}
-
-std::unique_ptr<api::BluetoothServerSocket>
-BluetoothClassicMedium::ListenForService(const std::string& service_name,
- const std::string& service_uuid) {
- auto socket = std::make_unique<BluetoothServerSocket>(GetAdapter());
- socket->SetCloseNotifier([this, uuid = service_uuid]() {
- absl::MutexLock lock(&mutex_);
- sockets_.erase(uuid);
- });
- NEARBY_LOGS(INFO) << "Adding service: medium=" << this
- << ", uuid=" << service_uuid;
- absl::MutexLock lock(&mutex_);
- sockets_.emplace(service_uuid, socket.get());
- return socket;
-}
-
-api::BluetoothDevice* BluetoothClassicMedium::GetRemoteDevice(
- const std::string& mac_address) {
- auto& env = MediumEnvironment::Instance();
- return env.FindBluetoothDevice(mac_address);
-}
-
-} // namespace g3
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/g3/bluetooth_classic.h b/chromium/third_party/nearby/src/cpp/platform/impl/g3/bluetooth_classic.h
deleted file mode 100644
index 9064547c8fe..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/g3/bluetooth_classic.h
+++ /dev/null
@@ -1,238 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_G3_BLUETOOTH_CLASSIC_H_
-#define PLATFORM_IMPL_G3_BLUETOOTH_CLASSIC_H_
-
-#include <memory>
-#include <string>
-
-#include "absl/container/flat_hash_map.h"
-#include "absl/container/flat_hash_set.h"
-#include "absl/synchronization/mutex.h"
-#include "platform/api/bluetooth_classic.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/exception.h"
-#include "platform/base/input_stream.h"
-#include "platform/base/listeners.h"
-#include "platform/base/output_stream.h"
-#include "platform/impl/g3/bluetooth_adapter.h"
-#include "platform/impl/g3/pipe.h"
-
-namespace location {
-namespace nearby {
-namespace g3 {
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html.
-class BluetoothSocket : public api::BluetoothSocket {
- public:
- BluetoothSocket() = default;
- explicit BluetoothSocket(BluetoothAdapter* adapter) : adapter_(adapter) {}
- ~BluetoothSocket() override;
-
- // Connects to another BluetoothSocket, to form a functional low-level
- // channel. From this point on, and until Close is called, connection exists.
- void Connect(BluetoothSocket& other);
-
- // NOTE:
- // It is an undefined behavior if GetInputStream() or GetOutputStream() is
- // called for a not-connected BluetoothSocket, i.e. any object that is not
- // returned by BluetoothClassicMedium::ConnectToService() for client side or
- // BluetoothServerSocket::Accept() for server side of connection.
-
- // Returns the InputStream of this connected BluetoothSocket.
- InputStream& GetInputStream() override;
-
- // Returns the OutputStream of this connected BluetoothSocket.
- // This stream is for local side to write.
- OutputStream& GetOutputStream() override;
-
- // Returns address of a remote BluetoothSocket or nullptr.
- BluetoothSocket* GetRemoteSocket() ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns true if connection exists to the (possibly closed) remote socket.
- bool IsConnected() const ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns true if socket is closed.
- bool IsClosed() const ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Closes both input and output streams, marks Socket as closed.
- // After this call object should be treated as not connected.
- // Returns Exception::kIo on error, Exception::kSuccess otherwise.
- Exception Close() override ABSL_LOCKS_EXCLUDED(mutex_);
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#getRemoteDevice()
- // Returns valid BluetoothDevice pointer if there is a connection, and
- // nullptr otherwise.
- BluetoothDevice* GetRemoteDevice() override ABSL_LOCKS_EXCLUDED(mutex_);
-
- private:
- void DoClose() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Returns true if connection exists to the (possibly closed) remote socket.
- bool IsConnectedLocked() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Returns InputStream of our side of a connection.
- // This is what the remote side is supposed to read from.
- // This is a helper for GetInputStream() method.
- InputStream& GetLocalInputStream() ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns OutputStream of our side of a connection.
- // This is what the local size is supposed to write to.
- // This is a helper for GetOutputStream() method.
- OutputStream& GetLocalOutputStream() ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Output pipe is initialized by constructor, it remains always valid, until
- // it is closed. it represents output part of a local socket. Input part of a
- // local socket comes from the peer socket, after connection.
- std::shared_ptr<Pipe> output_{new Pipe};
- std::shared_ptr<Pipe> input_;
- mutable absl::Mutex mutex_;
- BluetoothAdapter* adapter_ = nullptr; // Our Adapter. Read only.
- BluetoothSocket* remote_socket_ ABSL_GUARDED_BY(mutex_) = nullptr;
- bool closed_ ABSL_GUARDED_BY(mutex_) = false;
-};
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html.
-class BluetoothServerSocket : public api::BluetoothServerSocket {
- public:
- explicit BluetoothServerSocket(BluetoothAdapter& adapter)
- : adapter_(&adapter) {}
- ~BluetoothServerSocket() override;
-
- // Blocks until either:
- // - at least one incoming connection request is available, or
- // - ServerSocket is closed.
- // On success, returns connected socket, ready to exchange data.
- // Returns nullptr on error.
- // Once error is reported, it is permanent, and ServerSocket has to be closed.
- //
- // Called by the server side of a connection.
- // Returns BluetoothSocket to the server side.
- // If not null, returned socket is connected to its remote (client-side) peer.
- std::unique_ptr<api::BluetoothSocket> Accept() override
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Blocks until either:
- // - connection is available, or
- // - server socket is closed, or
- // - error happens.
- //
- // Called by the client side of a connection.
- // socket is an initialized BluetoothSocket, associated with a client
- // BluetoothAdapter.
- // Returns true, if socket is successfully connected.
- bool Connect(BluetoothSocket& socket) ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Called by the server side of a connection before passing ownership of
- // BluetoothServerSocker to user, to track validity of a pointer to this
- // server socket,
- void SetCloseNotifier(std::function<void()> notifier)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns Exception::kIo on error, Exception::kSuccess otherwise.
- // Calls close_notifier if it was previously set, and marks socket as closed.
- Exception Close() override ABSL_LOCKS_EXCLUDED(mutex_);
-
- private:
- Exception DoClose() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- absl::Mutex mutex_;
- absl::CondVar cond_;
- BluetoothAdapter* adapter_ = nullptr; // Our Adapter. Read only.
- absl::flat_hash_set<BluetoothSocket*> pending_sockets_
- ABSL_GUARDED_BY(mutex_);
- std::function<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
- bool closed_ ABSL_GUARDED_BY(mutex_) = false;
-};
-
-// Container of operations that can be performed over the Bluetooth Classic
-// medium.
-class BluetoothClassicMedium : public api::BluetoothClassicMedium {
- public:
- explicit BluetoothClassicMedium(api::BluetoothAdapter& adapter);
- ~BluetoothClassicMedium() override;
-
- // NOTE(DiscoveryCallback):
- // BluetoothDevice is a proxy object created as a result of BT discovery.
- // Its lifetime spans between calls to device_discovered_cb and
- // device_lost_cb.
- // It is safe to use BluetoothDevice in device_discovered_cb() callback
- // and at any time afterwards, until device_lost_cb() is called.
- // It is not safe to use BluetoothDevice after returning from
- // device_lost_cb() callback.
- // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#startDiscovery()
- //
- // Returns true once the process of discovery has been initiated.
- bool StartDiscovery(DiscoveryCallback callback) override
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#cancelDiscovery()
- //
- // Returns true once discovery is well and truly stopped; after this returns,
- // there must be no more invocations of the DiscoveryCallback passed in to
- // StartDiscovery().
- bool StopDiscovery() override ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Connects to existing remote BT service.
- //
- // A combination of
- // https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#createInsecureRfcommSocketToServiceRecord
- // followed by
- // https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#connect().
- //
- // service_uuid is the canonical textual representation
- // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format) of a
- // type 3 name-based
- // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based))
- // UUID.
- //
- // On success, returns a new BluetoothSocket.
- // On error, returns nullptr.
- std::unique_ptr<api::BluetoothSocket> ConnectToService(
- api::BluetoothDevice& remote_device, const std::string& service_uuid,
- CancellationFlag* cancellation_flag) override ABSL_LOCKS_EXCLUDED(mutex_);
-
- BluetoothAdapter& GetAdapter() { return *adapter_; }
-
- // Creates BT service, and begins listening for remote attempts to connect.
- //
- // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#listenUsingInsecureRfcommWithServiceRecord
- //
- // service_uuid is the canonical textual representation
- // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format) of a
- // type 3 name-based
- // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based))
- // UUID.
- //
- // Returns nullptr on error.
- std::unique_ptr<api::BluetoothServerSocket> ListenForService(
- const std::string& service_name, const std::string& service_uuid) override
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- api::BluetoothDevice* GetRemoteDevice(
- const std::string& mac_address) override;
-
- private:
- absl::Mutex mutex_;
- BluetoothAdapter* adapter_; // Our device adapter; read-only.
- absl::flat_hash_map<std::string, BluetoothServerSocket*> sockets_
- ABSL_GUARDED_BY(mutex_);
-};
-
-} // namespace g3
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_G3_BLUETOOTH_CLASSIC_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/g3/condition_variable.h b/chromium/third_party/nearby/src/cpp/platform/impl/g3/condition_variable.h
deleted file mode 100644
index a888a107d7d..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/g3/condition_variable.h
+++ /dev/null
@@ -1,51 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_G3_CONDITION_VARIABLE_H_
-#define PLATFORM_IMPL_G3_CONDITION_VARIABLE_H_
-
-#include "absl/synchronization/mutex.h"
-#include "platform/api/condition_variable.h"
-#include "platform/base/exception.h"
-#include "platform/impl/g3/mutex.h"
-
-namespace location {
-namespace nearby {
-namespace g3 {
-
-class ConditionVariable : public api::ConditionVariable {
- public:
- explicit ConditionVariable(g3::Mutex* mutex) : mutex_(&mutex->mutex_) {}
- ~ConditionVariable() override = default;
-
- Exception Wait() override {
- cond_var_.Wait(mutex_);
- return {Exception::kSuccess};
- }
- Exception Wait(absl::Duration timeout) override {
- cond_var_.WaitWithTimeout(mutex_, timeout);
- return {Exception::kSuccess};
- }
- void Notify() override { cond_var_.SignalAll(); }
-
- private:
- absl::Mutex* mutex_;
- absl::CondVar cond_var_;
-};
-
-} // namespace g3
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_G3_CONDITION_VARIABLE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/g3/crypto.cc b/chromium/third_party/nearby/src/cpp/platform/impl/g3/crypto.cc
deleted file mode 100644
index a6e9ad203dd..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/g3/crypto.cc
+++ /dev/null
@@ -1,53 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/api/crypto.h"
-
-#include <cstdint>
-#include <string>
-
-#include "absl/strings/string_view.h"
-#include "platform/base/byte_array.h"
-#include "openssl/digest.h"
-
-namespace location {
-namespace nearby {
-
-// Initialize global crypto state.
-void Crypto::Init() {}
-
-static ByteArray Hash(absl::string_view input, const EVP_MD* algo) {
- unsigned int md_out_size = EVP_MAX_MD_SIZE;
- uint8_t digest_buffer[EVP_MAX_MD_SIZE];
- if (input.empty()) return {};
-
- if (!EVP_Digest(input.data(), input.size(), digest_buffer, &md_out_size, algo,
- nullptr))
- return {};
-
- return ByteArray{reinterpret_cast<char*>(digest_buffer), md_out_size};
-}
-
-// Return MD5 hash of input.
-ByteArray Crypto::Md5(absl::string_view input) {
- return Hash(input, EVP_md5());
-}
-
-// Return SHA256 hash of input.
-ByteArray Crypto::Sha256(absl::string_view input) {
- return Hash(input, EVP_sha256());
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/g3/log_message.cc b/chromium/third_party/nearby/src/cpp/platform/impl/g3/log_message.cc
deleted file mode 100644
index dd63c332d43..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/g3/log_message.cc
+++ /dev/null
@@ -1,74 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/g3/log_message.h"
-
-#include <algorithm>
-
-#include "base/stringprintf.h"
-
-namespace location {
-namespace nearby {
-namespace g3 {
-
-api::LogMessage::Severity g_min_log_severity = api::LogMessage::Severity::kInfo;
-
-inline absl::LogSeverity ConvertSeverity(api::LogMessage::Severity severity) {
- switch (severity) {
- // api::LogMessage::Severity kVerbose and kInfo is mapped to
- // absl::LogSeverity kInfo since absl::LogSeverity doesn't have kVerbose
- // level.
- case api::LogMessage::Severity::kVerbose:
- case api::LogMessage::Severity::kInfo:
- return absl::LogSeverity::kInfo;
- case api::LogMessage::Severity::kWarning:
- return absl::LogSeverity::kWarning;
- case api::LogMessage::Severity::kError:
- return absl::LogSeverity::kError;
- case api::LogMessage::Severity::kFatal:
- return absl::LogSeverity::kFatal;
- }
-}
-
-LogMessage::LogMessage(const char* file, int line, Severity severity)
- : log_streamer_(ConvertSeverity(severity), file, line) {}
-
-LogMessage::~LogMessage() = default;
-
-void LogMessage::Print(const char* format, ...) {
- va_list ap;
- va_start(ap, format);
- std::string result;
- StringAppendV(&result, format, ap);
- log_streamer_.stream() << result;
- va_end(ap);
-}
-
-std::ostream& LogMessage::Stream() { return log_streamer_.stream(); }
-
-} // namespace g3
-
-namespace api {
-
-void LogMessage::SetMinLogSeverity(Severity severity) {
- g3::g_min_log_severity = severity;
-}
-
-bool LogMessage::ShouldCreateLogMessage(Severity severity) {
- return severity >= g3::g_min_log_severity;
-}
-
-} // namespace api
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/g3/log_message.h b/chromium/third_party/nearby/src/cpp/platform/impl/g3/log_message.h
deleted file mode 100644
index 600f075fae8..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/g3/log_message.h
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_G3_LOG_MESSAGE_H_
-#define PLATFORM_IMPL_G3_LOG_MESSAGE_H_
-
-#include "base/check.h"
-#include "platform/api/log_message.h"
-
-namespace location {
-namespace nearby {
-namespace g3 {
-
-// See documentation in
-// cpp/platform/api/log_message.h
-class LogMessage : public api::LogMessage {
- public:
- LogMessage(const char* file, int line, Severity severity);
- ~LogMessage() override;
-
- void Print(const char* format, ...) override;
-
- std::ostream& Stream() override;
-
- private:
- absl::LogStreamer log_streamer_;
-};
-
-} // namespace g3
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_G3_LOG_MESSAGE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/g3/multi_thread_executor.h b/chromium/third_party/nearby/src/cpp/platform/impl/g3/multi_thread_executor.h
deleted file mode 100644
index 37373af1f42..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/g3/multi_thread_executor.h
+++ /dev/null
@@ -1,66 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_G3_MULTI_THREAD_EXECUTOR_H_
-#define PLATFORM_IMPL_G3_MULTI_THREAD_EXECUTOR_H_
-
-#include <atomic>
-
-#include "absl/time/clock.h"
-#include "platform/api/submittable_executor.h"
-#include "platform/impl/shared/count_down_latch.h"
-#include "thread/threadpool.h"
-
-namespace location {
-namespace nearby {
-namespace g3 {
-
-// An Executor that reuses a fixed number of threads operating off a shared
-// unbounded queue.
-class MultiThreadExecutor : public api::SubmittableExecutor {
- public:
- explicit MultiThreadExecutor(int max_parallelism)
- : thread_pool_(max_parallelism) {
- thread_pool_.StartWorkers();
- }
- void Execute(Runnable&& runnable) override {
- if (!shutdown_) {
- thread_pool_.Schedule(std::move(runnable));
- }
- }
- bool DoSubmit(Runnable&& runnable) override {
- if (shutdown_) return false;
- thread_pool_.Schedule(std::move(runnable));
- return true;
- }
- void Shutdown() override { DoShutdown(); }
- ~MultiThreadExecutor() override { DoShutdown(); }
-
- void ScheduleAfter(absl::Duration delay, Runnable&& runnable) {
- if (shutdown_) return;
- thread_pool_.ScheduleAt(absl::Now() + delay, std::move(runnable));
- }
- bool InShutdown() const { return shutdown_; }
-
- private:
- void DoShutdown() { shutdown_ = true; }
- std::atomic_bool shutdown_ = false;
- ThreadPool thread_pool_;
-};
-
-} // namespace g3
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_G3_MULTI_THREAD_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/g3/mutex.h b/chromium/third_party/nearby/src/cpp/platform/impl/g3/mutex.h
deleted file mode 100644
index 65108af300c..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/g3/mutex.h
+++ /dev/null
@@ -1,61 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_G3_MUTEX_H_
-#define PLATFORM_IMPL_G3_MUTEX_H_
-
-#include "absl/synchronization/mutex.h"
-#include "platform/api/mutex.h"
-#include "platform/impl/shared/posix_mutex.h"
-
-namespace location {
-namespace nearby {
-namespace g3 {
-
-class ABSL_LOCKABLE Mutex : public api::Mutex {
- public:
- explicit Mutex(bool check) : check_(check) {}
- ~Mutex() override = default;
- Mutex(Mutex&&) = delete;
- Mutex& operator=(Mutex&&) = delete;
- Mutex(const Mutex&) = delete;
- Mutex& operator=(const Mutex&) = delete;
-
- void Lock() ABSL_EXCLUSIVE_LOCK_FUNCTION() override {
- mutex_.Lock();
- if (!check_) mutex_.ForgetDeadlockInfo();
- }
- void Unlock() ABSL_UNLOCK_FUNCTION() override { mutex_.Unlock(); }
-
- private:
- friend class ConditionVariable;
- absl::Mutex mutex_;
- bool check_;
-};
-
-class ABSL_LOCKABLE RecursiveMutex : public posix::Mutex {
- public:
- ~RecursiveMutex() override = default;
- RecursiveMutex() = default;
- RecursiveMutex(RecursiveMutex&&) = delete;
- RecursiveMutex& operator=(RecursiveMutex&&) = delete;
- RecursiveMutex(const RecursiveMutex&) = delete;
- RecursiveMutex& operator=(const RecursiveMutex&) = delete;
-};
-
-} // namespace g3
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_G3_MUTEX_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/g3/pipe.h b/chromium/third_party/nearby/src/cpp/platform/impl/g3/pipe.h
deleted file mode 100644
index 6485fff364b..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/g3/pipe.h
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_G3_PIPE_H_
-#define PLATFORM_IMPL_G3_PIPE_H_
-
-#include <memory>
-
-#include "platform/base/base_pipe.h"
-#include "platform/impl/g3/condition_variable.h"
-#include "platform/impl/g3/mutex.h"
-
-namespace location {
-namespace nearby {
-namespace g3 {
-
-class Pipe : public BasePipe {
- public:
- Pipe() {
- auto mutex = std::make_unique<g3::Mutex>(/*check=*/true);
- auto cond = std::make_unique<g3::ConditionVariable>(mutex.get());
- Setup(std::move(mutex), std::move(cond));
- }
- ~Pipe() override = default;
- Pipe(Pipe&&) = delete;
- Pipe& operator=(Pipe&&) = delete;
-};
-
-} // namespace g3
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_G3_PIPE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/g3/platform.cc b/chromium/third_party/nearby/src/cpp/platform/impl/g3/platform.cc
deleted file mode 100644
index 470af01d8c9..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/g3/platform.cc
+++ /dev/null
@@ -1,172 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/api/platform.h"
-
-#include <atomic>
-#include <memory>
-
-#include "absl/base/integral_types.h"
-#include "absl/memory/memory.h"
-#include "absl/strings/str_cat.h"
-#include "absl/time/time.h"
-#include "platform/api/atomic_boolean.h"
-#include "platform/api/atomic_reference.h"
-#include "platform/api/ble_v2.h"
-#include "platform/api/bluetooth_adapter.h"
-#include "platform/api/bluetooth_classic.h"
-#include "platform/api/condition_variable.h"
-#include "platform/impl/shared/count_down_latch.h"
-#include "platform/api/log_message.h"
-#include "platform/api/mutex.h"
-#include "platform/api/scheduled_executor.h"
-#include "platform/api/server_sync.h"
-#include "platform/api/submittable_executor.h"
-#include "platform/api/webrtc.h"
-#include "platform/api/wifi.h"
-#include "platform/base/medium_environment.h"
-#include "platform/impl/g3/atomic_boolean.h"
-#include "platform/impl/g3/atomic_reference.h"
-#include "platform/impl/g3/ble.h"
-#include "platform/impl/g3/bluetooth_adapter.h"
-#include "platform/impl/g3/bluetooth_classic.h"
-#include "platform/impl/g3/condition_variable.h"
-#include "platform/impl/g3/log_message.h"
-#include "platform/impl/g3/multi_thread_executor.h"
-#include "platform/impl/g3/mutex.h"
-#include "platform/impl/g3/scheduled_executor.h"
-#include "platform/impl/g3/single_thread_executor.h"
-#include "platform/impl/g3/webrtc.h"
-#include "platform/impl/g3/wifi_lan.h"
-#include "platform/impl/shared/file.h"
-
-namespace location {
-namespace nearby {
-namespace api {
-
-namespace {
-std::string GetPayloadPath(PayloadId payload_id) {
- return absl::StrCat("/tmp/", payload_id);
-}
-} // namespace
-
-int GetCurrentTid() {
- const LiveThread* my = Thread_GetMyLiveThread();
- return LiveThread_Pthread_TID(my);
-}
-
-std::unique_ptr<SubmittableExecutor>
-ImplementationPlatform::CreateSingleThreadExecutor() {
- return absl::make_unique<g3::SingleThreadExecutor>();
-}
-
-std::unique_ptr<SubmittableExecutor>
-ImplementationPlatform::CreateMultiThreadExecutor(int max_concurrency) {
- return absl::make_unique<g3::MultiThreadExecutor>(max_concurrency);
-}
-
-std::unique_ptr<ScheduledExecutor>
-ImplementationPlatform::CreateScheduledExecutor() {
- return absl::make_unique<g3::ScheduledExecutor>();
-}
-
-std::unique_ptr<AtomicUint32> ImplementationPlatform::CreateAtomicUint32(
- std::uint32_t value) {
- return absl::make_unique<g3::AtomicUint32>(value);
-}
-
-std::unique_ptr<BluetoothAdapter>
-ImplementationPlatform::CreateBluetoothAdapter() {
- return absl::make_unique<g3::BluetoothAdapter>();
-}
-
-std::unique_ptr<CountDownLatch> ImplementationPlatform::CreateCountDownLatch(
- std::int32_t count) {
- return absl::make_unique<shared::CountDownLatch>(count);
-}
-
-std::unique_ptr<AtomicBoolean> ImplementationPlatform::CreateAtomicBoolean(
- bool initial_value) {
- return absl::make_unique<g3::AtomicBoolean>(initial_value);
-}
-
-std::unique_ptr<InputFile> ImplementationPlatform::CreateInputFile(
- PayloadId payload_id, std::int64_t total_size) {
- return absl::make_unique<shared::InputFile>(GetPayloadPath(payload_id),
- total_size);
-}
-
-std::unique_ptr<OutputFile> ImplementationPlatform::CreateOutputFile(
- PayloadId payload_id) {
- return absl::make_unique<shared::OutputFile>(GetPayloadPath(payload_id));
-}
-
-std::unique_ptr<LogMessage> ImplementationPlatform::CreateLogMessage(
- const char* file, int line, LogMessage::Severity severity) {
- return absl::make_unique<g3::LogMessage>(file, line, severity);
-}
-
-std::unique_ptr<BluetoothClassicMedium>
-ImplementationPlatform::CreateBluetoothClassicMedium(
- api::BluetoothAdapter& adapter) {
- return absl::make_unique<g3::BluetoothClassicMedium>(adapter);
-}
-
-std::unique_ptr<BleMedium> ImplementationPlatform::CreateBleMedium(
- api::BluetoothAdapter& adapter) {
- return absl::make_unique<g3::BleMedium>(adapter);
-}
-
-std::unique_ptr<ble_v2::BleMedium> ImplementationPlatform::CreateBleV2Medium(
- api::BluetoothAdapter& adapter) {
- return std::unique_ptr<ble_v2::BleMedium>();
-}
-
-std::unique_ptr<ServerSyncMedium>
-ImplementationPlatform::CreateServerSyncMedium() {
- return std::unique_ptr<ServerSyncMedium>(/*new ServerSyncMediumImpl()*/);
-}
-
-std::unique_ptr<WifiMedium> ImplementationPlatform::CreateWifiMedium() {
- return std::unique_ptr<WifiMedium>();
-}
-
-std::unique_ptr<WifiLanMedium> ImplementationPlatform::CreateWifiLanMedium() {
- return absl::make_unique<g3::WifiLanMedium>();
-}
-
-std::unique_ptr<WebRtcMedium> ImplementationPlatform::CreateWebRtcMedium() {
- if (MediumEnvironment::Instance().GetEnvironmentConfig().webrtc_enabled) {
- return absl::make_unique<g3::WebRtcMedium>();
- } else {
- return nullptr;
- }
-}
-
-std::unique_ptr<Mutex> ImplementationPlatform::CreateMutex(Mutex::Mode mode) {
- if (mode == Mutex::Mode::kRecursive)
- return absl::make_unique<g3::RecursiveMutex>();
- else
- return absl::make_unique<g3::Mutex>(mode == Mutex::Mode::kRegular);
-}
-
-std::unique_ptr<ConditionVariable>
-ImplementationPlatform::CreateConditionVariable(Mutex* mutex) {
- return std::unique_ptr<ConditionVariable>(
- new g3::ConditionVariable(static_cast<g3::Mutex*>(mutex)));
-}
-
-} // namespace api
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/g3/scheduled_executor.cc b/chromium/third_party/nearby/src/cpp/platform/impl/g3/scheduled_executor.cc
deleted file mode 100644
index 8f1828faa11..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/g3/scheduled_executor.cc
+++ /dev/null
@@ -1,79 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/g3/scheduled_executor.h"
-
-#include <atomic>
-#include <memory>
-
-#include "absl/time/clock.h"
-#include "platform/api/cancelable.h"
-#include "platform/base/runnable.h"
-
-namespace location {
-namespace nearby {
-namespace g3 {
-
-namespace {
-
-class ScheduledCancelable : public api::Cancelable {
- public:
- bool Cancel() override {
- Status expected = kNotRun;
- while (expected == kNotRun) {
- if (status_.compare_exchange_strong(expected, kCanceled)) {
- return true;
- }
- }
- return false;
- }
- bool MarkExecuted() {
- Status expected = kNotRun;
- while (expected == kNotRun) {
- if (status_.compare_exchange_strong(expected, kExecuted)) {
- return true;
- }
- }
- return false;
- }
-
- private:
- enum Status {
- kNotRun,
- kExecuted,
- kCanceled,
- };
- std::atomic<Status> status_ = kNotRun;
-};
-
-} // namespace
-
-std::shared_ptr<api::Cancelable> ScheduledExecutor::Schedule(
- Runnable&& runnable, absl::Duration delay) {
- auto scheduled_cancelable = std::make_shared<ScheduledCancelable>();
- if (executor_.InShutdown()) {
- return scheduled_cancelable;
- }
- executor_.ScheduleAfter(
- delay, [this, scheduled_cancelable, runnable(std::move(runnable))]() {
- if (!executor_.InShutdown() && scheduled_cancelable->MarkExecuted()) {
- runnable();
- }
- });
- return scheduled_cancelable;
-}
-
-} // namespace g3
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/g3/scheduled_executor.h b/chromium/third_party/nearby/src/cpp/platform/impl/g3/scheduled_executor.h
deleted file mode 100644
index 7ffcf6c54fa..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/g3/scheduled_executor.h
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_G3_SCHEDULED_EXECUTOR_H_
-#define PLATFORM_IMPL_G3_SCHEDULED_EXECUTOR_H_
-
-#include <atomic>
-#include <memory>
-
-#include "absl/time/clock.h"
-#include "platform/api/cancelable.h"
-#include "platform/api/scheduled_executor.h"
-#include "platform/base/runnable.h"
-#include "platform/impl/g3/single_thread_executor.h"
-#include "thread/threadpool.h"
-
-namespace location {
-namespace nearby {
-namespace g3 {
-
-// An Executor that reuses a fixed number of threads operating off a shared
-// unbounded queue.
-class ScheduledExecutor final : public api::ScheduledExecutor {
- public:
- ScheduledExecutor() = default;
- ~ScheduledExecutor() override { executor_.Shutdown(); }
-
- void Execute(Runnable&& runnable) override {
- executor_.Execute(std::move(runnable));
- }
- std::shared_ptr<api::Cancelable> Schedule(Runnable&& runnable,
- absl::Duration delay) override;
- void Shutdown() override { executor_.Shutdown(); }
-
- private:
- SingleThreadExecutor executor_;
-};
-
-} // namespace g3
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_G3_SCHEDULED_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/g3/single_thread_executor.h b/chromium/third_party/nearby/src/cpp/platform/impl/g3/single_thread_executor.h
deleted file mode 100644
index 29ef3e87632..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/g3/single_thread_executor.h
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_G3_SINGLE_THREAD_EXECUTOR_H_
-#define PLATFORM_IMPL_G3_SINGLE_THREAD_EXECUTOR_H_
-
-#include "platform/impl/g3/multi_thread_executor.h"
-
-namespace location {
-namespace nearby {
-namespace g3 {
-
-// An Executor that uses a single worker thread operating off an unbounded
-// queue.
-class SingleThreadExecutor final : public MultiThreadExecutor {
- public:
- SingleThreadExecutor() : MultiThreadExecutor(1) {}
- ~SingleThreadExecutor() override = default;
-};
-
-} // namespace g3
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_G3_SINGLE_THREAD_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/g3/system_clock.cc b/chromium/third_party/nearby/src/cpp/platform/impl/g3/system_clock.cc
deleted file mode 100644
index cfa13a5ea74..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/g3/system_clock.cc
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/api/system_clock.h"
-
-#include "absl/time/clock.h"
-#include "platform/base/exception.h"
-
-namespace location {
-namespace nearby {
-
-absl::Time SystemClock::ElapsedRealtime() { return absl::Now(); }
-Exception SystemClock::Sleep(absl::Duration duration) {
- absl::SleepFor(duration);
- return {Exception::kSuccess};
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/g3/webrtc.cc b/chromium/third_party/nearby/src/cpp/platform/impl/g3/webrtc.cc
deleted file mode 100644
index 7394cd7eebd..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/g3/webrtc.cc
+++ /dev/null
@@ -1,96 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/g3/webrtc.h"
-
-#include <memory>
-
-#include "platform/base/medium_environment.h"
-#include "webrtc/api/task_queue/default_task_queue_factory.h"
-
-namespace location {
-namespace nearby {
-namespace g3 {
-
-WebRtcSignalingMessenger::WebRtcSignalingMessenger(
- absl::string_view self_id, const connections::LocationHint& location_hint)
- : self_id_(self_id), location_hint_(location_hint) {}
-
-bool WebRtcSignalingMessenger::SendMessage(absl::string_view peer_id,
- const ByteArray& message) {
- auto& env = MediumEnvironment::Instance();
- env.SendWebRtcSignalingMessage(peer_id, message);
- return true;
-}
-
-bool WebRtcSignalingMessenger::StartReceivingMessages(
- OnSignalingMessageCallback on_message_callback,
- OnSignalingCompleteCallback on_complete_callback) {
- auto& env = MediumEnvironment::Instance();
- env.RegisterWebRtcSignalingMessenger(self_id_, on_message_callback,
- on_complete_callback);
- return true;
-}
-
-void WebRtcSignalingMessenger::StopReceivingMessages() {
- auto& env = MediumEnvironment::Instance();
- env.UnregisterWebRtcSignalingMessenger(self_id_);
-}
-
-WebRtcMedium::~WebRtcMedium() { single_thread_executor_.Shutdown(); }
-
-const std::string WebRtcMedium::GetDefaultCountryCode() { return "US"; }
-
-void WebRtcMedium::CreatePeerConnection(
- webrtc::PeerConnectionObserver* observer, PeerConnectionCallback callback) {
- auto& env = MediumEnvironment::Instance();
- if (!env.GetUseValidPeerConnection()) {
- callback(nullptr);
- return;
- }
-
- webrtc::PeerConnectionInterface::RTCConfiguration rtc_config;
- webrtc::PeerConnectionDependencies dependencies(observer);
-
- std::unique_ptr<rtc::Thread> signaling_thread = rtc::Thread::Create();
- signaling_thread->SetName("signaling_thread", nullptr);
- RTC_CHECK(signaling_thread->Start()) << "Failed to start thread";
-
- webrtc::PeerConnectionFactoryDependencies factory_dependencies;
- factory_dependencies.task_queue_factory =
- webrtc::CreateDefaultTaskQueueFactory();
- factory_dependencies.signaling_thread = signaling_thread.release();
-
- rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection =
- webrtc::CreateModularPeerConnectionFactory(
- std::move(factory_dependencies))
- ->CreatePeerConnection(rtc_config, std::move(dependencies));
-
- single_thread_executor_.Execute(
- [&env, callback = std::move(callback),
- peer_connection = std::move(peer_connection)]() {
- absl::SleepFor(env.GetPeerConnectionLatency());
- callback(peer_connection);
- });
-}
-
-std::unique_ptr<api::WebRtcSignalingMessenger>
-WebRtcMedium::GetSignalingMessenger(
- absl::string_view self_id, const connections::LocationHint& location_hint) {
- return std::make_unique<WebRtcSignalingMessenger>(self_id, location_hint);
-}
-
-} // namespace g3
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/g3/webrtc.h b/chromium/third_party/nearby/src/cpp/platform/impl/g3/webrtc.h
deleted file mode 100644
index bacd0f51761..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/g3/webrtc.h
+++ /dev/null
@@ -1,81 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_G3_WEBRTC_H_
-#define PLATFORM_IMPL_G3_WEBRTC_H_
-
-#include <memory>
-
-#include "absl/strings/string_view.h"
-#include "platform/api/webrtc.h"
-#include "platform/impl/g3/single_thread_executor.h"
-#include "webrtc/api/peer_connection_interface.h"
-
-namespace location {
-namespace nearby {
-namespace g3 {
-
-class WebRtcSignalingMessenger : public api::WebRtcSignalingMessenger {
- public:
- using OnSignalingMessageCallback =
- api::WebRtcSignalingMessenger::OnSignalingMessageCallback;
- using OnSignalingCompleteCallback =
- api::WebRtcSignalingMessenger::OnSignalingCompleteCallback;
-
- explicit WebRtcSignalingMessenger(
- absl::string_view self_id,
- const connections::LocationHint& location_hint);
- ~WebRtcSignalingMessenger() override = default;
-
- bool SendMessage(absl::string_view peer_id,
- const ByteArray& message) override;
- bool StartReceivingMessages(
- OnSignalingMessageCallback on_message_callback,
- OnSignalingCompleteCallback on_complete_callback) override;
- void StopReceivingMessages() override;
-
- private:
- std::string self_id_;
- connections::LocationHint location_hint_;
-};
-
-class WebRtcMedium : public api::WebRtcMedium {
- public:
- using PeerConnectionCallback = api::WebRtcMedium::PeerConnectionCallback;
-
- WebRtcMedium() = default;
- ~WebRtcMedium() override;
-
- const std::string GetDefaultCountryCode() override;
-
- // Creates and returns a new webrtc::PeerConnectionInterface object via
- // |callback|.
- void CreatePeerConnection(webrtc::PeerConnectionObserver* observer,
- PeerConnectionCallback callback) override;
-
- // Returns a signaling messenger for sending WebRTC signaling messages.
- std::unique_ptr<api::WebRtcSignalingMessenger> GetSignalingMessenger(
- absl::string_view self_id,
- const connections::LocationHint& location_hint) override;
-
- private:
- // Executor for handling calls to create a peer connection.
- SingleThreadExecutor single_thread_executor_;
-};
-
-} // namespace g3
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_G3_WEBRTC_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/g3/wifi_lan.cc b/chromium/third_party/nearby/src/cpp/platform/impl/g3/wifi_lan.cc
deleted file mode 100644
index e2760365f72..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/g3/wifi_lan.cc
+++ /dev/null
@@ -1,371 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/g3/wifi_lan.h"
-
-#include <iostream>
-#include <memory>
-#include <string>
-#include <utility>
-
-#include "absl/strings/escaping.h"
-#include "absl/strings/str_format.h"
-#include "absl/synchronization/mutex.h"
-#include "platform/api/wifi_lan.h"
-#include "platform/base/cancellation_flag_listener.h"
-#include "platform/base/logging.h"
-#include "platform/base/medium_environment.h"
-#include "platform/base/nsd_service_info.h"
-
-namespace location {
-namespace nearby {
-namespace g3 {
-
-WifiLanSocket::~WifiLanSocket() {
- absl::MutexLock lock(&mutex_);
- DoClose();
-}
-
-void WifiLanSocket::Connect(WifiLanSocket& other) {
- absl::MutexLock lock(&mutex_);
- remote_socket_ = &other;
- input_ = other.output_;
-}
-
-InputStream& WifiLanSocket::GetInputStream() {
- auto* remote_socket = GetRemoteSocket();
- CHECK(remote_socket != nullptr);
- return remote_socket->GetLocalInputStream();
-}
-
-OutputStream& WifiLanSocket::GetOutputStream() {
- return GetLocalOutputStream();
-}
-
-WifiLanSocket* WifiLanSocket::GetRemoteSocket() {
- absl::MutexLock lock(&mutex_);
- return remote_socket_;
-}
-
-bool WifiLanSocket::IsConnected() const {
- absl::MutexLock lock(&mutex_);
- return IsConnectedLocked();
-}
-
-bool WifiLanSocket::IsClosed() const {
- absl::MutexLock lock(&mutex_);
- return closed_;
-}
-
-Exception WifiLanSocket::Close() {
- absl::MutexLock lock(&mutex_);
- DoClose();
- return {Exception::kSuccess};
-}
-
-void WifiLanSocket::DoClose() {
- if (!closed_) {
- remote_socket_ = nullptr;
- output_->GetOutputStream().Close();
- output_->GetInputStream().Close();
- input_->GetOutputStream().Close();
- input_->GetInputStream().Close();
- closed_ = true;
- }
-}
-
-bool WifiLanSocket::IsConnectedLocked() const { return input_ != nullptr; }
-
-InputStream& WifiLanSocket::GetLocalInputStream() {
- absl::MutexLock lock(&mutex_);
- return output_->GetInputStream();
-}
-
-OutputStream& WifiLanSocket::GetLocalOutputStream() {
- absl::MutexLock lock(&mutex_);
- return output_->GetOutputStream();
-}
-
-std::string WifiLanServerSocket::GetName(const std::string& ip_address,
- int port) {
- std::string dot_delimited_string;
- if (!ip_address.empty()) {
- for (auto byte : ip_address) {
- if (!dot_delimited_string.empty())
- absl::StrAppend(&dot_delimited_string, ".");
- absl::StrAppend(&dot_delimited_string, absl::StrFormat("%d", byte));
- }
- }
- std::string out = absl::StrCat(dot_delimited_string, ":", port);
- return out;
-}
-
-std::unique_ptr<api::WifiLanSocket> WifiLanServerSocket::Accept() {
- absl::MutexLock lock(&mutex_);
- while (!closed_ && pending_sockets_.empty()) {
- cond_.Wait(&mutex_);
- }
- // whether or not we were running in the wait loop, return early if closed.
- if (closed_) return {};
- auto* remote_socket =
- pending_sockets_.extract(pending_sockets_.begin()).value();
- CHECK(remote_socket);
-
- auto local_socket = std::make_unique<WifiLanSocket>();
- local_socket->Connect(*remote_socket);
- remote_socket->Connect(*local_socket);
- cond_.SignalAll();
- return local_socket;
-}
-
-bool WifiLanServerSocket::Connect(WifiLanSocket& socket) {
- absl::MutexLock lock(&mutex_);
- if (closed_) return false;
- if (socket.IsConnected()) {
- NEARBY_LOGS(ERROR)
- << "Failed to connect to WifiLan server socket: already connected";
- return true; // already connected.
- }
- // add client socket to the pending list
- pending_sockets_.insert(&socket);
- cond_.SignalAll();
- while (!socket.IsConnected()) {
- cond_.Wait(&mutex_);
- if (closed_) return false;
- }
- return true;
-}
-
-void WifiLanServerSocket::SetCloseNotifier(std::function<void()> notifier) {
- absl::MutexLock lock(&mutex_);
- close_notifier_ = std::move(notifier);
-}
-
-WifiLanServerSocket::~WifiLanServerSocket() {
- absl::MutexLock lock(&mutex_);
- DoClose();
-}
-
-Exception WifiLanServerSocket::Close() {
- absl::MutexLock lock(&mutex_);
- return DoClose();
-}
-
-Exception WifiLanServerSocket::DoClose() {
- bool should_notify = !closed_;
- closed_ = true;
- if (should_notify) {
- cond_.SignalAll();
- if (close_notifier_) {
- auto notifier = std::move(close_notifier_);
- mutex_.Unlock();
- // Notifier may contain calls to public API, and may cause deadlock, if
- // mutex_ is held during the call.
- notifier();
- mutex_.Lock();
- }
- }
- return {Exception::kSuccess};
-}
-
-WifiLanMedium::WifiLanMedium() {
- auto& env = MediumEnvironment::Instance();
- env.RegisterWifiLanMedium(*this);
-}
-
-WifiLanMedium::~WifiLanMedium() {
- auto& env = MediumEnvironment::Instance();
- env.UnregisterWifiLanMedium(*this);
-}
-
-bool WifiLanMedium::StartAdvertising(const NsdServiceInfo& nsd_service_info) {
- std::string service_type = nsd_service_info.GetServiceType();
- NEARBY_LOGS(INFO) << "G3 WifiLan StartAdvertising: nsd_service_info="
- << &nsd_service_info
- << ", service_name=" << nsd_service_info.GetServiceName()
- << ", service_type=" << service_type;
- {
- absl::MutexLock lock(&mutex_);
- if (advertising_info_.Existed(service_type)) {
- NEARBY_LOGS(INFO)
- << "G3 WifiLan StartAdvertising: Can't start advertising because "
- "service_type="
- << service_type << ", has started already.";
- return false;
- }
- }
- auto& env = MediumEnvironment::Instance();
- env.UpdateWifiLanMediumForAdvertising(*this, nsd_service_info,
- /*enabled=*/true);
- {
- absl::MutexLock lock(&mutex_);
- advertising_info_.Add(service_type);
- }
- return true;
-}
-
-bool WifiLanMedium::StopAdvertising(const NsdServiceInfo& nsd_service_info) {
- std::string service_type = nsd_service_info.GetServiceType();
- NEARBY_LOGS(INFO) << "G3 WifiLan StopAdvertising: nsd_service_info="
- << &nsd_service_info
- << ", service_name=" << nsd_service_info.GetServiceName()
- << ", service_type=" << service_type;
- {
- absl::MutexLock lock(&mutex_);
- if (!advertising_info_.Existed(service_type)) {
- NEARBY_LOGS(INFO)
- << "G3 WifiLan StopAdvertising: Can't stop advertising because "
- "we never started advertising for service_type="
- << service_type;
- return false;
- }
- advertising_info_.Remove(service_type);
- }
- auto& env = MediumEnvironment::Instance();
- env.UpdateWifiLanMediumForAdvertising(*this, nsd_service_info,
- /*enabled=*/false);
- return true;
-}
-
-bool WifiLanMedium::StartDiscovery(const std::string& service_type,
- DiscoveredServiceCallback callback) {
- NEARBY_LOGS(INFO) << "G3 WifiLan StartDiscovery: service_type="
- << service_type;
- {
- absl::MutexLock lock(&mutex_);
- if (discovering_info_.Existed(service_type)) {
- NEARBY_LOGS(INFO)
- << "G3 WifiLan StartDiscovery: Can't start discovery because "
- "service_type="
- << service_type << " has started already.";
- return false;
- }
- }
- auto& env = MediumEnvironment::Instance();
- env.UpdateWifiLanMediumForDiscovery(*this, std::move(callback), service_type,
- true);
- {
- absl::MutexLock lock(&mutex_);
- discovering_info_.Add(service_type);
- }
- return true;
-}
-
-bool WifiLanMedium::StopDiscovery(const std::string& service_type) {
- NEARBY_LOGS(INFO) << "G3 WifiLan StopDiscovery: service_type="
- << service_type;
- {
- absl::MutexLock lock(&mutex_);
- if (!discovering_info_.Existed(service_type)) {
- NEARBY_LOGS(INFO)
- << "G3 WifiLan StopDiscovery: Can't stop discovering because we "
- "never started discovering.";
- return false;
- }
- discovering_info_.Remove(service_type);
- }
- auto& env = MediumEnvironment::Instance();
- env.UpdateWifiLanMediumForDiscovery(*this, {}, service_type, false);
- return true;
-}
-
-std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
- const NsdServiceInfo& remote_service_info,
- CancellationFlag* cancellation_flag) {
- std::string service_type = remote_service_info.GetServiceType();
- NEARBY_LOGS(INFO) << "G3 WifiLan ConnectToService [self]: medium=" << this
- << ", service_type=" << service_type;
- return ConnectToService(remote_service_info.GetIPAddress(),
- remote_service_info.GetPort(), cancellation_flag);
-}
-
-std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
- const std::string& ip_address, int port,
- CancellationFlag* cancellation_flag) {
- std::string socket_name = WifiLanServerSocket::GetName(ip_address, port);
- NEARBY_LOGS(INFO) << "G3 WifiLan ConnectToService [self]: medium=" << this
- << ", ip address + port=" << socket_name;
- // First, find an instance of remote medium, that exposed this service.
- auto& env = MediumEnvironment::Instance();
- auto* remote_medium =
- static_cast<WifiLanMedium*>(env.GetWifiLanMedium(ip_address, port));
- if (!remote_medium) {
- return {};
- }
-
- WifiLanServerSocket* server_socket = nullptr;
- NEARBY_LOGS(INFO) << "G3 WifiLan ConnectToService [peer]: medium="
- << remote_medium
- << ", remote ip address + port=" << socket_name;
- // Then, find our server socket context in this medium.
- {
- absl::MutexLock medium_lock(&remote_medium->mutex_);
- auto item = remote_medium->server_sockets_.find(socket_name);
- server_socket = item != server_sockets_.end() ? item->second : nullptr;
- if (server_socket == nullptr) {
- NEARBY_LOGS(ERROR)
- << "G3 WifiLan Failed to find WifiLan Server socket: socket_name="
- << socket_name;
- return {};
- }
- }
-
- if (cancellation_flag->Cancelled()) {
- NEARBY_LOGS(ERROR) << "G3 WifiLan Connect: Has been cancelled: socket_name="
- << socket_name;
- return {};
- }
-
- CancellationFlagListener listener(cancellation_flag, [&server_socket]() {
- NEARBY_LOGS(INFO) << "G3 WifiLan Cancel Connect.";
- if (server_socket != nullptr) {
- server_socket->Close();
- }
- });
-
- auto socket = std::make_unique<WifiLanSocket>();
- // Finally, Request to connect to this socket.
- if (!server_socket->Connect(*socket)) {
- NEARBY_LOGS(ERROR) << "G3 WifiLan Failed to connect to existing WifiLan "
- "Server socket: name="
- << socket_name;
- return {};
- }
- NEARBY_LOGS(INFO) << "G3 WifiLan ConnectToService: connected: socket="
- << socket.get();
- return socket;
-}
-
-std::unique_ptr<api::WifiLanServerSocket> WifiLanMedium::ListenForService(
- int port) {
- auto& env = MediumEnvironment::Instance();
- auto server_socket = std::make_unique<WifiLanServerSocket>();
- server_socket->SetIPAddress(env.GetFakeIPAddress());
- server_socket->SetPort(port == 0 ? env.GetFakePort() : port);
- std::string socket_name = WifiLanServerSocket::GetName(
- server_socket->GetIPAddress(), server_socket->GetPort());
- server_socket->SetCloseNotifier([this, socket_name]() {
- absl::MutexLock lock(&mutex_);
- server_sockets_.erase(socket_name);
- });
- NEARBY_LOGS(INFO) << "G3 WifiLan Adding server socket: medium=" << this
- << ", socket_name=" << socket_name;
- absl::MutexLock lock(&mutex_);
- server_sockets_.insert({socket_name, server_socket.get()});
- return server_socket;
-}
-
-} // namespace g3
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/g3/wifi_lan.h b/chromium/third_party/nearby/src/cpp/platform/impl/g3/wifi_lan.h
deleted file mode 100644
index 8d95c6730bd..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/g3/wifi_lan.h
+++ /dev/null
@@ -1,279 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_G3_WIFI_LAN_H_
-#define PLATFORM_IMPL_G3_WIFI_LAN_H_
-
-#include <memory>
-#include <string>
-#include <utility>
-
-#include "absl/container/flat_hash_map.h"
-#include "absl/container/flat_hash_set.h"
-#include "absl/synchronization/mutex.h"
-#include "platform/api/wifi_lan.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/input_stream.h"
-#include "platform/base/nsd_service_info.h"
-#include "platform/base/output_stream.h"
-#include "platform/impl/g3/multi_thread_executor.h"
-#include "platform/impl/g3/pipe.h"
-
-namespace location {
-namespace nearby {
-namespace g3 {
-
-class WifiLanMedium;
-
-class WifiLanSocket : public api::WifiLanSocket {
- public:
- WifiLanSocket() = default;
- ~WifiLanSocket() override;
-
- // Connect to another WifiLanSocket, to form a functional low-level channel.
- // from this point on, and until Close is called, connection exists.
- void Connect(WifiLanSocket& other) ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns the InputStream of this connected WifiLanSocket.
- InputStream& GetInputStream() override ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns the OutputStream of this connected WifiLanSocket.
- // This stream is for local side to write.
- OutputStream& GetOutputStream() override ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns address of a remote WifiLanSocket or nullptr.
- WifiLanSocket* GetRemoteSocket() ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns true if connection exists to the (possibly closed) remote socket.
- bool IsConnected() const ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns true if socket is closed.
- bool IsClosed() const ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns Exception::kIo on error, Exception::kSuccess otherwise.
- Exception Close() override ABSL_LOCKS_EXCLUDED(mutex_);
-
- private:
- void DoClose() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Returns true if connection exists to the (possibly closed) remote socket.
- bool IsConnectedLocked() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- // Returns InputStream of our side of a connection.
- // This is what the remote side is supposed to read from.
- // This is a helper for GetInputStream() method.
- InputStream& GetLocalInputStream() ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns OutputStream of our side of a connection.
- // This is what the local size is supposed to write to.
- // This is a helper for GetOutputStream() method.
- OutputStream& GetLocalOutputStream() ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Output pipe is initialized by constructor, it remains always valid, until
- // it is closed. it represents output part of a local socket. Input part of a
- // local socket comes from the peer socket, after connection.
- std::shared_ptr<Pipe> output_{new Pipe};
- std::shared_ptr<Pipe> input_;
- mutable absl::Mutex mutex_;
- WifiLanSocket* remote_socket_ ABSL_GUARDED_BY(mutex_) = nullptr;
- bool closed_ ABSL_GUARDED_BY(mutex_) = false;
-};
-
-class WifiLanServerSocket : public api::WifiLanServerSocket {
- public:
- static std::string GetName(const std::string& ip_address, int port);
-
- ~WifiLanServerSocket() override;
-
- // Gets ip address.
- std::string GetIPAddress() const override ABSL_LOCKS_EXCLUDED(mutex_) {
- absl::MutexLock lock(&mutex_);
- return ip_address_;
- }
-
- // Sets the ip address.
- void SetIPAddress(const std::string& ip_address) ABSL_LOCKS_EXCLUDED(mutex_) {
- absl::MutexLock lock(&mutex_);
- ip_address_ = ip_address;
- }
-
- // Gets the port.
- int GetPort() const override ABSL_LOCKS_EXCLUDED(mutex_) {
- absl::MutexLock lock(&mutex_);
- return port_;
- }
-
- // Sets the port.
- void SetPort(int port) ABSL_LOCKS_EXCLUDED(mutex_) {
- absl::MutexLock lock(&mutex_);
- port_ = port;
- }
-
- // Blocks until either:
- // - at least one incoming connection request is available, or
- // - ServerSocket is closed.
- // On success, returns connected socket, ready to exchange data.
- // Returns nullptr on error.
- // Once error is reported, it is permanent, and ServerSocket has to be closed.
- //
- // Called by the server side of a connection.
- // Returns WifiLanSocket to the server side.
- // If not null, returned socket is connected to its remote (client-side) peer.
- std::unique_ptr<api::WifiLanSocket> Accept() override
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Blocks until either:
- // - connection is available, or
- // - server socket is closed, or
- // - error happens.
- //
- // Called by the client side of a connection.
- // Returns true, if socket is successfully connected.
- bool Connect(WifiLanSocket& socket) ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Called by the server side of a connection before passing ownership of
- // WifiLanServerSocker to user, to track validity of a pointer to this
- // server socket.
- void SetCloseNotifier(std::function<void()> notifier)
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Returns Exception::kIo on error, Exception::kSuccess otherwise.
- // Calls close_notifier if it was previously set, and marks socket as closed.
- Exception Close() override ABSL_LOCKS_EXCLUDED(mutex_);
-
- private:
- Exception DoClose() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
-
- mutable absl::Mutex mutex_;
- std::string ip_address_ ABSL_GUARDED_BY(mutex_);
- int port_ ABSL_GUARDED_BY(mutex_);
- absl::CondVar cond_;
- absl::flat_hash_set<WifiLanSocket*> pending_sockets_ ABSL_GUARDED_BY(mutex_);
- std::function<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
- bool closed_ ABSL_GUARDED_BY(mutex_) = false;
-};
-
-// Container of operations that can be performed over the WifiLan medium.
-class WifiLanMedium : public api::WifiLanMedium {
- public:
- WifiLanMedium();
- ~WifiLanMedium() override;
-
- // Starts WifiLan advertising.
- //
- // nsd_service_info - NsdServiceInfo data that's advertised through mDNS
- // service.
- // On success if the service is now advertising.
- // On error if the service cannot start to advertise or the service type in
- // NsdServiceInfo has been passed previously which StopAdvertising is not
- // been called.
- bool StartAdvertising(const NsdServiceInfo& nsd_service_info) override
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Stops WifiLan advertising.
- //
- // nsd_service_info - NsdServiceInfo data that's advertised through mDNS
- // service.
- // On success if the service stops advertising.
- // On error if the service cannot stop advertising or the service type in
- // NsdServiceInfo cannot be found.
- bool StopAdvertising(const NsdServiceInfo& nsd_service_info) override
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Starts the discovery of nearby WifiLan services.
- //
- // Returns true once the WifiLan discovery has been initiated. The
- // service_type is associated with callback.
- bool StartDiscovery(const std::string& service_type,
- DiscoveredServiceCallback callback) override
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Stops the discovery of nearby WifiLan services.
- //
- // service_type - The one assigend in StartDiscovery.
- // On success if service_type is matched to the callback and will be removed
- // from the list. If list is empty then stops the WifiLan discovery
- // service.
- // On error if the service_type is not existed, then return immediately.
- bool StopDiscovery(const std::string& service_type) override
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Connects to a WifiLan service.
- // On success, returns a new WifiLanSocket.
- // On error, returns nullptr.
- std::unique_ptr<api::WifiLanSocket> ConnectToService(
- const NsdServiceInfo& remote_service_info,
- CancellationFlag* cancellation_flag) override ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Connects to a WifiLan service by ip address and port.
- // On success, returns a new WifiLanSocket.
- // On error, returns nullptr.
- std::unique_ptr<api::WifiLanSocket> ConnectToService(
- const std::string& ip_address, int port,
- CancellationFlag* cancellation_flag) override ABSL_LOCKS_EXCLUDED(mutex_);
-
- // Listens for incoming connection.
- //
- // port - A port number.
- // 0 : use a random port.
- // 1~65536 : open a server socket on that exact port.
- // On success, returns a new WifiLanServerSocket.
- // On error, returns nullptr.
- std::unique_ptr<api::WifiLanServerSocket> ListenForService(int port) override
- ABSL_LOCKS_EXCLUDED(mutex_);
-
- private:
- struct AdvertisingInfo {
- bool Empty() const { return service_types.empty(); }
- void Clear() { service_types.clear(); }
- void Add(const std::string& service_type) {
- service_types.insert(service_type);
- }
- void Remove(const std::string& service_type) {
- service_types.erase(service_type);
- }
- bool Existed(const std::string& service_type) const {
- return service_types.contains(service_type);
- }
-
- absl::flat_hash_set<std::string> service_types;
- };
- struct DiscoveringInfo {
- bool Empty() const { return service_types.empty(); }
- void Clear() { service_types.clear(); }
- void Add(const std::string& service_type) {
- service_types.insert(service_type);
- }
- void Remove(const std::string& service_type) {
- service_types.erase(service_type);
- }
- bool Existed(const std::string& service_type) const {
- return service_types.contains(service_type);
- }
-
- absl::flat_hash_set<std::string> service_types;
- };
-
- absl::Mutex mutex_;
- AdvertisingInfo advertising_info_ ABSL_GUARDED_BY(mutex_);
- DiscoveringInfo discovering_info_ ABSL_GUARDED_BY(mutex_);
- absl::flat_hash_map<std::string, WifiLanServerSocket*> server_sockets_
- ABSL_GUARDED_BY(mutex_);
-};
-
-} // namespace g3
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_G3_WIFI_LAN_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/shared/BUILD b/chromium/third_party/nearby/src/cpp/platform/impl/shared/BUILD
deleted file mode 100644
index 71e588dcd31..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/shared/BUILD
+++ /dev/null
@@ -1,90 +0,0 @@
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# https://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-licenses(["notice"])
-
-cc_library(
- name = "posix_mutex",
- srcs = [
- "posix_mutex.cc",
- ],
- hdrs = [
- "posix_mutex.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- visibility = [
- "//platform/impl:__subpackages__",
- ],
- deps = ["//platform/api:types"],
-)
-
-cc_library(
- name = "posix_condition_variable",
- srcs = [
- "posix_condition_variable.cc",
- ],
- hdrs = [
- "posix_condition_variable.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- deps = [
- ":posix_mutex",
- "//platform/api:types",
- ],
-)
-
-cc_library(
- name = "file",
- srcs = ["file.cc"],
- hdrs = ["file.h"],
- compatible_with = ["//buildenv/target:non_prod"],
- visibility = [
- "//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
- "//platform/impl:__subpackages__",
- ],
- deps = [
- "//absl/strings",
- "//platform/api:types",
- "//platform/base",
- ],
-)
-
-cc_library(
- name = "count_down_latch",
- srcs = ["count_down_latch.cc"],
- hdrs = ["count_down_latch.h"],
- compatible_with = ["//buildenv/target:non_prod"],
- visibility = [
- "//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
- "//platform/impl:__subpackages__",
- ],
- deps = [
- "//absl/base:core_headers",
- "//absl/strings",
- "//absl/synchronization",
- "//absl/time",
- "//platform/api:types",
- ],
-)
-
-cc_test(
- name = "file_test",
- srcs = ["file_test.cc"],
- deps = [
- ":file",
- "//file/util:temp_path",
- "//testing/base/public:gunit_main",
- "//absl/strings",
- "//platform/base",
- ],
-)
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/shared/count_down_latch.cc b/chromium/third_party/nearby/src/cpp/platform/impl/shared/count_down_latch.cc
deleted file mode 100644
index f79971026a2..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/shared/count_down_latch.cc
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/shared/count_down_latch.h"
-
-namespace location {
-namespace nearby {
-namespace shared {
-
-// A synchronization aid that allows one or more threads to wait until a set of
-// operations being performed in other threads completes.
-//
-// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html
-CountDownLatch::CountDownLatch(int count) : count_(count) {}
-
-ExceptionOr<bool> CountDownLatch::Await(absl::Duration timeout) {
- absl::MutexLock lock(&mutex_);
- absl::Time deadline = absl::Now() + timeout;
- while (count_ > 0) {
- if (cond_.WaitWithDeadline(&mutex_, deadline)) {
- return ExceptionOr<bool>(false);
- }
- }
- return ExceptionOr<bool>(true);
-}
-
-Exception CountDownLatch::Await() {
- absl::MutexLock lock(&mutex_);
- while (count_ > 0) {
- cond_.Wait(&mutex_);
- }
- return {Exception::kSuccess};
-}
-void CountDownLatch::CountDown() {
- absl::MutexLock lock(&mutex_);
- if (count_ > 0 && --count_ == 0) {
- cond_.SignalAll();
- }
-}
-
-} // namespace shared
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/shared/count_down_latch.h b/chromium/third_party/nearby/src/cpp/platform/impl/shared/count_down_latch.h
deleted file mode 100644
index d52d3ad44ee..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/shared/count_down_latch.h
+++ /dev/null
@@ -1,53 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_SHARED_COUNT_DOWN_LATCH_H_
-#define PLATFORM_IMPL_SHARED_COUNT_DOWN_LATCH_H_
-
-#include "absl/base/thread_annotations.h"
-#include "absl/synchronization/mutex.h"
-#include "absl/time/clock.h"
-#include "platform/api/count_down_latch.h"
-
-namespace location {
-namespace nearby {
-namespace shared {
-
-// A synchronization aid that allows one or more threads to wait until a set of
-// operations being performed in other threads completes.
-//
-// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html
-class CountDownLatch final : public api::CountDownLatch {
- public:
- explicit CountDownLatch(int count);
- CountDownLatch(const CountDownLatch&) = delete;
- CountDownLatch& operator=(const CountDownLatch&) = delete;
- CountDownLatch(CountDownLatch&&) = delete;
- CountDownLatch& operator=(CountDownLatch&&) = delete;
- ExceptionOr<bool> Await(absl::Duration timeout) override;
- Exception Await() override;
- void CountDown() override;
-
- private:
- absl::Mutex mutex_; // Mutex to be used with cond_.Wait...() method family.
- absl::CondVar cond_; // Condition to synchronize up to N waiting threads.
- int count_
- ABSL_GUARDED_BY(mutex_); // When zero, latch should release all waiters.
-};
-
-} // namespace shared
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_G3_COUNT_DOWN_LATCH_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/shared/file.cc b/chromium/third_party/nearby/src/cpp/platform/impl/shared/file.cc
deleted file mode 100644
index cadbadb6084..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/shared/file.cc
+++ /dev/null
@@ -1,96 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/shared/file.h"
-
-#include <cstddef>
-#include <memory>
-
-#include "absl/strings/string_view.h"
-#include "platform/base/exception.h"
-
-namespace location {
-namespace nearby {
-namespace shared {
-
-// InputFile
-
-InputFile::InputFile(const std::string& path, std::int64_t size)
- : file_(path, std::ios::binary), path_(path), total_size_(size) {}
-
-ExceptionOr<ByteArray> InputFile::Read(std::int64_t size) {
- if (!file_.is_open()) {
- return ExceptionOr<ByteArray>{Exception::kIo};
- }
-
- if (file_.peek() == EOF) {
- return ExceptionOr<ByteArray>{ByteArray{}};
- }
-
- if (!file_.good()) {
- return ExceptionOr<ByteArray>{Exception::kIo};
- }
-
- ByteArray bytes(size);
- std::unique_ptr<char[]> read_bytes{new char[size]};
- file_.read(read_bytes.get(), static_cast<ptrdiff_t>(size));
- auto num_bytes_read = file_.gcount();
- if (num_bytes_read == 0) {
- return ExceptionOr<ByteArray>{Exception::kIo};
- }
-
- return ExceptionOr<ByteArray>(ByteArray(read_bytes.get(), num_bytes_read));
-}
-
-Exception InputFile::Close() {
- if (file_.is_open()) {
- file_.close();
- }
- return {Exception::kSuccess};
-}
-
-// OutputFile
-
-OutputFile::OutputFile(absl::string_view path)
- : file_(std::string(path), std::ios::binary) {}
-
-Exception OutputFile::Write(const ByteArray& data) {
- if (!file_.is_open()) {
- return {Exception::kIo};
- }
-
- if (!file_.good()) {
- return {Exception::kIo};
- }
-
- file_.write(data.data(), data.size());
- file_.flush();
- return {file_.good() ? Exception::kSuccess : Exception::kIo};
-}
-
-Exception OutputFile::Flush() {
- file_.flush();
- return {file_.good() ? Exception::kSuccess : Exception::kIo};
-}
-
-Exception OutputFile::Close() {
- if (file_.is_open()) {
- file_.close();
- }
- return {Exception::kSuccess};
-}
-
-} // namespace shared
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/shared/file.h b/chromium/third_party/nearby/src/cpp/platform/impl/shared/file.h
deleted file mode 100644
index 21ed871c532..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/shared/file.h
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_SHARED_FILE_H_
-#define PLATFORM_IMPL_SHARED_FILE_H_
-
-#include <cstdint>
-#include <fstream>
-
-#include "absl/strings/string_view.h"
-#include "platform/api/input_file.h"
-#include "platform/api/output_file.h"
-#include "platform/base/exception.h"
-
-namespace location {
-namespace nearby {
-namespace shared {
-
-class InputFile final : public api::InputFile {
- public:
- explicit InputFile(const std::string& path, std::int64_t size);
- ~InputFile() override = default;
- InputFile(InputFile&&) = default;
- InputFile& operator=(InputFile&&) = default;
-
- ExceptionOr<ByteArray> Read(std::int64_t size) override;
- std::string GetFilePath() const override { return path_; }
- std::int64_t GetTotalSize() const override { return total_size_; }
- Exception Close() override;
-
- private:
- std::ifstream file_;
- std::string path_;
- std::int64_t total_size_;
-};
-
-class OutputFile final : public api::OutputFile {
- public:
- explicit OutputFile(absl::string_view path);
- ~OutputFile() override = default;
- OutputFile(OutputFile&&) = default;
- OutputFile& operator=(OutputFile&&) = default;
-
- Exception Write(const ByteArray& data) override;
- Exception Flush() override;
- Exception Close() override;
-
- private:
- std::ofstream file_;
-};
-
-} // namespace shared
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_SHARED_FILE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/shared/file_test.cc b/chromium/third_party/nearby/src/cpp/platform/impl/shared/file_test.cc
deleted file mode 100644
index e1a55a813db..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/shared/file_test.cc
+++ /dev/null
@@ -1,148 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/shared/file.h"
-
-#include <cstring>
-#include <fstream>
-#include <memory>
-#include <ostream>
-
-#include "file/util/temp_path.h"
-#include "gtest/gtest.h"
-#include "absl/strings/string_view.h"
-#include "platform/base/byte_array.h"
-
-namespace location {
-namespace nearby {
-namespace shared {
-
-class FileTest : public ::testing::Test {
- protected:
- void SetUp() override {
- temp_path_ = std::make_unique<TempPath>(TempPath::Local);
- path_ = temp_path_->path() + "/file.txt";
- std::ofstream output_file(path_);
- file_ = std::fstream(path_, std::fstream::in | std::fstream::out);
- }
-
- void WriteToFile(absl::string_view text) {
- file_ << text;
- file_.flush();
- size_ += text.size();
- }
-
- size_t GetSize() const { return size_; }
-
- void AssertEquals(const ExceptionOr<ByteArray>& bytes,
- const std::string& expected) {
- EXPECT_TRUE(bytes.ok());
- EXPECT_EQ(std::string(bytes.result()), expected);
- }
-
- void AssertEmpty(const ExceptionOr<ByteArray>& bytes) {
- EXPECT_TRUE(bytes.ok());
- EXPECT_TRUE(bytes.result().Empty());
- }
-
- static constexpr int64_t kMaxSize = 3;
-
- std::unique_ptr<TempPath> temp_path_;
- std::string path_;
- std::fstream file_;
- size_t size_ = 0;
-};
-
-TEST_F(FileTest, InputFile_NonExistentPath) {
- InputFile input_file("/not/a/valid/path.txt", GetSize());
- ExceptionOr<ByteArray> read_result = input_file.Read(kMaxSize);
- EXPECT_FALSE(read_result.ok());
- EXPECT_TRUE(read_result.GetException().Raised(Exception::kIo));
-}
-
-TEST_F(FileTest, InputFile_GetFilePath) {
- InputFile input_file(path_, GetSize());
- EXPECT_EQ(input_file.GetFilePath(), path_);
-}
-
-TEST_F(FileTest, InputFile_EmptyFileEOF) {
- InputFile input_file(path_, GetSize());
- AssertEmpty(input_file.Read(kMaxSize));
-}
-
-TEST_F(FileTest, InputFile_ReadWorks) {
- WriteToFile("abc");
- InputFile input_file(path_, GetSize());
- input_file.Read(kMaxSize);
- SUCCEED();
-}
-
-TEST_F(FileTest, InputFile_ReadUntilEOF) {
- WriteToFile("abc");
- InputFile input_file(path_, GetSize());
- AssertEquals(input_file.Read(kMaxSize), "abc");
- AssertEmpty(input_file.Read(kMaxSize));
-}
-
-TEST_F(FileTest, InputFile_ReadWithSize) {
- WriteToFile("abc");
- InputFile input_file(path_, GetSize());
- AssertEquals(input_file.Read(2), "ab");
- AssertEquals(input_file.Read(1), "c");
- AssertEmpty(input_file.Read(kMaxSize));
-}
-
-TEST_F(FileTest, InputFile_GetTotalSize) {
- WriteToFile("abc");
- InputFile input_file(path_, GetSize());
- EXPECT_EQ(input_file.GetTotalSize(), 3);
- AssertEquals(input_file.Read(1), "a");
- EXPECT_EQ(input_file.GetTotalSize(), 3);
-}
-
-TEST_F(FileTest, InputFile_Close) {
- WriteToFile("abc");
- InputFile input_file(path_, GetSize());
- input_file.Close();
- ExceptionOr<ByteArray> read_result = input_file.Read(kMaxSize);
- EXPECT_FALSE(read_result.ok());
- EXPECT_TRUE(read_result.GetException().Raised(Exception::kIo));
-}
-
-TEST_F(FileTest, OutputFile_NonExistentPath) {
- OutputFile output_file("/not/a/valid/path.txt");
- ByteArray bytes("a", 1);
- EXPECT_TRUE(output_file.Write(bytes).Raised(Exception::kIo));
-}
-
-TEST_F(FileTest, OutputFile_Write) {
- OutputFile output_file(path_);
- ByteArray bytes1("a");
- ByteArray bytes2("bc");
- EXPECT_EQ(output_file.Write(bytes1), Exception{Exception::kSuccess});
- EXPECT_EQ(output_file.Write(bytes2), Exception{Exception::kSuccess});
- InputFile input_file(path_, GetSize());
- AssertEquals(input_file.Read(kMaxSize), "abc");
-}
-
-TEST_F(FileTest, OutputFile_Close) {
- OutputFile output_file(path_);
- output_file.Close();
- ByteArray bytes("a");
- EXPECT_EQ(output_file.Write(bytes), Exception{Exception::kIo});
-}
-
-} // namespace shared
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/shared/posix_condition_variable.cc b/chromium/third_party/nearby/src/cpp/platform/impl/shared/posix_condition_variable.cc
deleted file mode 100644
index 35acfc39f78..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/shared/posix_condition_variable.cc
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/shared/posix_condition_variable.h"
-
-namespace location {
-namespace nearby {
-namespace posix {
-
-ConditionVariable::ConditionVariable(Mutex* mutex)
- : mutex_(mutex), attr_(), cond_() {
- pthread_condattr_init(&attr_);
-
- pthread_cond_init(&cond_, &attr_);
-}
-
-ConditionVariable::~ConditionVariable() {
- pthread_cond_destroy(&cond_);
-
- pthread_condattr_destroy(&attr_);
-}
-
-void ConditionVariable::Notify() { pthread_cond_broadcast(&cond_); }
-
-Exception ConditionVariable::Wait() {
- pthread_cond_wait(&cond_, &(mutex_->mutex_));
-
- return {Exception::kSuccess};
-}
-
-} // namespace posix
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/shared/posix_condition_variable.h b/chromium/third_party/nearby/src/cpp/platform/impl/shared/posix_condition_variable.h
deleted file mode 100644
index e2526296bf8..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/shared/posix_condition_variable.h
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_SHARED_POSIX_CONDITION_VARIABLE_H_
-#define PLATFORM_IMPL_SHARED_POSIX_CONDITION_VARIABLE_H_
-
-#include <pthread.h>
-
-#include "platform/api/condition_variable.h"
-#include "platform/impl/shared/posix_mutex.h"
-
-namespace location {
-namespace nearby {
-namespace posix {
-
-class ConditionVariable : public api::ConditionVariable {
- public:
- explicit ConditionVariable(Mutex* mutex);
- ~ConditionVariable() override;
-
- void Notify() override;
- Exception Wait() override;
-
- private:
- Mutex* mutex_;
- pthread_condattr_t attr_;
- pthread_cond_t cond_;
-};
-
-} // namespace posix
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_SHARED_POSIX_CONDITION_VARIABLE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/shared/posix_mutex.cc b/chromium/third_party/nearby/src/cpp/platform/impl/shared/posix_mutex.cc
deleted file mode 100644
index 663e93ccd66..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/shared/posix_mutex.cc
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/shared/posix_mutex.h"
-
-namespace location {
-namespace nearby {
-namespace posix {
-
-Mutex::Mutex() : attr_(), mutex_() {
- pthread_mutexattr_init(&attr_);
- pthread_mutexattr_settype(&attr_, PTHREAD_MUTEX_RECURSIVE);
-
- pthread_mutex_init(&mutex_, &attr_);
-}
-
-Mutex::~Mutex() {
- pthread_mutex_destroy(&mutex_);
-
- pthread_mutexattr_destroy(&attr_);
-}
-
-void Mutex::Lock() { pthread_mutex_lock(&mutex_); }
-
-void Mutex::Unlock() { pthread_mutex_unlock(&mutex_); }
-
-} // namespace posix
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/shared/posix_mutex.h b/chromium/third_party/nearby/src/cpp/platform/impl/shared/posix_mutex.h
deleted file mode 100644
index 3128408003a..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/shared/posix_mutex.h
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_SHARED_POSIX_MUTEX_H_
-#define PLATFORM_IMPL_SHARED_POSIX_MUTEX_H_
-
-#include <pthread.h>
-
-#include "platform/api/mutex.h"
-
-namespace location {
-namespace nearby {
-namespace posix {
-
-class ABSL_LOCKABLE Mutex : public api::Mutex {
- public:
- Mutex();
- ~Mutex() override;
-
- void Lock() ABSL_EXCLUSIVE_LOCK_FUNCTION() override;
- void Unlock() ABSL_UNLOCK_FUNCTION() override;
-
- private:
- friend class ConditionVariable;
-
- pthread_mutexattr_t attr_;
- pthread_mutex_t mutex_;
-};
-
-} // namespace posix
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_SHARED_POSIX_MUTEX_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/BUILD b/chromium/third_party/nearby/src/cpp/platform/impl/windows/BUILD
deleted file mode 100644
index 726067b445b..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/BUILD
+++ /dev/null
@@ -1,173 +0,0 @@
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# https://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-licenses(["notice"])
-
-cc_library(
- name = "types",
- srcs = [
- "log_message.cc",
- ],
- hdrs = [
- "atomic_boolean.h",
- "atomic_reference.h",
- "bluetooth_adapter.h",
- "cancelable.h",
- "condition_variable.h",
- "executor.h",
- "future.h",
- "input_file.h",
- "listenable_future.h",
- "log_message.h",
- "mutex.h",
- "output_file.h",
- "scheduled_executor.h",
- "settable_future.h",
- "submittable_executor.h",
- "utils.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- deps = [
- "//base",
- "//platform/api:types",
- "//platform/base",
- ],
-)
-
-cc_library(
- name = "comm",
- hdrs = [
- "ble.h",
- "bluetooth_adapter.h",
- "bluetooth_classic.h",
- "bluetooth_classic_device.h",
- "bluetooth_classic_medium.h",
- "bluetooth_classic_server_socket.h",
- "bluetooth_classic_socket.h",
- "condition_variable.h",
- "executor.h",
- "mutex.h",
- "runner.h",
- "scheduled_executor.h",
- "server_sync.h",
- "submittable_executor.h",
- "thread_pool.h",
- "webrtc.h",
- "wifi.h",
- "wifi_lan.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- visibility = ["//visibility:private"],
- deps = [
- "//platform/api:comm",
- "//platform/base",
- "//platform/impl/windows/generated:types",
- ],
-)
-
-cc_library(
- name = "crypto",
- srcs = [
- "crypto.cc",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- visibility = ["//visibility:private"],
- deps = [
- "//absl/strings",
- "//platform/api:types",
- "//platform/base",
- "//openssl:crypto",
- ],
-)
-
-cc_library(
- name = "windows",
- srcs = [
- "bluetooth_adapter.cc",
- "bluetooth_classic_device.cc",
- "bluetooth_classic_medium.cc",
- "bluetooth_classic_server_socket.cc",
- "bluetooth_classic_socket.cc",
- "executor.cc",
- "platform.cc",
- "scheduled_executor.cc",
- "submittable_executor.cc",
- "system_clock.cc",
- "thread_pool.cc",
- "utils.cc",
- "wifi_lan_medium.cc",
- "wifi_lan_server_socket.cc",
- "wifi_lan_socket.cc",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- copts = ["-Ithird_party/nearby_connections/cpp/platform/impl/windows/generated"],
- visibility = [
- "//third_party/nearby_connections/windows:__subpackages__",
- ],
- deps = [
- ":comm",
- ":crypto", # build_cleaner: keep
- ":types",
- "//platform/api:comm",
- "//platform/api:platform",
- "//platform/api:types",
- "//platform/impl/shared:count_down_latch",
- "//platform/impl/shared:file",
- "//platform/impl/windows/generated:types",
- "//platform/public:types",
- ],
-)
-
-cc_library(
- name = "test_utils",
- srcs = [
- "test_utils.cc",
- ],
- hdrs = [
- "test_data.h",
- "test_utils.h",
- ],
- visibility = [
- "//third_party/nearby_connections/windows:__subpackages__",
- ],
- deps = [
- "//platform/base",
- ],
-)
-
-cc_test(
- name = "impl_test",
- size = "small",
- srcs = [
- "atomic_boolean_test.cc",
- "atomic_reference_test.cc",
- "count_down_latch_test.cc",
- "crypto_test.cc",
- "executor_test.cc",
- "scheduled_executor_test.cc",
- "submittable_executor_test.cc",
- ],
- copts = ["-Iplatform/impl/windows/generated -DCORE_ADAPTER_DLL"],
- deps = [
- ":comm",
- ":crypto",
- ":test_utils",
- ":types",
- "//testing/base/public:gunit_main",
- "//platform/api:platform",
- "//platform/base",
- "//platform/impl/windows",
- "//platform/impl/windows/generated:types",
- "//platform/public:logging",
- ],
-)
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/atomic_boolean.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/atomic_boolean.h
deleted file mode 100644
index 8337edd8e3c..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/atomic_boolean.h
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_ATOMIC_BOOLEAN_H_
-#define PLATFORM_IMPL_WINDOWS_ATOMIC_BOOLEAN_H_
-
-#include <atomic>
-
-#include "platform/api/atomic_boolean.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-// A boolean value that may be updated atomically.
-class AtomicBoolean : public api::AtomicBoolean {
- public:
- ~AtomicBoolean() override = default;
-
- // Atomically read and return current value.
- bool Get() const override { return atomic_boolean_; };
-
- // Atomically exchange original value with a new one. Return previous value.
- bool Set(bool value) override { return atomic_boolean_.exchange(value); };
-
- private:
- std::atomic_bool atomic_boolean_;
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_WINDOWS_ATOMIC_BOOLEAN_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/atomic_boolean_test.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/atomic_boolean_test.cc
deleted file mode 100644
index c8c171b52c3..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/atomic_boolean_test.cc
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/windows/atomic_boolean.h"
-
-#include "gtest/gtest.h"
-
-TEST(atomic_boolean, SuccessfulCreation) {
- // Arrange
- location::nearby::windows::AtomicBoolean atomicBoolean;
- bool oldValue = true;
- bool result = false;
-
- // Act
- oldValue = atomicBoolean.Set(true);
- result = atomicBoolean.Get();
-
- // Assert
- EXPECT_TRUE(result);
- EXPECT_FALSE(oldValue);
-}
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/atomic_reference.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/atomic_reference.h
deleted file mode 100644
index 2c399012334..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/atomic_reference.h
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_ATOMIC_REFERENCE_H_
-#define PLATFORM_IMPL_WINDOWS_ATOMIC_REFERENCE_H_
-
-#include <atomic>
-
-#include "platform/api/atomic_reference.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-// Type that allows 32-bit atomic reads and writes.
-class AtomicUint32 : public api::AtomicUint32 {
- public:
- ~AtomicUint32() override = default;
-
- // Atomically reads and returns stored value.
- std::uint32_t Get() const override { return atomic_uint32_; };
-
- // Atomically stores value.
- void Set(std::uint32_t value) override { atomic_uint32_ = value; }
-
- private:
- std::atomic_int32_t atomic_uint32_ = 0;
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_WINDOWS_ATOMIC_REFERENCE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/atomic_reference_test.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/atomic_reference_test.cc
deleted file mode 100644
index adb41801d75..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/atomic_reference_test.cc
+++ /dev/null
@@ -1,72 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/windows/atomic_reference.h"
-
-#include "gtest/gtest.h"
-
-TEST(atomic_reference, SuccessfulCreation) {
- // Arrange
- location::nearby::windows::AtomicUint32 atomicUint32;
- uint32_t result = UINT32_MAX;
- const uint32_t expected = 0;
-
- // Act
- result = atomicUint32.Get();
-
- // Assert
- EXPECT_EQ(result, expected);
-}
-
-TEST(atomic_reference, SuccessfulMaxSet) {
- // Arrange
- location::nearby::windows::AtomicUint32 atomicUint32;
- uint32_t result = 0;
- const uint32_t expected = UINT32_MAX;
-
- // Act
- atomicUint32.Set(UINT32_MAX);
- result = atomicUint32.Get();
-
- // Assert
- EXPECT_EQ(result, expected);
-}
-
-TEST(atomic_reference, SuccessfulMinSet) {
- // Arrange
- location::nearby::windows::AtomicUint32 atomicUint32;
- uint32_t result = UINT32_MAX;
- const uint32_t expected = 0;
-
- // Act
- atomicUint32.Set(0);
- result = atomicUint32.Get();
-
- // Assert
- EXPECT_EQ(result, expected);
-}
-
-TEST(atomic_reference, SetNegativeOneReturnsMAXUINT) {
- // Arrange
- location::nearby::windows::AtomicUint32 atomicUint32;
- uint32_t result = 0;
- const uint32_t expected = UINT32_MAX;
-
- // Act
- atomicUint32.Set(-1); // Try Set -1, should actually store UINT32_MAX
- result = atomicUint32.Get();
-
- // Assert
- EXPECT_EQ(result, expected);
-}
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/ble.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/ble.h
deleted file mode 100644
index 4141f732623..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/ble.h
+++ /dev/null
@@ -1,155 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_BLE_H_
-#define PLATFORM_IMPL_WINDOWS_BLE_H_
-
-#include "platform/api/ble.h"
-#include "platform/base/exception.h"
-#include "platform/base/input_stream.h"
-#include "platform/base/output_stream.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-// Opaque wrapper over a BLE peripheral. Must contain enough data about a
-// particular BLE device to connect to its GATT server.
-class BlePeripheral : public api::BlePeripheral {
- public:
- // TODO(b/184975123): replace with real implementation.
- ~BlePeripheral() override = default;
-
- // TODO(b/184975123): replace with real implementation.
- std::string GetName() const override { return std::string{""}; }
- // TODO(b/184975123): replace with real implementation.
- ByteArray GetAdvertisementBytes(
- const std::string& service_id) const override {
- return ByteArray{};
- }
-};
-
-class BleSocket : public api::BleSocket {
- public:
- // TODO(b/184975123): replace with real implementation.
- ~BleSocket() override;
-
- // Returns the InputStream of the BleSocket.
- // On error, returned stream will report Exception::kIo on any operation.
- //
- // The returned object is not owned by the caller, and can be invalidated once
- // the BleSocket object is destroyed.
- // TODO(b/184975123): replace with real implementation.
- InputStream& GetInputStream() override { return fake_input_stream_; }
-
- // Returns the OutputStream of the BleSocket.
- // On error, returned stream will report Exception::kIo on any operation.
- //
- // The returned object is not owned by the caller, and can be invalidated once
- // the BleSocket object is destroyed.
- // TODO(b/184975123): replace with real implementation.
- OutputStream& GetOutputStream() override { return fake_output_stream_; }
-
- // Conforms to the same contract as
- // https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#close().
- //
- // Returns Exception::kIo on error, Exception::kSuccess otherwise.
- // TODO(b/184975123): replace with real implementation.
- Exception Close() override { return Exception{}; }
-
- // Returns valid BlePeripheral pointer if there is a connection, and
- // nullptr otherwise.
- // TODO(b/184975123): replace with real implementation.
- BlePeripheral* GetRemotePeripheral() override { return nullptr; }
-
- // Unhooked InputStream & OutputStream for empty implementation.
- // TODO(b/184975123): replace with real implementation.
- private:
- class FakeInputStream : public InputStream {
- ~FakeInputStream() override = default;
- ExceptionOr<ByteArray> Read(std::int64_t size) override {
- return ExceptionOr<ByteArray>(Exception::kFailed);
- }
- Exception Close() override { return {.value = Exception::kFailed}; }
- };
- class FakeOutputStream : public OutputStream {
- ~FakeOutputStream() override = default;
-
- Exception Write(const ByteArray& data) override {
- return {.value = Exception::kFailed};
- }
- Exception Flush() override { return {.value = Exception::kFailed}; }
- Exception Close() override { return {.value = Exception::kFailed}; }
- };
- FakeInputStream fake_input_stream_;
- FakeOutputStream fake_output_stream_;
-};
-
-// Container of operations that can be performed over the BLE medium.
-class BleMedium : public api::BleMedium {
- public:
- // TODO(b/184975123): replace with real implementation.
- ~BleMedium() override = default;
-
- // TODO(b/184975123): replace with real implementation.
- bool StartAdvertising(
- const std::string& service_id, const ByteArray& advertisement_bytes,
- const std::string& fast_advertisement_service_uuid) override {
- return false;
- }
- // TODO(b/184975123): replace with real implementation.
- bool StopAdvertising(const std::string& service_id) override { return false; }
-
- // Returns true once the BLE scan has been initiated.
- // TODO(b/184975123): replace with real implementation.
- bool StartScanning(const std::string& service_id,
- const std::string& fast_advertisement_service_uuid,
- DiscoveredPeripheralCallback callback) override {
- return false;
- }
-
- // Returns true once BLE scanning for service_id is well and truly stopped;
- // after this returns, there must be no more invocations of the
- // DiscoveredPeripheralCallback passed in to StartScanning() for service_id.
- // TODO(b/184975123): replace with real implementation.
- bool StopScanning(const std::string& service_id) override { return false; }
-
- // Returns true once BLE socket connection requests to service_id can be
- // accepted.
- // TODO(b/184975123): replace with real implementation.
- bool StartAcceptingConnections(const std::string& service_id,
- AcceptedConnectionCallback callback) override {
- return false;
- }
- // TODO(b/184975123): replace with real implementation.
- bool StopAcceptingConnections(const std::string& service_id) override {
- return false;
- }
-
- // Connects to a BLE peripheral.
- // On success, returns a new BleSocket.
- // On error, returns nullptr.
- // TODO(b/184975123): replace with real implementation.
- std::unique_ptr<api::BleSocket> Connect(
- api::BlePeripheral& peripheral, const std::string& service_id,
- CancellationFlag* cancellation_flag) override {
- return nullptr;
- }
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_WINDOWS_BLE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_adapter.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_adapter.cc
deleted file mode 100644
index 4402507ebdc..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_adapter.cc
+++ /dev/null
@@ -1,452 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/windows/bluetooth_adapter.h"
-
-#include <windows.h>
-#include <winioctl.h>
-#include <bthdef.h>
-#include <bthioctl.h>
-#include <cfgmgr32.h>
-#include <devguid.h>
-#include <initguid.h>
-#include <objbase.h>
-#include <setupapi.h>
-#include <stdio.h>
-#include <usbiodef.h>
-
-#include <string>
-
-#include "absl/strings/str_format.h"
-#include "platform/impl/windows/generated/winrt/Windows.Foundation.h"
-#include "platform/impl/windows/utils.h"
-#include "platform/public/logging.h"
-
-typedef std::basic_string<TCHAR> tstring;
-
-// IOCTL to get local radio information
-#define BTH_GET_DEVICE_INFO_IOCTL 0x411008
-
-#define BUFFER_SIZE 64
-#define FILE_NAME_SIZE 1024
-
-#define REGISTRY_QUERY_FORMAT \
- "SYSTEM\\ControlSet001\\Enum\\%s\\Device Parameters"
-
-#define BLUETOOTH_RADIO_REGISTRY_NAME_KEY "Local Name"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-BluetoothAdapter::BluetoothAdapter()
- : windows_bluetooth_adapter_(winrt::Windows::Devices::Bluetooth::
- BluetoothAdapter::GetDefaultAsync()
- .get()) {
- // Gets the radio represented by this Bluetooth adapter.
- // https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.bluetoothadapter.getradioasync?view=winrt-20348
- windows_bluetooth_radio_ = windows_bluetooth_adapter_.GetRadioAsync().get();
-}
-
-// Synchronously sets the status of the BluetoothAdapter to 'status', and
-// returns true if the operation was a success.
-bool BluetoothAdapter::SetStatus(Status status) {
- if (status == Status::kDisabled) {
- // An asynchronous operation that attempts to set the state of the radio
- // represented by this object.
- // https://docs.microsoft.com/en-us/uwp/api/windows.devices.radios.radio.setstateasync?view=winrt-20348
- windows_bluetooth_radio_.SetStateAsync(RadioState::Off).get();
- } else {
- windows_bluetooth_radio_.SetStateAsync(RadioState::On).get();
- }
- return true;
-}
-
-// Returns true if the BluetoothAdapter's current status is
-// Status::Value::kEnabled.
-bool BluetoothAdapter::IsEnabled() const {
- // Gets the current state of the radio represented by this object.
- // https://docs.microsoft.com/en-us/uwp/api/windows.devices.radios.radio.state?view=winrt-20348
- return windows_bluetooth_radio_.State() == RadioState::On;
-}
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getScanMode()
-//
-// Returns ScanMode::kUnknown on error.
-BluetoothAdapter::ScanMode BluetoothAdapter::GetScanMode() const {
- return scan_mode_;
-}
-
-// Synchronously sets the scan mode of the adapter, and returns true if the
-// operation was a success.
-bool BluetoothAdapter::SetScanMode(ScanMode scan_mode) {
- scan_mode_ = scan_mode;
-
- if (scan_mode_changed_ != nullptr) {
- scan_mode_changed_(scan_mode);
- }
-
- return true;
-}
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getName()
-// Returns an empty string on error
-std::string BluetoothAdapter::GetName() const {
- char *instanceID = GetGenericBluetoothAdapterInstanceID();
-
- if (instanceID == NULL) {
- NEARBY_LOGS(ERROR)
- << __func__ << ": Failed to get Generic Bluetooth Adapter InstanceID";
- return std::string();
- }
- // Add 1 to length to get size (including null)
- // Modify the InstanceID to the format that the Registry expects
- char *instanceIDModified = new char[(strlen(instanceID) + 1) * sizeof(char)];
- absl::SNPrintF(instanceIDModified,
- size_t((strlen(instanceID) + 1) * sizeof(char)), "%s",
- instanceID);
- find_and_replace(instanceIDModified, "\\", "#");
-
- // Change radio module local name in registry
- HKEY hKey;
- char rmLocalNameKey[FILE_NAME_SIZE] = {0};
- LSTATUS ret;
-
- absl::SNPrintF(rmLocalNameKey, sizeof(rmLocalNameKey), REGISTRY_QUERY_FORMAT,
- instanceID);
-
- // Opens the specified registry key.
- // https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regopenkeyexa
- ret = RegOpenKeyExA(
- HKEY_LOCAL_MACHINE, // A handle to an open registry key, using
- // predefined key for local machine
- rmLocalNameKey, // The name of the registry subkey to be opened.
- 0L, // Specifies the option to apply when opening the key.
- KEY_QUERY_VALUE, // A mask that specifies the desired access rights to
- // the key to be opened.
- &hKey); // A pointer to a variable that receives a handle to the opened
- // key
-
- if (ret == ERROR_SUCCESS) {
- BYTE rmLocalName[FILE_NAME_SIZE] = {0};
- DWORD rmLocalNameSize = FILE_NAME_SIZE;
- DWORD valueType;
-
- LSTATUS status =
- // Retrieves the type and data for the specified value name associated
- // with an open registry key.
- // https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regqueryvalueexa
- RegQueryValueExA(
- hKey, // A handle to an open registry key.
- BLUETOOTH_RADIO_REGISTRY_NAME_KEY, // The name of the registry
- // value.
- nullptr, // This parameter is reserved and must be NULL.
- &valueType, // A pointer to a variable that receives a code
- // indicating the type of data stored in the
- // specified value.
- &rmLocalName[0], // A pointer to a buffer that receives the
- // value's data.
- &rmLocalNameSize); // A pointer to a variable that specifies the
- // size of the buffer pointed to by the lpData
- // parameter, in bytes.
-
- // Closes a handle to the specified registry key.
- // https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regclosekey
- RegCloseKey(hKey);
-
- if (status == ERROR_SUCCESS) {
- char str[FILE_NAME_SIZE]{0};
- memcpy(str, rmLocalName, rmLocalNameSize);
- return std::string(str);
- }
- }
-
- // The local name is not in the registry, return the machine name
- char localName[FILE_NAME_SIZE];
- DWORD nameSize = FILE_NAME_SIZE;
-
- // Retrieves the NetBIOS name of the local computer.
- // https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getcomputernamea
- if (GetComputerNameA(localName, &nameSize)) {
- return std::string(localName);
- }
-
- // If we're here, we couldn't get a local name, this should never happen
- NEARBY_LOGS(ERROR) << __func__ << ": Failed to get any radio name";
- return std::string();
-}
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#setName(java.lang.String)
-bool BluetoothAdapter::SetName(absl::string_view name) {
- char *instanceID = GetGenericBluetoothAdapterInstanceID();
-
- if (instanceID == NULL) {
- NEARBY_LOGS(ERROR)
- << __func__ << ": Failed to get Generic Bluetooth Adapter InstanceID";
- return false;
- }
-
- // Add 1 to length to get size (including null)
- char *instanceIDModified = new char[(strlen(instanceID) + 1) * sizeof(char)];
-
- absl::SNPrintF(instanceIDModified,
- size_t((strlen(instanceID) + 1) * sizeof(char)), "%s",
- instanceID);
-
- find_and_replace(instanceIDModified, "\\", "#");
-
- HANDLE hDevice;
- char fileName[FILE_NAME_SIZE] = {0};
-
- // defined in usbiodef.h
- const GUID guid = GUID_DEVINTERFACE_USB_DEVICE;
-
- OLECHAR guidOleStr[BUFFER_SIZE];
- int oleBufferLen = BUFFER_SIZE;
-
- char guidStr[BUFFER_SIZE];
- int bufferLen = BUFFER_SIZE;
- BOOL defaultCharUsed;
-
- // Converts a globally unique identifier (GUID) into a string of printable
- // characters.
- // https://docs.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-stringfromguid2
- auto conversionResult = StringFromGUID2(guid, guidOleStr, bufferLen);
-
- if (conversionResult == 0) {
- NEARBY_LOGS(ERROR) << __func__ << ": Failed to convert guid to string";
- return false;
- }
-
- // Maps a UTF-16 (wide character) string to a new character string. The new
- // character string is not necessarily from a multibyte character set.
- // https://docs.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-widechartomultibyte
- conversionResult =
- WideCharToMultiByte(CP_UTF8, 0, guidOleStr, oleBufferLen, guidStr,
- bufferLen, NULL, &defaultCharUsed);
-
- if (conversionResult != 0) {
- const char *errorResult = {};
-
- switch (conversionResult) {
- case ERROR_INSUFFICIENT_BUFFER:
- errorResult =
- "A supplied buffer size was not large enough, or it was "
- "incorrectly set to NULL.";
- break;
- case ERROR_INVALID_FLAGS:
- errorResult = "The values supplied for flags were not valid.";
- break;
- case ERROR_INVALID_PARAMETER:
- errorResult = "Any of the parameter values was invalid.";
- break;
- case ERROR_NO_UNICODE_TRANSLATION:
- errorResult = "Invalid Unicode was found in a string.";
- break;
- }
-
- NEARBY_LOGS(ERROR) << __func__ << ": Failed to convert guid to string "
- << errorResult;
- }
-
- absl::SNPrintF(fileName, sizeof(fileName), "\\\\.\\%s%s#%s", fileName,
- instanceIDModified, guidStr);
-
- // Creates or opens a file or I/O device.
- // https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea
- hDevice = CreateFileA(
- fileName, // The name of the file or device to be created or opened.
- GENERIC_WRITE, // The requested access to the file or device.
- 0, // The requested sharing mode of the file or device.
- NULL, // A pointer to a SECURITY_ATTRIBUTES structure.
- OPEN_EXISTING, // An action to take on a file or device that exists or
- // does not exist.
- 0, // The file or device attributes and flags.
- NULL); // A valid handle to a template file with the GENERIC_READ access
- // right. This parameter can be NULL.
-
- delete[] instanceIDModified;
-
- if (hDevice == INVALID_HANDLE_VALUE) {
- NEARBY_LOGS(ERROR) << __func__ << ": Failed to open device. Error code: "
- << GetLastError();
- return false;
- }
-
- // Change radio module local name in registry
- HKEY hKey;
- char rmLocalNameKey[FILE_NAME_SIZE] = {0};
- LSTATUS ret;
-
- absl::SNPrintF(rmLocalNameKey, sizeof(rmLocalNameKey), REGISTRY_QUERY_FORMAT,
- instanceID);
-
- // Opens the specified registry key. Note that key names are not case
- // sensitive.
- // https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regopenkeyexa
- ret = RegOpenKeyExA(
- HKEY_LOCAL_MACHINE, // A handle to an open registry key.
- rmLocalNameKey, // The name of the registry subkey to be opened.
- 0L, // Specifies the option to apply when opening the key.
- KEY_SET_VALUE, // A mask that specifies the desired access rights to the
- // key to be opened.
- &hKey); // A pointer to a variable that receives a handle to the opened
- // key.
-
- if (ret != ERROR_SUCCESS) {
- NEARBY_LOGS(ERROR) << __func__
- << ": Failed to open registry key. Error code: " << ret;
- return false;
- }
-
- if (name != "") {
- // Sets the data and type of a specified value under a registry key.
- // https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regsetvalueexa
- ret = RegSetValueExA(
- hKey, // A handle to an open registry key
- BLUETOOTH_RADIO_REGISTRY_NAME_KEY, // The name of the value to be set.
- 0, // This parameter is reserved and must be zero.
- REG_BINARY, // The type of data pointed to by the lpData parameter.
- (LPBYTE)std::string(name).c_str(), // The data to be stored.
- strlen(std::string(name)
- .c_str())); // The size of the information pointed
- // to by the lpData parameter, in bytes.
- } else {
- // If we are told to set the key to "", we treat this as a reset
- // If we delete the key value the OS will default to the system
- // name. If we just set it to blank, it will show as blank in all
- // system dialogs, this is likely undesireable
- ret = RegDeleteValueA(hKey, BLUETOOTH_RADIO_REGISTRY_NAME_KEY);
- }
-
- if (ret != ERROR_SUCCESS) {
- NEARBY_LOGS(ERROR) << __func__
- << ": Failed to set/delete registry key. Error code: "
- << ret;
- return false;
- }
-
- // Closes a handle to the specified registry key.
- // https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regclosekey
- RegCloseKey(hKey);
-
- // tells the control function to reset or reload or similar...
- int32 reload = 4;
- // merely a placeholder
- DWORD bytes = 0;
-
- // Send radio module driver command to update device information
- // Sends a control code directly to a specified device driver, causing the
- // corresponding device to perform the corresponding operation.
- // https://docs.microsoft.com/en-us/windows/win32/api/ioapiset/nf-ioapiset-deviceiocontrol
- if (!DeviceIoControl(
- hDevice, // A handle to the device on which the operation is to be
- // performed.
- BTH_GET_DEVICE_INFO_IOCTL, // The control code for the operation.
- &reload, // A pointer to the input buffer that contains the data
- // required to perform the operation.
- sizeof(reload), // The size of the input buffer, in bytes.
- NULL, // A pointer to the output buffer that is to receive the data
- // returned by the operation.
- 0, // The size of the output buffer, in bytes.
- &bytes, // A pointer to a variable that receives the size of the data
- // stored in the output buffer, in bytes.
- NULL)) { // A pointer to an OVERLAPPED structure.
- NEARBY_LOGS(ERROR)
- << __func__
- << ": Failed to update radio module local name. Error code: "
- << GetLastError();
-
- return false;
- }
-
- return true;
-}
-
-void BluetoothAdapter::find_and_replace(char *source, const char *strFind,
- const char *strReplace) const {
- std::string s = std::string(source);
- std::string f = std::string(strFind);
- std::string r = std::string(strReplace);
- size_t j;
-
- for (; (j = s.find(f)) != std::string::npos;) {
- s.replace(j, f.length(), r);
- }
-
- memcpy(source, s.c_str(), s.size());
-}
-
-char *BluetoothAdapter::GetGenericBluetoothAdapterInstanceID(void) const {
- unsigned i;
- CONFIGRET r;
- HDEVINFO hDevInfo;
- SP_DEVINFO_DATA DeviceInfoData;
- char *deviceInstanceID = new char[MAX_DEVICE_ID_LEN];
-
- // Find all bluetooth radio modules
- // The SetupDiGetClassDevs function returns a handle to a device information
- // set that contains requested device information elements for a local
- // computer.
- // https://docs.microsoft.com/en-us/windows/win32/api/setupapi/nf-setupapi-setupdigetclassdevsa
- hDevInfo =
- SetupDiGetClassDevsA(&GUID_DEVCLASS_BLUETOOTH, NULL, NULL, DIGCF_PRESENT);
-
- if (hDevInfo == INVALID_HANDLE_VALUE) {
- NEARBY_LOGS(ERROR) << __func__
- << ": Could not find BluetoothDevice on this machine";
- return NULL;
- }
-
- // Get first Generic Bluetooth Adapter InstanceID
- for (i = 0;; i++) {
- DeviceInfoData.cbSize = sizeof(DeviceInfoData);
-
- // The SetupDiEnumDeviceInfo function returns a SP_DEVINFO_DATA structure
- // that specifies a device information element in a device information set.
- // https://docs.microsoft.com/en-us/windows/win32/api/setupapi/nf-setupapi-setupdienumdeviceinfo
- if (!SetupDiEnumDeviceInfo(hDevInfo, i, &DeviceInfoData)) break;
-
- // The CM_Get_Device_ID function retrieves the device instance ID for a
- // specified device instance on the local machine.
- // https://docs.microsoft.com/en-us/windows/win32/api/cfgmgr32/nf-cfgmgr32-cm_get_device_ida
- r = CM_Get_Device_IDA(DeviceInfoData.DevInst, deviceInstanceID,
- MAX_DEVICE_ID_LEN, 0);
-
- if (r != CR_SUCCESS) continue;
-
- // With Windows, a Bluetooth radio can be packaged as an external dongle or
- // embedded inside a computer but it must be connected to one of the
- // computer's USB ports.
- // https://docs.microsoft.com/en-us/windows-hardware/drivers/bluetooth/bluetooth-host-radio-support
- if (strncmp("USB", deviceInstanceID, 3) == 0) {
- return deviceInstanceID;
- }
- }
-
- NEARBY_LOGS(ERROR) << __func__
- << ": Failed to get the generic bluetooth adapter id";
-
- return NULL;
-}
-
-// Returns BT MAC address assigned to this adapter.
-std::string BluetoothAdapter::GetMacAddress() const {
- return uint64_to_mac_address_string(
- windows_bluetooth_adapter_.BluetoothAddress());
-}
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_adapter.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_adapter.h
deleted file mode 100644
index 8f083c63e4d..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_adapter.h
+++ /dev/null
@@ -1,99 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_BLUETOOTH_ADAPTER_H_
-#define PLATFORM_IMPL_WINDOWS_BLUETOOTH_ADAPTER_H_
-
-#include <guiddef.h>
-
-#include <string>
-
-#include "platform/api/bluetooth_adapter.h"
-#include "platform/impl/windows/generated/winrt/base.h"
-#include "platform/impl/windows/generated/winrt/Windows.Devices.Bluetooth.h"
-#include "platform/impl/windows/generated/winrt/Windows.Devices.Radios.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-// Represents a Bluetooth adapter.
-// https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.bluetoothadapter?view=winrt-20348
-using winrt::Windows::Devices::Bluetooth::IBluetoothAdapter;
-
-// Represents a radio device on the system.
-// https://docs.microsoft.com/en-us/uwp/api/windows.devices.radios.radio?view=winrt-20348
-using winrt::Windows::Devices::Radios::IRadio;
-
-// Enumeration that describes possible radio states.
-// https://docs.microsoft.com/en-us/uwp/api/windows.devices.radios.radiostate?view=winrt-20348
-using winrt::Windows::Devices::Radios::RadioState;
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html
-class BluetoothAdapter : public api::BluetoothAdapter {
- public:
- BluetoothAdapter();
-
- ~BluetoothAdapter() override = default;
-
- typedef std::function<void(api::BluetoothAdapter::ScanMode)> ScanModeCallback;
-
- // Synchronously sets the status of the BluetoothAdapter to 'status', and
- // returns true if the operation was a success.
- bool SetStatus(Status status) override;
-
- // Returns true if the BluetoothAdapter's current status is
- // Status::Value::kEnabled.
- bool IsEnabled() const override;
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getScanMode()
- // Returns ScanMode::kUnknown on error.
- ScanMode GetScanMode() const override;
-
- // Synchronously sets the scan mode of the adapter, and returns true if the
- // operation was a success.
- bool SetScanMode(ScanMode scan_mode) override;
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getName()
- // Returns an empty string on error
- std::string GetName() const override;
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#setName(java.lang.String)
- bool SetName(absl::string_view name) override;
-
- // Returns BT MAC address assigned to this adapter.
- std::string GetMacAddress() const override;
-
- void SetOnScanModeChanged(ScanModeCallback callback) {
- if (scan_mode_changed_ == nullptr) {
- scan_mode_changed_ = callback;
- }
- }
-
- private:
- IBluetoothAdapter windows_bluetooth_adapter_;
-
- IRadio windows_bluetooth_radio_;
- char *GetGenericBluetoothAdapterInstanceID(void) const;
- void find_and_replace(char *source, const char *strFind,
- const char *strReplace) const;
- ScanMode scan_mode_ = ScanMode::kNone;
- ScanModeCallback scan_mode_changed_ = nullptr;
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_WINDOWS_BLUETOOTH_ADAPTER_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic.h
deleted file mode 100644
index e9d239fcaa6..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic.h
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_H_
-#define PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_H_
-
-#include "platform/impl/windows/bluetooth_classic_device.h"
-#include "platform/impl/windows/bluetooth_classic_medium.h"
-#include "platform/impl/windows/bluetooth_classic_server_socket.h"
-#include "platform/impl/windows/bluetooth_classic_socket.h"
-
-#endif // PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_device.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_device.cc
deleted file mode 100644
index 49f47ee1a0d..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_device.cc
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/windows/bluetooth_classic_device.h"
-
-#include <winstring.h>
-
-#include <codecvt>
-#include <locale>
-#include <string>
-
-#include "platform/impl/windows/generated/winrt/Windows.Devices.Bluetooth.h"
-
-#include "platform/impl/windows/utils.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-BluetoothDevice::~BluetoothDevice() {}
-
-BluetoothDevice::BluetoothDevice(
- const winrt::Windows::Devices::Bluetooth::BluetoothDevice& bluetoothDevice)
- : windows_bluetooth_device_(bluetoothDevice) {
- id_ = winrt::to_string(bluetoothDevice.DeviceId());
-
- // Get the device address.
- auto bluetoothAddress = bluetoothDevice.BluetoothAddress();
-
- mac_address_ = uint64_to_mac_address_string(bluetoothAddress);
-}
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#getName()
-std::string BluetoothDevice::GetName() const {
- return winrt::to_string(windows_bluetooth_device_.Name());
-}
-
-// Returns BT MAC address assigned to this device.
-std::string BluetoothDevice::GetMacAddress() const { return mac_address_; }
-
-// We are using Uncached because:
-// For the following APIs, Cached means only use values cached in the system
-// cached (if not cached then don't fall back to querying the device).
-// The device may be present, but not entered into the cache yet, so always
-// check the actual device.
-IAsyncOperation<RfcommDeviceServicesResult>
-BluetoothDevice::GetRfcommServicesForIdAsync(const RfcommServiceId serviceId) {
- return windows_bluetooth_device_.GetRfcommServicesForIdAsync(
- serviceId, BluetoothCacheMode::Uncached);
-}
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_device.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_device.h
deleted file mode 100644
index 919c3d2b9f2..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_device.h
+++ /dev/null
@@ -1,93 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_DEVICE_H_
-#define PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_DEVICE_H_
-
-#include <guiddef.h>
-
-#include <string>
-
-#include "platform/api/bluetooth_classic.h"
-#include "platform/base/exception.h"
-#include "platform/base/input_stream.h"
-#include "platform/base/output_stream.h"
-#include "platform/impl/windows/generated/winrt/Windows.Devices.Bluetooth.h"
-#include "platform/impl/windows/generated/winrt/Windows.Devices.Enumeration.h"
-#include "platform/impl/windows/generated/winrt/base.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-// Represents an asynchronous operation, which returns a result upon completion.
-// https://docs.microsoft.com/en-us/uwp/api/windows.foundation.iasyncoperation-1?view=winrt-20348
-using winrt::Windows::Foundation::IAsyncOperation;
-
-// The result of an Rfcomm device service request.
-// https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.rfcomm.rfcommdeviceservicesresult?view=winrt-20348
-using winrt::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceServicesResult;
-
-// Represents an RFCOMM service ID.
-// https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.rfcomm.rfcommserviceid?view=winrt-20348
-using winrt::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId;
-
-// Indicates whether applicable Bluetooth API methods should operate on values
-// cached in the system, or whether they should retrieve those values from the
-// Bluetooth device.
-// https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.bluetoothcachemode?view=winrt-20348
-using winrt::Windows::Devices::Bluetooth::BluetoothCacheMode;
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html.
-class BluetoothDevice : public api::BluetoothDevice {
- public:
- BluetoothDevice(std::string mac_address)
- : windows_bluetooth_device_(nullptr), mac_address_(mac_address) {}
- BluetoothDevice(const winrt::Windows::Devices::Bluetooth::BluetoothDevice&
- bluetoothDevice);
-
- ~BluetoothDevice() override;
- BluetoothDevice(BluetoothDevice&&) = default;
- BluetoothDevice& operator=(BluetoothDevice&&) = default;
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#getName()
- std::string GetName() const override;
-
- // Returns BT MAC address assigned to this device.
- std::string GetMacAddress() const override;
-
- std::string GetId() { return id_; }
-
- winrt::Windows::Foundation::IAsyncOperation<
- winrt::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceServicesResult>
- GetRfcommServicesForIdAsync(
- const winrt::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId
- serviceId);
-
- private:
- // https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.bluetoothdevice?view=winrt-20348
- winrt::Windows::Devices::Bluetooth::BluetoothDevice windows_bluetooth_device_;
-
- // Once the device is lost, we can no longer access it's id.
- std::string id_;
-
- // Once the device is lost, we can no longer access it's mac address.
- std::string mac_address_;
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_DEVICE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_medium.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_medium.cc
deleted file mode 100644
index 4f8a7db4124..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_medium.cc
+++ /dev/null
@@ -1,443 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/windows/bluetooth_classic_medium.h"
-
-#include <windows.h>
-#include <stdio.h>
-
-#include <codecvt>
-#include <locale>
-#include <regex> // NOLINT
-#include <string>
-
-#include "platform/base/cancellation_flag.h"
-#include "platform/base/cancellation_flag_listener.h"
-#include "platform/base/exception.h"
-#include "platform/impl/windows/bluetooth_adapter.h"
-#include "platform/impl/windows/bluetooth_classic_device.h"
-#include "platform/impl/windows/bluetooth_classic_server_socket.h"
-#include "platform/impl/windows/bluetooth_classic_socket.h"
-#include "platform/impl/windows/generated/winrt/Windows.Devices.Bluetooth.Rfcomm.h"
-#include "platform/impl/windows/generated/winrt/Windows.Devices.Bluetooth.h"
-#include "platform/impl/windows/generated/winrt/Windows.Devices.Enumeration.h"
-#include "platform/impl/windows/generated/winrt/Windows.Foundation.Collections.h"
-#include "platform/impl/windows/generated/winrt/base.h"
-#include "platform/impl/windows/utils.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-BluetoothClassicMedium::BluetoothClassicMedium(
- api::BluetoothAdapter& bluetoothAdapter)
- : bluetooth_adapter_(dynamic_cast<BluetoothAdapter&>(bluetoothAdapter)) {
- InitializeCriticalSection(&critical_section_);
-
- InitializeDeviceWatcher();
-
- bluetooth_adapter_.SetOnScanModeChanged(std::bind(
- &BluetoothClassicMedium::OnScanModeChanged, this, std::placeholders::_1));
-}
-
-BluetoothClassicMedium::~BluetoothClassicMedium() {}
-
-void BluetoothClassicMedium::OnScanModeChanged(
- BluetoothAdapter::ScanMode scanMode) {
- scan_mode_ = scanMode;
- bool radioDiscoverable = bluetooth_adapter_.GetScanMode() ==
- BluetoothAdapter::ScanMode::kConnectableDiscoverable;
-
- if (bluetooth_server_socket_ != nullptr) {
- bluetooth_server_socket_->SetScanMode(radioDiscoverable);
- }
-}
-
-bool BluetoothClassicMedium::StartDiscovery(
- BluetoothClassicMedium::DiscoveryCallback discovery_callback) {
- EnterCriticalSection(&critical_section_);
-
- bool result = false;
- discovery_callback_ = discovery_callback;
-
- if (!IsWatcherStarted()) {
- result = StartScanning();
- }
-
- LeaveCriticalSection(&critical_section_);
-
- return result;
-}
-
-bool BluetoothClassicMedium::StopDiscovery() {
- EnterCriticalSection(&critical_section_);
-
- bool result = false;
-
- if (IsWatcherStarted()) {
- result = StopScanning();
- }
-
- LeaveCriticalSection(&critical_section_);
-
- return result;
-}
-
-void BluetoothClassicMedium::InitializeDeviceWatcher() {
- // create watcher
- device_watcher_ = DeviceInformation::CreateWatcher(
- BLUETOOTH_SELECTOR, // aqsFilter
- nullptr, // additionalProperties
- DeviceInformationKind::AssociationEndpoint); // kind
-
- // An app must subscribe to all of the added, removed, and updated events to
- // be notified when there are device additions, removals or updates. If an
- // app handles only the added event, it will not receive an update if a
- // device is added to the system after the initial device enumeration
- // completes. register event handlers before starting the watcher
-
- // Event that is raised when a device is added to the collection enumerated
- // by the DeviceWatcher.
- // https://docs.microsoft.com/en-us/uwp/api/windows.devices.enumeration.devicewatcher.added?view=winrt-20348
- device_watcher_.Added({this, &BluetoothClassicMedium::DeviceWatcher_Added});
-
- // Event that is raised when a device is updated in the collection of
- // enumerated devices.
- // https://docs.microsoft.com/en-us/uwp/api/windows.devices.enumeration.devicewatcher.updated?view=winrt-20348
- device_watcher_.Updated(
- {this, &BluetoothClassicMedium::DeviceWatcher_Updated});
-
- // Event that is raised when a device is removed from the collection of
- // enumerated devices.
- // https://docs.microsoft.com/en-us/uwp/api/windows.devices.enumeration.devicewatcher.removed?view=winrt-20348
- device_watcher_.Removed(
- {this, &BluetoothClassicMedium::DeviceWatcher_Removed});
-}
-
-std::unique_ptr<api::BluetoothSocket> BluetoothClassicMedium::ConnectToService(
- api::BluetoothDevice& remote_device, const std::string& service_uuid,
- CancellationFlag* cancellation_flag) {
- if (service_uuid.empty()) {
- NEARBY_LOGS(ERROR) << __func__ << ": service_uuid not specified.";
- return nullptr;
- }
-
- const std::regex pattern(
- "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]"
- "{12}$");
-
- // Must check for valid pattern as the guid constructor will throw on an
- // invalid format
- if (!regex_match(service_uuid, pattern)) {
- NEARBY_LOGS(ERROR) << __func__
- << ": invalid service_uuid: " << service_uuid;
- return nullptr;
- }
-
- winrt::guid service(service_uuid);
-
- if (cancellation_flag == nullptr) {
- NEARBY_LOGS(ERROR) << __func__ << ": cancellation_flag not specified.";
- return nullptr;
- }
-
- BluetoothDevice* currentDevice =
- dynamic_cast<BluetoothDevice*>(&remote_device);
-
- if (currentDevice == nullptr) {
- NEARBY_LOGS(ERROR) << __func__ << ": Failed to get current device.";
- return nullptr;
- }
-
- winrt::hstring deviceId = winrt::to_hstring(currentDevice->GetId());
-
- if (!HaveAccess(deviceId)) {
- NEARBY_LOGS(ERROR) << __func__ << ": Failed to gain access to device: "
- << winrt::to_string(deviceId);
- return nullptr;
- }
-
- RfcommDeviceService requestedService(
- GetRequestedService(currentDevice, service));
-
- if (!CheckSdp(requestedService)) {
- NEARBY_LOGS(ERROR) << __func__ << ": Invalid SDP.";
- return nullptr;
- }
-
- device_watcher_.Stop();
-
- EnterCriticalSection(&critical_section_);
-
- std::unique_ptr<BluetoothSocket> rfcommSocket =
- std::make_unique<BluetoothSocket>();
-
- location::nearby::CancellationFlagListener cancellationFlagListener(
- cancellation_flag,
- [&rfcommSocket]() { rfcommSocket.get()->CancelIOAsync().get(); });
-
- try {
- rfcommSocket->Connect(requestedService.ConnectionHostName(),
- requestedService.ConnectionServiceName());
- } catch (std::exception exception) {
- // We will log and eat the exception since the caller
- // expects nullptr if it fails
- NEARBY_LOGS(ERROR) << __func__ << ": Exception connecting bluetooth async: "
- << exception.what();
-
- LeaveCriticalSection(&critical_section_);
-
- return nullptr;
- }
-
- LeaveCriticalSection(&critical_section_);
-
- return rfcommSocket;
-}
-
-bool BluetoothClassicMedium::HaveAccess(winrt::hstring deviceId) {
- DeviceAccessStatus accessStatus =
- DeviceAccessInformation::CreateFromId(deviceId).CurrentStatus();
-
- if (accessStatus == DeviceAccessStatus::DeniedByUser ||
- // This status is most likely caused by app permissions (did not declare
- // the device in the app's package.appxmanifest)
- // This status does not cover the case where the device is already opened
- // by another app.
- accessStatus == DeviceAccessStatus::DeniedBySystem ||
- // Most likely the device is opened by another app, but cannot be sure
- accessStatus == DeviceAccessStatus::Unspecified) {
- return false;
- }
-
- return true;
-}
-
-RfcommDeviceService BluetoothClassicMedium::GetRequestedService(
- BluetoothDevice* device, winrt::guid service) {
- RfcommServiceId rfcommServiceId = RfcommServiceId::FromUuid(service);
-
- // Retrieves all Rfcomm Services on the Remote Bluetooth Device matching the
- // specified RfcommServiceId.
- // https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.bluetoothdevice.getrfcommservicesforidasync?view=winrt-20348
- IAsyncOperation<RfcommDeviceServicesResult> rfcommServices =
- device->GetRfcommServicesForIdAsync(rfcommServiceId);
-
- RfcommDeviceService requestedService(nullptr);
-
- if (rfcommServices.get().Services().Size() > 0) {
- requestedService = rfcommServices.get().Services().GetAt(0);
- } else {
- NEARBY_LOGS(ERROR) << __func__ << ": No services found.";
- return nullptr;
- }
-
- return requestedService;
-}
-
-bool BluetoothClassicMedium::CheckSdp(RfcommDeviceService requestedService) {
- // Do various checks of the SDP record to make sure you are talking to a
- // device that actually supports the Bluetooth Rfcomm Service
- // https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.rfcomm.rfcommdeviceservice.getsdprawattributesasync?view=winrt-20348
- auto attributes = requestedService.GetSdpRawAttributesAsync().get();
- if (!attributes.HasKey(Constants::SdpServiceNameAttributeId)) {
- NEARBY_LOGS(ERROR) << __func__ << ": Missing SdpServiceNameAttributeId.";
- return false;
- }
-
- auto attributeReader = DataReader::FromBuffer(
- attributes.Lookup(Constants::SdpServiceNameAttributeId));
-
- auto attributeType = attributeReader.ReadByte();
-
- if (attributeType != Constants::SdpServiceNameAttributeType) {
- NEARBY_LOGS(ERROR) << __func__ << ": Missing SdpServiceNameAttributeType.";
- return false;
- }
-
- return true;
-}
-// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#listenUsingInsecureRfcommWithServiceRecord
-//
-// service_uuid is the canonical textual representation
-// (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format) of a
-// type 3 name-based
-// (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based))
-// UUID.
-//
-// Returns nullptr error.
-std::unique_ptr<api::BluetoothServerSocket>
-BluetoothClassicMedium::ListenForService(const std::string& service_name,
- const std::string& service_uuid) {
- if (service_uuid.empty()) {
- NEARBY_LOGS(ERROR) << __func__ << ": service_uuid was empty.";
- return nullptr;
- }
-
- if (service_name.empty()) {
- NEARBY_LOGS(ERROR) << __func__ << ": service_name was empty.";
- return nullptr;
- }
-
- auto bluetooth_server_socket =
- std::make_unique<location::nearby::windows::BluetoothServerSocket>(
- service_name, service_uuid);
-
- if (bluetooth_server_socket == nullptr) {
- NEARBY_LOGS(ERROR) << __func__ << ": Failed to create the server socket.";
- return nullptr;
- }
-
- bool radioDiscoverable = bluetooth_adapter_.GetScanMode() ==
- BluetoothAdapter::ScanMode::kConnectableDiscoverable;
-
- Exception result = bluetooth_server_socket->StartListening(radioDiscoverable);
-
- if (result.value != Exception::kSuccess) {
- NEARBY_LOGS(ERROR) << __func__ << ": Failed to start listening.";
- return nullptr;
- }
-
- return std::move(bluetooth_server_socket);
-}
-
-api::BluetoothDevice* BluetoothClassicMedium::GetRemoteDevice(
- const std::string& mac_address) {
- return new BluetoothDevice(mac_address);
-}
-
-bool BluetoothClassicMedium::StartScanning() {
- if (!IsWatcherStarted()) {
- // The Start method can only be called when the DeviceWatcher is in the
- // Created, Stopped or Aborted state.
- auto status = device_watcher_.Status();
-
- if (status == DeviceWatcherStatus::Created ||
- status == DeviceWatcherStatus::Stopped ||
- status == DeviceWatcherStatus::Aborted) {
- device_watcher_.Start();
-
- return true;
- }
- }
-
- NEARBY_LOGS(ERROR)
- << __func__
- << ": Attempted to start scanning when watcher already started.";
- return false;
-}
-
-bool BluetoothClassicMedium::StopScanning() {
- if (IsWatcherRunning()) {
- device_watcher_.Stop();
- return true;
- }
- NEARBY_LOGS(ERROR)
- << __func__
- << ": Attempted to stop scanning when watcher already stopped.";
- return false;
-}
-
-winrt::fire_and_forget BluetoothClassicMedium::DeviceWatcher_Added(
- DeviceWatcher sender, DeviceInformation deviceInfo) {
- if (IsWatcherStarted()) {
- // Represents a Bluetooth device.
- // https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.bluetoothdevice?view=winrt-20348
- std::unique_ptr<winrt::Windows::Devices::Bluetooth::BluetoothDevice>
- windowsBluetoothDevice;
-
- // Create an iterator for the internal list
- std::map<winrt::hstring, std::unique_ptr<BluetoothDevice>>::const_iterator
- it = devices_by_id_.find(deviceInfo.Id());
-
- // Add to our internal list if necessary
- if (it == devices_by_id_.end()) {
- // Create a bluetooth device out of this id
- winrt::Windows::Devices::Bluetooth::BluetoothDevice::FromIdAsync(
- deviceInfo.Id())
- .Completed(
- [this, deviceInfo, wbd = std::move(windowsBluetoothDevice)](
- auto&& async,
- winrt::Windows::Foundation::AsyncStatus status) {
- EnterCriticalSection(&critical_section_);
-
- std::unique_ptr<BluetoothDevice> bluetoothDevice =
- std::make_unique<BluetoothDevice>(async.get());
-
- devices_by_id_[deviceInfo.Id()] = std::move(bluetoothDevice);
-
- if (discovery_callback_.device_discovered_cb != nullptr) {
- discovery_callback_.device_discovered_cb(
- *devices_by_id_[deviceInfo.Id()]);
- }
-
- LeaveCriticalSection(&critical_section_);
- });
- }
- }
-
- return winrt::fire_and_forget();
-}
-
-winrt::fire_and_forget BluetoothClassicMedium::DeviceWatcher_Updated(
- DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate) {
- if (IsWatcherStarted()) {
- // TODO(jfcarroll): Check for device name change
- }
-
- return winrt::fire_and_forget();
-}
-
-winrt::fire_and_forget BluetoothClassicMedium::DeviceWatcher_Removed(
- DeviceWatcher sender, DeviceInformationUpdate deviceInfo) {
- EnterCriticalSection(&critical_section_);
-
- if (IsWatcherStarted()) {
- if (discovery_callback_.device_lost_cb != nullptr) {
- discovery_callback_.device_lost_cb(*devices_by_id_[deviceInfo.Id()]);
- }
-
- devices_by_id_.erase(deviceInfo.Id());
- }
-
- LeaveCriticalSection(&critical_section_);
-
- return winrt::fire_and_forget();
-}
-
-bool BluetoothClassicMedium::IsWatcherStarted() {
- if (device_watcher_ == nullptr) {
- return false;
- }
-
- DeviceWatcherStatus status = device_watcher_.Status();
- return (status == DeviceWatcherStatus::Started) ||
- (status == DeviceWatcherStatus::EnumerationCompleted);
-}
-
-bool BluetoothClassicMedium::IsWatcherRunning() {
- if (device_watcher_ == nullptr) {
- return false;
- }
-
- DeviceWatcherStatus status = device_watcher_.Status();
- return (status == DeviceWatcherStatus::Started) ||
- (status == DeviceWatcherStatus::EnumerationCompleted) ||
- (status == DeviceWatcherStatus::Stopping);
-}
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_medium.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_medium.h
deleted file mode 100644
index a5d9692689d..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_medium.h
+++ /dev/null
@@ -1,191 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_MEDIUM_H_
-#define PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_MEDIUM_H_
-
-#include "platform/api/bluetooth_classic.h"
-#include "platform/impl/windows/bluetooth_adapter.h"
-#include "platform/impl/windows/bluetooth_classic_device.h"
-#include "platform/impl/windows/bluetooth_classic_server_socket.h"
-#include "platform/impl/windows/bluetooth_classic_socket.h"
-#include "platform/impl/windows/generated/winrt/Windows.Devices.Enumeration.h"
-#include "platform/impl/windows/generated/winrt/Windows.Networking.Sockets.h"
-#include "platform/impl/windows/generated/winrt/base.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-// Represents a device. This class allows access to well-known device properties
-// as well as additional properties specified during device enumeration.
-// https://docs.microsoft.com/en-us/uwp/api/windows.devices.enumeration.deviceinformation?view=winrt-20348
-using winrt::Windows::Devices::Enumeration::DeviceInformation;
-
-// Represents the kind of DeviceInformation object.
-// https://docs.microsoft.com/en-us/uwp/api/windows.devices.enumeration.deviceinformationkind?view=winrt-20348
-using winrt::Windows::Devices::Enumeration::DeviceInformationKind;
-
-// Contains updated properties for a DeviceInformation object.
-// https://docs.microsoft.com/en-us/uwp/api/windows.devices.enumeration.deviceinformationupdate?view=winrt-20348
-using winrt::Windows::Devices::Enumeration::DeviceInformationUpdate;
-
-// Enumerates devices dynamically, so that the app receives notifications if
-// devices are added, removed, or changed after the initial enumeration is
-// complete.
-// https://docs.microsoft.com/en-us/uwp/api/windows.devices.enumeration.devicewatcher?view=winrt-20348
-using winrt::Windows::Devices::Enumeration::DeviceWatcher;
-
-// Describes the state of a DeviceWatcher object.
-// https://docs.microsoft.com/en-us/uwp/api/windows.devices.enumeration.devicewatcherstatus?view=winrt-20348
-using winrt::Windows::Devices::Enumeration::DeviceWatcherStatus;
-
-// Represents an instance of a service on a Bluetooth basic rate device.
-// https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.rfcomm.rfcommdeviceservice?view=winrt-20348
-using winrt::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService;
-
-// Indicates the status of the access to a device.
-// https://docs.microsoft.com/en-us/uwp/api/windows.devices.enumeration.deviceaccessstatus?view=winrt-20348
-using winrt::Windows::Devices::Enumeration::DeviceAccessStatus;
-
-// Contains the information about access to a device.
-// https://docs.microsoft.com/en-us/uwp/api/windows.devices.enumeration.deviceaccessinformation?view=winrt-20348
-using winrt::Windows::Devices::Enumeration::DeviceAccessInformation;
-
-// Represents an RFCOMM service ID.
-// https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.rfcomm.rfcommserviceid?view=winrt-20348
-using winrt::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId;
-
-// Reads data from an input stream.
-// https://docs.microsoft.com/en-us/uwp/api/windows.storage.streams.datareader?view=winrt-20348
-using winrt::Windows::Storage::Streams::DataReader;
-
-// Writes data to an output stream.
-// https://docs.microsoft.com/en-us/uwp/api/windows.storage.streams.datawriter?view=winrt-20348
-using winrt::Windows::Storage::Streams::DataWriter;
-
-// Bluetooth protocol ID = \"{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}\"
-// https://docs.microsoft.com/en-us/windows/uwp/devices-sensors/aep-service-class-ids
-#define BLUETOOTH_SELECTOR \
- L"System.Devices.Aep.ProtocolId:=\"{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}\""
-
-// Container of operations that can be performed over the Bluetooth Classic
-// medium.
-class BluetoothClassicMedium : public api::BluetoothClassicMedium {
- public:
- BluetoothClassicMedium(api::BluetoothAdapter& bluetoothAdapter);
-
- ~BluetoothClassicMedium() override;
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#startDiscovery()
- bool StartDiscovery(DiscoveryCallback discovery_callback) override;
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#cancelDiscovery()
- //
- // Returns true once discovery is well and truly stopped; after this returns,
- // there must be no more invocations of the DiscoveryCallback passed in to
- // StartDiscovery().
- bool StopDiscovery() override;
-
- // A combination of
- // https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#createInsecureRfcommSocketToServiceRecord
- // followed by
- // https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#connect().
- //
- // service_uuid is the canonical textual representation
- // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format) of a
- // type 3 name-based
- // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based))
- // UUID.
- //
- // On success, returns a new BluetoothSocket.
- // On error, throw's an exception
- std::unique_ptr<api::BluetoothSocket> ConnectToService(
- api::BluetoothDevice& remote_device, const std::string& service_uuid,
- CancellationFlag* cancellation_flag) override;
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#listenUsingInsecureRfcommWithServiceRecord
- //
- // service_uuid is the canonical textual representation
- // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format) of a
- // type 3 name-based
- // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based))
- // UUID.
- //
- // Returns nullptr error.
- std::unique_ptr<api::BluetoothServerSocket> ListenForService(
- const std::string& service_name,
- const std::string& service_uuid) override;
-
- api::BluetoothDevice* GetRemoteDevice(
- const std::string& mac_address) override;
-
- private:
- bool StartScanning();
- bool StopScanning();
- bool IsWatcherStarted();
- bool IsWatcherRunning();
- void InitializeDeviceWatcher();
- void OnScanModeChanged(BluetoothAdapter::ScanMode scanMode);
-
- // This is for a coroutine whose return type is winrt::fire_and_forget, which
- // handles async operations which don't have any dependencies.
- // https://docs.microsoft.com/en-us/uwp/cpp-ref-for-winrt/fire-and-forget
- winrt::fire_and_forget DeviceWatcher_Added(DeviceWatcher sender,
- DeviceInformation deviceInfo);
-
- winrt::fire_and_forget DeviceWatcher_Updated(
- DeviceWatcher sender, DeviceInformationUpdate deviceInfo);
-
- winrt::fire_and_forget DeviceWatcher_Removed(
- DeviceWatcher sender, DeviceInformationUpdate deviceInfo);
-
- // Check to make sure we can connect if we try
- bool HaveAccess(winrt::hstring deviceId);
-
- // Get the service requested
- RfcommDeviceService GetRequestedService(BluetoothDevice* device,
- winrt::guid service);
-
- // Check to see that the device actually handles the requested service
- bool CheckSdp(RfcommDeviceService requestedService);
-
- BluetoothClassicMedium::DiscoveryCallback discovery_callback_;
-
- DeviceWatcher device_watcher_ = nullptr;
-
- std::unique_ptr<BluetoothSocket> bluetooth_socket_;
- std::unique_ptr<BluetoothServerSocket> bluetooth_server_socket_;
-
- std::string service_name_;
- std::string service_uuid_;
-
- // hstring is the only type of string winrt understands.
- // https://docs.microsoft.com/en-us/uwp/cpp-ref-for-winrt/hstring
- std::map<winrt::hstring, std::unique_ptr<BluetoothDevice>> devices_by_id_;
-
- // CRITICAL_SECTION is a lightweight synchronization mechanism
- // https://docs.microsoft.com/en-us/windows/win32/sync/critical-section-objects
- CRITICAL_SECTION critical_section_;
-
- BluetoothAdapter& bluetooth_adapter_;
-
- BluetoothAdapter::ScanMode scan_mode_;
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_MEDIUM_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_medium_test.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_medium_test.cc
deleted file mode 100644
index 63d3b01b251..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_medium_test.cc
+++ /dev/null
@@ -1,189 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/windows/bluetooth_classic_medium.h"
-
-#include <synchapi.h>
-#include <windows.h>
-
-#include <string>
-
-#include "absl/strings/str_format.h"
-#include "platform/api/bluetooth_adapter.h"
-#include "platform/api/bluetooth_classic.h"
-#include "platform/impl/windows/bluetooth_adapter.h"
-#include "platform/impl/windows/bluetooth_classic_device.h"
-#include "platform/impl/windows/generated/winrt/Windows.Devices.Bluetooth.Rfcomm.h"
-
-#include "gtest/gtest.h"
-
-// TODO(jfcarroll): Find a way to mock winrt components in order to properly
-// unit test this. Once that's done, unit tests can be written, in a later C/L.
-//
-// CAUTION: THIS IS NOT A REAL TEST, THIS EXERCISES THE SCANNER, IT MAY NOT
-// STOP/HANG AND IS INTENDED SOLELY FOR DEBUG AND DEMONSTRATION PURPOSES. DO NOT
-// ATTEMPT TO BUILD AND RUN THIS TEST ON GOOGLE3 YOU HAVE BEEN WARNED
-
-using location::nearby::windows::BluetoothDevice;
-
-typedef std::map<const std::string, location::nearby::api::BluetoothDevice*>
- DeviceMap;
-
-class BluetoothClassicMediumTests : public testing::Test {
- protected:
- static void device_discovered_cb(
- location::nearby::api::BluetoothDevice& device) {
- const std::string address = device.GetMacAddress();
-
- std::map<std::string,
- location::nearby::api::BluetoothDevice*>::const_iterator it =
- deviceList.find(address);
-
- std::string buffer =
- absl::StrFormat("processing device %s : ", address.c_str());
-
- OutputDebugStringA(buffer.c_str());
-
- if (it == deviceList.end()) {
- buffer = absl::StrFormat("adding device %s\n", address.c_str());
-
- OutputDebugStringA(buffer.c_str());
- deviceList[device.GetMacAddress()] = &device;
- }
- }
-
- static void device_name_changed_cb(
- location::nearby::api::BluetoothDevice& device) {}
-
- static void device_lost_cb(location::nearby::api::BluetoothDevice& device) {
- deviceList.erase(device.GetMacAddress());
- }
-
- int callcount = 0;
- static inline DeviceMap deviceList = {};
-};
-
-#ifdef TESTING_LOCALLY
-TEST_F(BluetoothClassicMediumTests, ManualTest) {
- auto bluetoothAdapter = location::nearby::windows::BluetoothAdapter();
-
- std::string bluetoothAdapterName = bluetoothAdapter.GetName();
- bluetoothAdapter.SetName("BluetoothTestName");
- bluetoothAdapterName = bluetoothAdapter.GetName();
- bluetoothAdapter.SetName("");
- bluetoothAdapterName = bluetoothAdapter.GetName();
-
- std::unique_ptr<location::nearby::windows::BluetoothClassicMedium> bcm =
- std::make_unique<location::nearby::windows::BluetoothClassicMedium>(
- bluetoothAdapter);
-
- bluetoothAdapter.SetScanMode(location::nearby::windows::BluetoothAdapter::
- ScanMode::kConnectableDiscoverable);
-
- auto mode = bluetoothAdapter.GetScanMode();
-
- bcm->StartDiscovery(
- location::nearby::api::BluetoothClassicMedium::DiscoveryCallback{
- .device_discovered_cb = device_discovered_cb,
- .device_name_changed_cb = device_name_changed_cb,
- .device_lost_cb = device_lost_cb,
- });
-
- Sleep(30000);
-
- auto currentDevice = deviceList["DC:DC:E2:F2:B5:99"];
- auto serviceUuid = winrt::to_string(
- winrt::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId::SerialPort()
- .AsString());
-
- location::nearby::CancellationFlag cancellationFlag;
- bcm->ConnectToService(*currentDevice,
- // "a82efa21-ae5c-3dde-9bbc-f16da7b16c5a",
- "00001101-0000-1000-8000-00805F9B34FB",
- &cancellationFlag);
-
- EXPECT_EQ(1, 1);
- EXPECT_TRUE(true);
-}
-#endif
-TEST_F(BluetoothClassicMediumTests, ConnectToServiceNullUuid) {
- // Arrange
- auto bluetoothAdapter = location::nearby::windows::BluetoothAdapter();
-
- std::unique_ptr<location::nearby::windows::BluetoothClassicMedium>
- bluetoothClassicMedium =
- std::make_unique<location::nearby::windows::BluetoothClassicMedium>(
- bluetoothAdapter);
-
- location::nearby::windows::BluetoothDevice bluetoothDevice =
- location::nearby::windows::BluetoothDevice(
- std::string("1D:EA:DB:EE:B9:00"));
- location::nearby::CancellationFlag cancellationFlag;
-
- auto bluetoothClassicMediumImpl = bluetoothClassicMedium.get();
-
- // Act
- auto asyncResult = bluetoothClassicMediumImpl->ConnectToService(
- bluetoothDevice, std::string(), &cancellationFlag);
-
- // Assert
- EXPECT_TRUE(asyncResult.get() == nullptr);
-}
-
-TEST_F(BluetoothClassicMediumTests, ConnectToServiceNullCancellationFlag) {
- // Arrange
- auto bluetoothAdapter = location::nearby::windows::BluetoothAdapter();
-
- std::unique_ptr<location::nearby::windows::BluetoothClassicMedium>
- bluetoothClassicMedium =
- std::make_unique<location::nearby::windows::BluetoothClassicMedium>(
- bluetoothAdapter);
-
- location::nearby::windows::BluetoothDevice bluetoothDevice =
- location::nearby::windows::BluetoothDevice(
- std::string("1D:EA:DB:EE:B9:00"));
-
- auto bluetoothClassicMediumImpl = bluetoothClassicMedium.get();
-
- // Act
- auto asyncResult = bluetoothClassicMediumImpl->ConnectToService(
- bluetoothDevice, std::string("test service"), nullptr);
-
- // Assert
- EXPECT_TRUE(asyncResult.get() == nullptr);
-}
-
-TEST_F(BluetoothClassicMediumTests, ConnectToServiceWithInvalidServiceUuid) {
- // Arrange
- auto bluetoothAdapter = location::nearby::windows::BluetoothAdapter();
-
- std::unique_ptr<location::nearby::windows::BluetoothClassicMedium>
- bluetoothClassicMedium =
- std::make_unique<location::nearby::windows::BluetoothClassicMedium>(
- bluetoothAdapter);
-
- location::nearby::windows::BluetoothDevice bluetoothDevice =
- location::nearby::windows::BluetoothDevice(
- std::string("1D:EA:DB:EE:B9:00"));
- location::nearby::CancellationFlag cancellationFlag;
-
- auto bluetoothClassicMediumImpl = bluetoothClassicMedium.get();
-
- // Act
- auto asyncResult = bluetoothClassicMediumImpl->ConnectToService(
- bluetoothDevice, std::string("test service"), &cancellationFlag);
-
- // Assert
- EXPECT_TRUE(asyncResult.get() == nullptr);
-}
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_server_socket.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_server_socket.cc
deleted file mode 100644
index e83394b6db4..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_server_socket.cc
+++ /dev/null
@@ -1,191 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/windows/bluetooth_classic_server_socket.h"
-
-#include <codecvt>
-#include <locale>
-#include <string>
-
-#include "platform/impl/windows/bluetooth_classic_socket.h"
-#include "platform/impl/windows/generated/winrt/Windows.Foundation.Collections.h"
-#include "platform/impl/windows/utils.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-BluetoothServerSocket::BluetoothServerSocket(const std::string service_name,
- const std::string service_uuid)
- : radio_discoverable_(false),
- service_name_(service_name),
- service_uuid_(service_uuid),
- rfcomm_provider_(nullptr) {
- InitializeCriticalSection(&critical_section_);
-}
-
-BluetoothServerSocket::~BluetoothServerSocket() {}
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html#accept()
-//
-// Blocks until either:
-// - at least one incoming connection request is available, or
-// - ServerSocket is closed.
-// On success, returns connected socket, ready to exchange data.
-// Returns nullptr on error.
-// Once error is reported, it is permanent, and ServerSocket has to be closed.
-std::unique_ptr<api::BluetoothSocket> BluetoothServerSocket::Accept() {
- while (bluetooth_sockets_.empty() && !closed_) {
- Sleep(1000);
- }
-
- EnterCriticalSection(&critical_section_);
- if (!closed_) {
- std::unique_ptr<BluetoothSocket> bluetoothSocket =
- std::move(bluetooth_sockets_.front());
- bluetooth_sockets_.pop();
- LeaveCriticalSection(&critical_section_);
-
- return std::move(bluetoothSocket);
- } else {
- bluetooth_sockets_ = {};
- LeaveCriticalSection(&critical_section_);
- }
-
- return nullptr;
-}
-
-Exception BluetoothServerSocket::StartListening(bool radioDiscoverable) {
- EnterCriticalSection(&critical_section_);
-
- radio_discoverable_ = radioDiscoverable;
-
- // Create the StreamSocketListener
- stream_socket_listener_ = StreamSocketListener();
-
- // Configure control property
- stream_socket_listener_.Control().QualityOfService(
- SocketQualityOfService::LowLatency);
-
- stream_socket_listener_.Control().KeepAlive(true);
-
- // Note From the perspective of a StreamSocket, a Parallel Patterns Library
- // (PPL) completion handler is done executing (and the socket is eligible for
- // disposal) before the continuation body runs. So, to keep your socket from
- // being disposed if you want to use it inside a continuation, you'll need to
- // use one of the techniques described in References to StreamSockets in C++
- // PPL continuations.
- // Assign ConnectionReceived event to event handler on the server socket
- stream_socket_listener_.ConnectionReceived(
- [this](StreamSocketListener streamSocketListener,
- StreamSocketListenerConnectionReceivedEventArgs args) {
- EnterCriticalSection(&critical_section_);
- if (!closed_) {
- this->bluetooth_sockets_.push(
- std::make_unique<BluetoothSocket>(args.Socket()));
- }
- LeaveCriticalSection(&critical_section_);
- });
-
- try {
- auto rfcommProviderRef =
- RfcommServiceProvider::CreateAsync(
- RfcommServiceId::FromUuid(winrt::guid(service_uuid_)))
- .get();
-
- rfcomm_provider_ = rfcommProviderRef;
-
- stream_socket_listener_
- .BindServiceNameAsync(
- winrt::to_hstring(rfcomm_provider_.ServiceId().AsString()),
- SocketProtectionLevel::PlainSocket)
- .get();
-
- // Set the SDP attributes and start Bluetooth advertising
- InitializeServiceSdpAttributes(rfcomm_provider_, service_name_);
- } catch (std::exception exception) {
- // We will log and eat the exception since the caller
- // expects nullptr if it fails
- NEARBY_LOGS(ERROR) << __func__ << ": Exception setting up for listen: "
- << exception.what();
-
- LeaveCriticalSection(&critical_section_);
-
- return {Exception::kFailed};
- }
-
- StartAdvertising();
-
- LeaveCriticalSection(&critical_section_);
-
- return {Exception::kSuccess};
-}
-
-Exception BluetoothServerSocket::StartAdvertising() {
- try {
- rfcomm_provider_.StartAdvertising(stream_socket_listener_,
- radio_discoverable_);
- } catch (std::exception exception) {
- // We will log and eat the exception since the caller
- // expects nullptr if it fails
- NEARBY_LOGS(ERROR) << __func__ << ": Exception calling StartAdvertising: "
- << exception.what();
-
- LeaveCriticalSection(&critical_section_);
-
- return {Exception::kFailed};
- }
-
- return {Exception::kSuccess};
-}
-
-void BluetoothServerSocket::StopAdvertising() {
- rfcomm_provider_.StopAdvertising();
-}
-
-void BluetoothServerSocket::InitializeServiceSdpAttributes(
- RfcommServiceProvider rfcommProvider, std::string service_name) {
- auto sdpWriter = DataWriter();
-
- // Write the Service Name Attribute.
- sdpWriter.WriteByte(Constants::SdpServiceNameAttributeType);
-
- // The length of the UTF-8 encoded Service Name SDP Attribute.
- sdpWriter.WriteByte(service_name.size());
-
- // The UTF-8 encoded Service Name value.
- sdpWriter.UnicodeEncoding(UnicodeEncoding::Utf8);
- sdpWriter.WriteString(winrt::to_hstring(service_name));
-
- // Set the SDP Attribute on the RFCOMM Service Provider.
- rfcommProvider.SdpRawAttributes().Insert(Constants::SdpServiceNameAttributeId,
- sdpWriter.DetachBuffer());
-}
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html#close()
-//
-// Returns Exception::kIo on error, Exception::kSuccess otherwise.
-Exception BluetoothServerSocket::Close() {
- EnterCriticalSection(&critical_section_);
- closed_ = true;
- bluetooth_sockets_ = {};
- rfcomm_provider_.StopAdvertising();
- LeaveCriticalSection(&critical_section_);
-
- return {Exception::kSuccess};
-}
-} // namespace windows
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_server_socket.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_server_socket.h
deleted file mode 100644
index b8712b505d8..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_server_socket.h
+++ /dev/null
@@ -1,129 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_SERVER_SOCKET_H_
-#define PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_SERVER_SOCKET_H_
-
-#include <Windows.h>
-
-#include <queue>
-
-#include "platform/api/bluetooth_classic.h"
-#include "platform/impl/windows/bluetooth_classic_socket.h"
-#include "platform/impl/windows/generated/winrt/Windows.Devices.Bluetooth.Rfcomm.h"
-#include "platform/impl/windows/generated/winrt/Windows.Foundation.h"
-#include "platform/impl/windows/generated/winrt/Windows.Networking.Sockets.h"
-#include "platform/impl/windows/generated/winrt/base.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-// Supports listening for an incoming network connection using Bluetooth RFCOMM.
-// https://docs.microsoft.com/en-us/uwp/api/windows.networking.sockets.streamsocketlistener?view=winrt-20348
-using winrt::Windows::Networking::Sockets::StreamSocketListener;
-
-// Provides data for a ConnectionReceived event on a StreamSocketListener
-// object.
-// https://docs.microsoft.com/en-us/uwp/api/windows.networking.sockets.streamsocketlistenerconnectionreceivedeventargs?view=winrt-20348
-using winrt::Windows::Networking::Sockets::
- StreamSocketListenerConnectionReceivedEventArgs;
-
-// Represents an asynchronous action.
-// https://docs.microsoft.com/en-us/uwp/api/windows.foundation.iasyncaction?view=winrt-20348
-using winrt::Windows::Foundation::IAsyncAction;
-
-// Specifies the quality of service for a StreamSocket object.
-// https://docs.microsoft.com/en-us/uwp/api/windows.networking.sockets.socketqualityofservice?view=winrt-20348
-using winrt::Windows::Networking::Sockets::SocketQualityOfService;
-
-// Represents an instance of a local RFCOMM service.
-// https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.rfcomm.rfcommserviceprovider?view=winrt-20348
-using winrt::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceProvider;
-
-// Represents an RFCOMM service ID.
-// https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.rfcomm.rfcommserviceid?view=winrt-20348
-using winrt::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId;
-
-// Writes data to an output stream.
-// https://docs.microsoft.com/en-us/uwp/api/windows.storage.streams.datawriter?view=winrt-20348
-using winrt::Windows::Storage::Streams::DataWriter;
-
-// Specifies the type of character encoding for a stream.
-// https://docs.microsoft.com/en-us/uwp/api/windows.storage.streams.unicodeencoding?view=winrt-20348
-using winrt::Windows::Storage::Streams::UnicodeEncoding;
-
-// Specifies the level of encryption to use on a StreamSocket object.
-// https://docs.microsoft.com/en-us/uwp/api/windows.networking.sockets.socketprotectionlevel?view=winrt-22000
-using winrt::Windows::Networking::Sockets::SocketProtectionLevel;
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html.
-class BluetoothServerSocket : public api::BluetoothServerSocket {
- public:
- BluetoothServerSocket(const std::string service_name,
- const std::string service_uuid);
-
- ~BluetoothServerSocket() override;
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html#accept()
- //
- // Blocks until either:
- // - at least one incoming connection request is available, or
- // - ServerSocket is closed.
- // On success, returns connected socket, ready to exchange data.
- // Returns nullptr on error.
- // Once error is reported, it is permanent, and ServerSocket has to be closed.
- std::unique_ptr<api::BluetoothSocket> Accept() override;
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html#close()
- //
- // Returns Exception::kIo on error, Exception::kSuccess otherwise.
- Exception Close() override;
-
- Exception StartListening(bool radioDiscoverable);
-
- void SetScanMode(bool radioDiscoverable) {
- StopAdvertising();
- radio_discoverable_ = radioDiscoverable;
- StartAdvertising();
- }
-
- private:
- void InitializeServiceSdpAttributes(RfcommServiceProvider rfcommProvider,
- std::string service_name);
-
- Exception StartAdvertising();
- void StopAdvertising();
-
- // This is used to store sockets in case Accept hasn't been called. Once
- // Accept has been called the socket is popped from the queue and returned to
- // the caller
- std::queue<std::unique_ptr<BluetoothSocket>> bluetooth_sockets_;
-
- StreamSocketListener stream_socket_listener_;
- winrt::event_token listener_token_;
- CRITICAL_SECTION critical_section_;
- bool closed_ = false;
- bool radio_discoverable_;
-
- const std::string service_name_;
- const std::string service_uuid_;
-
- RfcommServiceProvider rfcomm_provider_;
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-#endif // PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_SERVER_SOCKET_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_socket.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_socket.cc
deleted file mode 100644
index 3ce04b300e3..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_socket.cc
+++ /dev/null
@@ -1,194 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/windows/bluetooth_classic_socket.h"
-
-#include "platform/base/logging.h"
-#include "platform/impl/windows/generated/winrt/Windows.Networking.Sockets.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-BluetoothSocket::BluetoothSocket(StreamSocket streamSocket)
- : windows_socket_(streamSocket) {
- bluetooth_device_ = std::make_unique<BluetoothDevice>(
- winrt::Windows::Devices::Bluetooth::BluetoothDevice::FromHostNameAsync(
- windows_socket_.Information().RemoteHostName())
- .get());
- input_stream_ =
- std::make_unique<BluetoothInputStream>(windows_socket_.InputStream());
- output_stream_ =
- std::make_unique<BluetoothOutputStream>(windows_socket_.OutputStream());
-}
-
-BluetoothSocket::BluetoothSocket() {}
-
-BluetoothSocket::~BluetoothSocket() {}
-
-// NOTE:
-// It is an undefined behavior if GetInputStream() or GetOutputStream() is
-// called for a not-connected BluetoothSocket, i.e. any object that is not
-// returned by BluetoothClassicMedium::ConnectToService() for client side or
-// BluetoothServerSocket::Accept() for server side of connection.
-// Returns the InputStream of this connected BluetoothSocket.
-InputStream& BluetoothSocket::GetInputStream() { return *input_stream_.get(); }
-
-// Returns the OutputStream of this connected BluetoothSocket.
-OutputStream& BluetoothSocket::GetOutputStream() {
- return *output_stream_.get();
-}
-
-// Closes both input and output streams, marks Socket as closed.
-// After this call object should be treated as not connected.
-// Returns Exception::kIo on error, Exception::kSuccess otherwise.
-Exception BluetoothSocket::Close() {
- // The Close method aborts any pending operations and releases all unmanaged
- // resources associated with the StreamSocket object, including the Input and
- // Output streams
- windows_socket_.Close();
- return {Exception::kSuccess};
-}
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#getRemoteDevice()
-// Returns valid BluetoothDevice pointer if there is a connection, and
-// nullptr otherwise.
-api::BluetoothDevice* BluetoothSocket::GetRemoteDevice() {
- return bluetooth_device_.get();
-}
-
-// Starts an asynchronous operation on a StreamSocket object to connect to a
-// remote network destination specified by a remote hostname and a remote
-// service name.
-void BluetoothSocket::Connect(HostName connectionHostName,
- winrt::hstring connectionServiceName) {
- windows_socket_ = winrt::Windows::Networking::Sockets::StreamSocket();
-
- // https://docs.microsoft.com/en-us/uwp/api/windows.networking.sockets.streamsocket.connectasync?view=winrt-20348
- windows_socket_.ConnectAsync(connectionHostName, connectionServiceName).get();
-
- auto info = windows_socket_.Information();
- auto hostName = info.RemoteHostName();
-
- bluetooth_device_ = std::make_unique<BluetoothDevice>(
- winrt::Windows::Devices::Bluetooth::BluetoothDevice::FromHostNameAsync(
- windows_socket_.Information().RemoteHostName())
- .get());
-
- input_stream_ =
- std::make_unique<BluetoothInputStream>(windows_socket_.InputStream());
- output_stream_ =
- std::make_unique<BluetoothOutputStream>(windows_socket_.OutputStream());
-}
-
-BluetoothSocket::BluetoothInputStream::BluetoothInputStream(
- IInputStream stream) {
- winrt_stream_ = stream;
-}
-
-ExceptionOr<ByteArray> BluetoothSocket::BluetoothInputStream::Read(
- std::int64_t size) {
- if (winrt_stream_ == nullptr) {
- return {Exception::kFailed};
- }
-
- Buffer buffer = Buffer(size);
-
- winrt_stream_.ReadAsync(buffer, size, InputStreamOptions::Partial).get();
-
- DataReader dataReader = DataReader::FromBuffer(buffer);
-
- ByteArray data((char*)buffer.data(), buffer.Length());
-
- return ExceptionOr(data);
-}
-
-IAsyncAction BluetoothSocket::CancelIOAsync() {
- // Cancels pending reads and writes over a StreamSocket object.
- // https://docs.microsoft.com/en-us/uwp/api/windows.networking.sockets.streamsocket.cancelioasync?view=winrt-20348
- return windows_socket_.CancelIOAsync();
-}
-
-Exception BluetoothSocket::BluetoothInputStream::Close() {
- if (winrt_stream_ == nullptr) {
- return {Exception::kSuccess}; // Already closed, don't error out
- }
-
- try {
- winrt_stream_.Close();
- winrt_stream_ = nullptr;
- } catch (std::exception exception) {
- return {Exception::kFailed};
- }
-
- return {Exception::kSuccess};
-}
-
-BluetoothSocket::BluetoothOutputStream::BluetoothOutputStream(
- IOutputStream stream) {
- winrt_stream_ = stream;
-}
-
-Exception BluetoothSocket::BluetoothOutputStream::Write(const ByteArray& data) {
- Buffer buffer = Buffer(data.size());
- std::memcpy(buffer.data(), data.data(), data.size());
- buffer.Length(data.size());
- if (winrt_stream_ == nullptr) {
- return {Exception::kFailed};
- }
-
- try {
- auto hresult = winrt_stream_.WriteAsync(buffer).get();
- } catch (winrt::hresult_error const& ex) {
- NEARBY_LOGS(ERROR) << __func__ << ": winrt exception: " << ex.code() << ": "
- << winrt::to_string(ex.message());
-
- return {Exception::kFailed};
- }
-
- return {Exception::kSuccess};
-}
-
-Exception BluetoothSocket::BluetoothOutputStream::Flush() {
- if (winrt_stream_ == nullptr) {
- return {Exception::kFailed};
- }
-
- try {
- winrt_stream_.FlushAsync().get();
- } catch (std::exception exception) {
- return {Exception::kFailed};
- }
-
- return {Exception::kSuccess};
-}
-
-Exception BluetoothSocket::BluetoothOutputStream::Close() {
- if (winrt_stream_ == nullptr) {
- return {Exception::kSuccess}; // Already closed, don't error out
- }
-
- try {
- winrt_stream_.Close();
- winrt_stream_ = nullptr;
- } catch (std::exception exception) {
- return {Exception::kFailed};
- }
-
- return {Exception::kSuccess};
-}
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_socket.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_socket.h
deleted file mode 100644
index 57dbf57099e..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/bluetooth_classic_socket.h
+++ /dev/null
@@ -1,139 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_SOCKET_H_
-#define PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_SOCKET_H_
-
-#include "platform/api/bluetooth_classic.h"
-#include "platform/impl/windows/bluetooth_classic_device.h"
-#include "platform/impl/windows/generated/winrt/Windows.Foundation.h"
-#include "platform/impl/windows/generated/winrt/Windows.Networking.Sockets.h"
-#include "platform/impl/windows/generated/winrt/Windows.Storage.Streams.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-// Provides data for a hostname or an IP address.
-// https://docs.microsoft.com/en-us/uwp/api/windows.networking.hostname?view=winrt-20348
-using winrt::Windows::Networking::HostName;
-
-// Supports network communication using a stream socket over Bluetooth RFCOMM.
-// https://docs.microsoft.com/en-us/uwp/api/windows.networking.sockets.streamsocket?view=winrt-20348
-using winrt::Windows::Networking::Sockets::IStreamSocket;
-using winrt::Windows::Networking::Sockets::StreamSocket;
-
-// Provides a default implementation of the IBuffer interface and its related
-// interfaces.
-// https://docs.microsoft.com/en-us/uwp/api/windows.storage.streams.buffer?view=winrt-20348
-using winrt::Windows::Storage::Streams::Buffer;
-
-// Represents a sequential stream of bytes to be read.
-// https://docs.microsoft.com/en-us/uwp/api/windows.storage.streams.iinputstream?view=winrt-20348
-using winrt::Windows::Storage::Streams::IInputStream;
-
-// Represents a sequential stream of bytes to be written.
-// https://docs.microsoft.com/en-us/uwp/api/windows.storage.streams.ioutputstream?view=winrt-20348
-using winrt::Windows::Storage::Streams::IOutputStream;
-
-// Specifies the read options for an input stream.
-// This enumeration has a FlagsAttribute attribute that allows a bitwise
-// combination of its member values.
-// https://docs.microsoft.com/en-us/uwp/api/windows.storage.streams.inputstreamoptions?view=winrt-20348
-using winrt::Windows::Storage::Streams::InputStreamOptions;
-
-// Reads data from an input stream.
-// https://docs.microsoft.com/en-us/uwp/api/windows.storage.streams.datareader?view=winrt-20348
-using winrt::Windows::Storage::Streams::DataReader;
-
-// Represents an asynchronous action.
-// https://docs.microsoft.com/en-us/uwp/api/windows.foundation.iasyncaction?view=winrt-20348
-using winrt::Windows::Foundation::IAsyncAction;
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html.
-class BluetoothSocket : public api::BluetoothSocket {
- public:
- BluetoothSocket();
-
- BluetoothSocket(StreamSocket streamSocket);
-
- ~BluetoothSocket() override;
-
- // NOTE:
- // It is an undefined behavior if GetInputStream() or GetOutputStream() is
- // called for a not-connected BluetoothSocket, i.e. any object that is not
- // returned by BluetoothClassicMedium::ConnectToService() for client side or
- // BluetoothServerSocket::Accept() for server side of connection.
-
- // Returns the InputStream of this connected BluetoothSocket.
- InputStream& GetInputStream() override;
-
- // Returns the OutputStream of this connected BluetoothSocket.
- OutputStream& GetOutputStream() override;
-
- // Closes both input and output streams, marks Socket as closed.
- // After this call object should be treated as not connected.
- // Returns Exception::kIo on error, Exception::kSuccess otherwise.
- Exception Close() override;
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#getRemoteDevice()
- // Returns valid BluetoothDevice pointer if there is a connection, and
- // nullptr otherwise.
- api::BluetoothDevice* GetRemoteDevice() override;
-
- // Connect asynchronously to the target remote device
- void Connect(HostName connectionHostName,
- winrt::hstring connectionServiceName);
-
- IAsyncAction CancelIOAsync();
-
- private:
- class BluetoothInputStream : public InputStream {
- public:
- BluetoothInputStream(IInputStream stream);
- ~BluetoothInputStream() override = default;
-
- ExceptionOr<ByteArray> Read(std::int64_t size) override;
- Exception Close() override;
-
- private:
- IInputStream winrt_stream_;
- };
-
- class BluetoothOutputStream : public OutputStream {
- public:
- BluetoothOutputStream(IOutputStream stream);
- ~BluetoothOutputStream() override = default;
-
- Exception Write(const ByteArray& data) override;
- Exception Flush() override;
-
- Exception Close() override;
-
- private:
- IOutputStream winrt_stream_;
- };
-
- std::unique_ptr<BluetoothInputStream> input_stream_;
- std::unique_ptr<BluetoothOutputStream> output_stream_;
-
- StreamSocket windows_socket_;
- std::unique_ptr<BluetoothDevice> bluetooth_device_;
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_SOCKET_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/cancelable.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/cancelable.h
deleted file mode 100644
index 1f9b2644344..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/cancelable.h
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_CANCELABLE_H_
-#define PLATFORM_IMPL_WINDOWS_CANCELABLE_H_
-
-#include <windows.h>
-
-#include "platform/api/cancelable.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-// An interface to provide a cancellation mechanism for objects that represent
-// long-running operations.
-class Cancelable : public api::Cancelable {
- public:
- Cancelable(HANDLE handle) : handle_(handle) {}
- ~Cancelable() override = default;
-
- bool Cancel() override {
- if (CancelWaitableTimer(handle_)) {
- CloseHandle(handle_);
- return true;
- }
-
- return false;
- };
-
- private:
- HANDLE handle_;
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_WINDOWS_CANCELABLE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/condition_variable.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/condition_variable.h
deleted file mode 100644
index b28c0b227a7..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/condition_variable.h
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2021 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-#ifndef PLATFORM_IMPL_WINDOWS_CONDITION_VARIABLE_H_
-#define PLATFORM_IMPL_WINDOWS_CONDITION_VARIABLE_H_
-#include <windows.h>
-#include <stdio.h>
-#include <synchapi.h>
-
-#include <mutex> // NOLINT
-
-#include "platform/api/condition_variable.h"
-#include "platform/impl/windows/mutex.h"
-#include "platform/public/mutex.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-class ConditionVariable : public api::ConditionVariable {
- public:
- explicit ConditionVariable(api::Mutex* mutex)
- : mutex_(&(static_cast<windows::Mutex*>(mutex))->mutex_) {}
- ~ConditionVariable() override = default;
-
- Exception Wait() override {
- cond_var_.Wait(mutex_);
- return {Exception::kSuccess};
- }
-
- Exception Wait(absl::Duration timeout) override {
- cond_var_.WaitWithTimeout(mutex_, timeout);
- return {Exception::kSuccess};
- }
-
- void Notify() override { cond_var_.SignalAll(); }
-
- private:
- absl::Mutex* mutex_;
- absl::CondVar cond_var_;
-};
-} // namespace windows
-} // namespace nearby
-} // namespace location
-#endif // PLATFORM_IMPL_WINDOWS_CONDITION_VARIABLE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/condition_variable_test.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/condition_variable_test.cc
deleted file mode 100644
index ccad7ac5312..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/condition_variable_test.cc
+++ /dev/null
@@ -1,104 +0,0 @@
-// Copyright 2021 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/windows/condition_variable.h"
-
-#include <future> // NOLINT
-
-#include "absl/time/clock.h"
-#include "platform/base/exception.h"
-#include "platform/impl/windows/mutex.h"
-
-#include "gtest/gtest.h"
-
-class ConditionVariableTests : public testing::Test {
- public:
- class ConditionVariableTest {
- public:
- ConditionVariableTest() {}
-
- std::future<bool> WaitForEvent(bool timedWait, // NOLINT
- const absl::Duration* timeout) {
- return std::async(
- std::launch::async,
- [this, timedWait, timeout]() mutable {
- std::thread::id currentThread = std::this_thread::get_id();
-
- if (timedWait == true) {
- auto result = this->condition_variable_actual_.Wait(*timeout);
- if (result.value == location::nearby::Exception::kSuccess) {
- return true;
- } else {
- return false;
- }
- } else {
- this->condition_variable_actual_.Wait();
- }
- return true;
- });
- }
-
- void PostEvent() {
- std::lock_guard<std::mutex> guard(mutex_actual_.GetWindowsMutex());
- condition_variable_actual_.Notify();
- }
-
- private:
- location::nearby::windows::Mutex mutex_actual_ =
- location::nearby::windows::Mutex(
- location::nearby::windows::Mutex::Mode::kRegular);
- location::nearby::windows::Mutex& mutex_ = mutex_actual_;
- location::nearby::windows::ConditionVariable condition_variable_actual_ =
- location::nearby::windows::ConditionVariable(&mutex_);
- location::nearby::windows::ConditionVariable& condition_variable_ =
- condition_variable_actual_;
- };
-};
-
-TEST_F(ConditionVariableTests, SuccessfulCreation) {
- // Arrange
- ConditionVariableTest conditionVariableTest;
-
- auto result = conditionVariableTest.WaitForEvent(false, nullptr);
-
- Sleep(1);
-
- // Act
- conditionVariableTest.PostEvent();
-
- // Assert
- ASSERT_TRUE(result.get());
-}
-
-TEST_F(ConditionVariableTests, TimedCreation) {
- // Arrange
- ConditionVariableTest conditionVariableTest;
- const absl::Duration duration = absl::Milliseconds(100);
-
- // Act
- auto result = conditionVariableTest.WaitForEvent(true, &duration);
-
- // Assert
- ASSERT_FALSE(result.get()); // Timed out
-
- // Act
- result = conditionVariableTest.WaitForEvent(true, &duration);
-
- Sleep(1);
-
- conditionVariableTest.PostEvent();
-
- // Assert
- ASSERT_TRUE(result.get()); // Didn't timeout
-}
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/count_down_latch_test.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/count_down_latch_test.cc
deleted file mode 100644
index ace8ee02e51..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/count_down_latch_test.cc
+++ /dev/null
@@ -1,186 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/shared/count_down_latch.h"
-
-#include <Windows.h>
-
-#include "gtest/gtest.h"
-#include "platform/api/platform.h"
-
-class CountDownLatchTests : public testing::Test {
- public:
- class TestData {
- public:
- std::unique_ptr<location::nearby::api::CountDownLatch>& countDownLatch;
- LONG volatile& count;
- };
-
- class CountDownLatchTest {
- public:
- static DWORD ThreadProcCountDown(LPVOID lpParam) {
- TestData* testData = static_cast<TestData*>(lpParam);
-
- Sleep(1);
-
- InterlockedIncrement(&testData->count);
- testData->countDownLatch->CountDown();
- return 0;
- }
-
- static DWORD ThreadProcAwait(LPVOID lpParam) {
- TestData* testData = static_cast<TestData*>(lpParam);
-
- Sleep(1);
-
- testData->countDownLatch->Await();
- InterlockedIncrement(&testData->count);
-
- return 0;
- }
- };
-
- CountDownLatchTests() {}
-};
-
-TEST_F(CountDownLatchTests, CountDownLatchAwaitSucceeds) {
- // Arrange
- LONG volatile count = 0;
-
- std::unique_ptr<location::nearby::api::CountDownLatch> countDownLatch =
- location::nearby::api::ImplementationPlatform::CreateCountDownLatch(3);
-
- HANDLE hThreads[3];
- DWORD dwThreadID;
-
- TestData testData{countDownLatch, count};
-
- // Setup 3 threads
- for (int i = 0; i < 3; i++) {
- // TODO: More complex scenarios may require use of a parameter
- // to the thread procedure, such as an event per thread to
- // be used for synchronization.
- hThreads[i] = CreateThread(
- NULL, // default security
- 0, // default stack size
- CountDownLatchTest::ThreadProcCountDown, // name of the thread function
- &testData, // no thread parameters
- 0, // default startup flags
- &dwThreadID);
-
- EXPECT_TRUE(hThreads[i] != NULL);
- }
-
- // Act
- location::nearby::Exception result = countDownLatch->Await();
-
- //
- // Assert
- EXPECT_EQ(result.value, location::nearby::Exception::kSuccess);
- EXPECT_EQ(count, 3);
-}
-
-TEST_F(CountDownLatchTests, CountDownLatchAwaitTimeoutTimesOut) {
- // Arrange
- LONG volatile count = 0;
-
- std::unique_ptr<location::nearby::api::CountDownLatch> countDownLatch =
- location::nearby::api::ImplementationPlatform::CreateCountDownLatch(3);
-
- // Act
- location::nearby::ExceptionOr<bool> result =
- countDownLatch->Await(absl::Milliseconds(5));
-
- Sleep(40);
-
- // Assert
- EXPECT_FALSE(result.GetResult());
- // TODO(jfcarroll)I think there's a bug in the shared version of this, it's
- // not returning a timeout exception, need to look at it some more.
- // EXPECT_EQ(result.GetException().value,
- // location::nearby::Exception::kTimeout);
-}
-
-TEST_F(CountDownLatchTests, CountDownLatchAwaitNoTimeoutSucceeds) {
- // Arrange
- LONG volatile count = 0;
-
- std::unique_ptr<location::nearby::api::CountDownLatch> countDownLatch =
- location::nearby::api::ImplementationPlatform::CreateCountDownLatch(3);
-
- TestData testData{countDownLatch, count};
-
- HANDLE hThreads[3];
- DWORD dwThreadID;
-
- // Setup 3 threads
- for (int i = 0; i < 3; i++) {
- // TODO: More complex scenarios may require use of a parameter
- // to the thread procedure, such as an event per thread to
- // be used for synchronization.
- hThreads[i] = CreateThread(
- NULL, // default security
- 0, // default stack size
- CountDownLatchTest::ThreadProcCountDown, // name of the thread function
- &testData, // no thread parameters
- 0, // default startup flags
- &dwThreadID);
-
- EXPECT_TRUE(hThreads[i] != NULL);
- }
-
- WaitForMultipleObjects(3, hThreads, true, INFINITE);
- // Act
- location::nearby::ExceptionOr<bool> result =
- countDownLatch->Await(absl::Milliseconds(100));
-
- // Assert
- EXPECT_TRUE(result.GetResult());
- EXPECT_EQ(result.GetException().value, location::nearby::Exception::kSuccess);
- EXPECT_EQ(count, 3);
-}
-
-TEST_F(CountDownLatchTests, CountDownLatchCountDownBeforeAwaitSucceeds) {
- // Arrange
- LONG volatile count = 0;
- std::unique_ptr<location::nearby::api::CountDownLatch> countDownLatch =
- location::nearby::api::ImplementationPlatform::CreateCountDownLatch(1);
-
- HANDLE hThread;
- DWORD dwThreadID;
-
- TestData testData{countDownLatch, count};
-
- hThread = CreateThread(
- NULL, // default security
- 0, // default stack size
- CountDownLatchTest::ThreadProcAwait, // name of the thread function
- &testData, // no thread parameters
- 0, // default startup flags
- &dwThreadID);
-
- EXPECT_TRUE(hThread != NULL);
-
- // Act
- countDownLatch->CountDown(); // This countdown occurs before the thread has a
- // chance to run
-
- if (hThread != NULL) {
- WaitForSingleObject(hThread,
- INFINITE); // This will wait till the thread exits
- }
-
- // Assert
- EXPECT_EQ(count, 1);
-}
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/crypto.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/crypto.cc
deleted file mode 100644
index 5904d04d815..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/crypto.cc
+++ /dev/null
@@ -1,58 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/api/crypto.h"
-
-#include <cstdint>
-#include <string>
-
-#include "absl/strings/string_view.h"
-#include "platform/base/byte_array.h"
-#if defined NEARBY_WINDOWS_DLL
-#include "openssl/boringssl/src/include/openssl/digest.h"
-#else
-#include "openssl/digest.h"
-#endif
-
-// Function implementations for platform/api/crypto.h.
-namespace location {
-namespace nearby {
-
-// Initialize global crypto state.
-void Crypto::Init() {}
-
-static ByteArray Hash(absl::string_view input, const EVP_MD* algo) {
- unsigned int md_out_size = EVP_MAX_MD_SIZE;
- uint8_t digest_buffer[EVP_MAX_MD_SIZE];
- if (input.empty()) return {};
-
- if (!EVP_Digest(input.data(), input.size(), digest_buffer, &md_out_size, algo,
- nullptr))
- return {};
-
- return ByteArray{reinterpret_cast<char*>(digest_buffer), md_out_size};
-}
-
-// Return MD5 hash of input.
-ByteArray Crypto::Md5(absl::string_view input) {
- return Hash(input, EVP_md5());
-}
-
-// Return SHA256 hash of input.
-ByteArray Crypto::Sha256(absl::string_view input) {
- return Hash(input, EVP_sha256());
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/crypto_test.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/crypto_test.cc
deleted file mode 100644
index 5276a9e6f05..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/crypto_test.cc
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/api/crypto.h"
-
-#include "gtest/gtest.h"
-
-namespace location {
-namespace nearby {
-namespace {
-
-TEST(CryptoTest, Md5Hash) {
- const std::string input{"Hello Nearby Connection"};
- const ByteArray expected_md5(
- "\x94\xa3\xbe\xc1\x8d\x30\xe3\x24\x5f\xa1\x4c\xee\xe7\x52\xe9\x36");
- ByteArray md5_hash = Crypto::Md5(input);
- EXPECT_EQ(md5_hash, expected_md5);
-}
-
-TEST(CryptoTest, Md5HashOnEmptyInput) {
- EXPECT_EQ(Crypto::Md5(""), ByteArray{});
-}
-
-TEST(CryptoTest, Sha256Hash) {
- const std::string input("Hello Nearby Connection");
- const ByteArray expected_sha256(
- "\xb4\x24\xd3\xc0\x58\x12\x9a\x42\xcb\x81\xa0\x4b\x6e\x9d\xfe\x45\x45\x9f"
- "\x15\xf7\xc0\xa9\x32\x2f\xfb\x9\x45\xf0\xf9\xbe\x75\xb");
- ByteArray sha256_hash = Crypto::Sha256(input);
- EXPECT_EQ(sha256_hash, expected_sha256);
-}
-
-TEST(CryptoTest, Sha256HashOnEmptyInput) {
- EXPECT_EQ(Crypto::Sha256(""), ByteArray{});
-}
-
-} // namespace
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/executor.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/executor.cc
deleted file mode 100644
index bc126f9311f..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/executor.cc
+++ /dev/null
@@ -1,80 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/windows/executor.h"
-
-#include "platform/impl/windows/generated/winrt/Windows.System.Threading.Core.h"
-#include "platform/impl/windows/generated/winrt/Windows.System.Threading.h"
-#include "platform/impl/windows/runner.h"
-#include "platform/impl/windows/thread_pool.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-Executor::Executor() : Executor(1) {
- // Call thread pool creator
-}
-
-Executor::Executor(int32_t max_concurrency)
- : thread_pool_(std::make_unique<ThreadPool>(max_concurrency, false)),
- executor_state_(ExecutorState::NotReady),
- max_concurrency_(max_concurrency) {
- if (max_concurrency_ < 1) {
- throw(std::invalid_argument("max_concurrency"));
- }
-
- InitializeThreadPool();
-}
-
-bool Executor::InitializeThreadPool() {
- if (executor_state_ != ExecutorState::NotReady) {
- // To create a new pool, destroy the existing one first
- return false;
- }
-
- thread_pool_->SetPoolSize(max_concurrency_);
- thread_pool_->Create();
- executor_state_ = ExecutorState::Ready;
-
- return true;
-}
-
-// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-
-void Executor::Execute(Runnable&& runnable) {
- if (shut_down_) {
- NEARBY_LOGS(VERBOSE) << "Warning: " << __func__
- << ": Attempt to execute on a shut down pool.";
- return;
- }
-
- if (runnable == nullptr) {
- NEARBY_LOGS(VERBOSE) << "Error: " << __func__ << "Runnable was null.";
- return;
- }
-
- std::unique_ptr<Runner> runner = std::make_unique<Runner>(runnable);
- thread_pool_->Run(std::move(runner));
-}
-
-// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#shutdown--
-void Executor::Shutdown() {
- shut_down_ = true;
- thread_pool_ = nullptr;
-}
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/executor.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/executor.h
deleted file mode 100644
index 09a1f37176f..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/executor.h
+++ /dev/null
@@ -1,60 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_EXECUTOR_H_
-#define PLATFORM_IMPL_WINDOWS_EXECUTOR_H_
-
-#include <atomic>
-
-#include "platform/api/executor.h"
-#include "platform/impl/windows/thread_pool.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-enum class ExecutorState {
- Ready, // has been created and initialized
- NotReady // Executor has not been initialized
-};
-
-// This abstract class is the superclass of all classes representing an
-// Executor.
-class Executor : public api::Executor {
- public:
- Executor();
- Executor(int32_t maxConcurrency);
-
- // Before returning from destructor, executor must wait for all pending
- // jobs to finish.
- ~Executor() override {}
- // https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-
- void Execute(Runnable&& runnable) override;
-
- // https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#shutdown--
- void Shutdown() override;
-
- private:
- bool InitializeThreadPool();
- std::unique_ptr<ThreadPool> thread_pool_;
-
- std::atomic<bool> shut_down_;
- ExecutorState executor_state_;
- int32_t max_concurrency_;
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_WINDOWS_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/executor_test.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/executor_test.cc
deleted file mode 100644
index fd4d64270da..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/executor_test.cc
+++ /dev/null
@@ -1,348 +0,0 @@
-// Copyright 2021 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/windows/executor.h"
-
-#include <algorithm>
-#include <utility>
-
-#include "platform/impl/windows/test_data.h"
-
-#include "gtest/gtest.h"
-
-TEST(ExecutorTests, SingleThreadedExecutorSucceeds) {
- // Arrange
- std::string expected(RUNNABLE_0_TEXT.c_str());
-
- std::unique_ptr<location::nearby::windows::Executor> executor =
- std::make_unique<location::nearby::windows::Executor>();
- std::string output = std::string();
- // Container to note threads that ran
- std::unique_ptr<std::vector<DWORD>> threadIds =
- std::make_unique<std::vector<DWORD>>();
-
- threadIds->push_back(GetCurrentThreadId());
-
- // Act
- executor->Execute([&output, &threadIds]() {
- threadIds->push_back(GetCurrentThreadId());
- output.append(RUNNABLE_0_TEXT.c_str());
- });
-
- executor->Shutdown();
-
- // Assert
- // We should've run 1 time on the main thread, and 5 times on the
- // workerThread
- ASSERT_EQ(threadIds->size(), 2);
- // We should still be on the main thread
- ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
- // We should've run all runnables on the worker thread
- ASSERT_EQ(output, expected);
-}
-
-TEST(ExecutorTests, SingleThreadedExecutorAfterShutdownFails) {
- // Arrange
- std::string expected("");
-
- std::unique_ptr<location::nearby::windows::Executor> executor =
- std::make_unique<location::nearby::windows::Executor>();
- std::unique_ptr<std::string> output = std::make_unique<std::string>();
- // Container to note threads that ran
- std::unique_ptr<std::vector<DWORD>> threadIds =
- std::make_unique<std::vector<DWORD>>();
-
- threadIds->push_back(GetCurrentThreadId());
- executor->Shutdown();
-
- // Act
- executor->Execute([&output, &threadIds]() {
- threadIds->push_back(GetCurrentThreadId());
- output->append(RUNNABLE_0_TEXT.c_str());
- });
-
- // Assert
- // We should've run 1 time on the main thread, and 5 times on the
- // workerThread
- ASSERT_EQ(threadIds->size(), 1);
- // We should still be on the main thread
- ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
- // We should've run all runnables on the worker thread
- ASSERT_EQ(*output.get(), expected);
-}
-
-TEST(ExecutorTests, SingleThreadedExecutorExecuteNullSucceeds) {
- // Arrange
- std::string expected(RUNNABLE_0_TEXT.c_str());
-
- std::unique_ptr<location::nearby::windows::Executor> executor =
- std::make_unique<location::nearby::windows::Executor>();
- std::string output = std::string();
- // Container to note threads that ran
- std::unique_ptr<std::vector<DWORD>> threadIds =
- std::make_unique<std::vector<DWORD>>();
-
- threadIds->push_back(GetCurrentThreadId());
-
- // Act
- executor->Execute(nullptr);
- executor->Execute([&output, &threadIds]() {
- threadIds->push_back(GetCurrentThreadId());
- output.append(RUNNABLE_0_TEXT.c_str());
- });
- executor->Execute(nullptr);
-
- executor->Shutdown();
-
- // Assert
- // We should've run 1 time on the main thread, and 5 times on the
- // workerThread
- ASSERT_EQ(threadIds->size(), 2);
- // We should still be on the main thread
- ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
- // We should've run all runnables on the worker thread
- ASSERT_EQ(output, expected);
-}
-
-TEST(ExecutorTests, SingleThreadedExecutorMultipleTasksSucceeds) {
- // Arrange
- std::string expected(RUNNABLE_ALL_TEXT.c_str());
-
- std::unique_ptr<location::nearby::windows::Executor> executor =
- std::make_unique<location::nearby::windows::Executor>();
- std::string output = std::string();
- // Container to note threads that ran
- std::unique_ptr<std::vector<DWORD>> threadIds =
- std::make_unique<std::vector<DWORD>>();
-
- threadIds->push_back(GetCurrentThreadId());
-
- // Act
- for (int index = 0; index < 5; index++) {
- executor->Execute([&output, &threadIds, index]() {
- threadIds->push_back(GetCurrentThreadId());
- char buffer[128];
- snprintf(buffer, sizeof(buffer), "%s%d, ", RUNNABLE_TEXT.c_str(), index);
- output.append(std::string(buffer));
- });
- }
-
- executor->Shutdown();
-
- // Assert
- // We should've run 1 time on the main thread, and 5 times on the
- // workerThread
- ASSERT_EQ(threadIds->size(), 6);
- // We should still be on the main thread
- ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
- // We should've run all runnables on the worker thread
- auto workerThreadId = threadIds->at(1);
- for (int index = 1; index < threadIds->size(); index++) {
- ASSERT_EQ(threadIds->at(index), workerThreadId);
- }
-
- // We should of run them in the order submitted
- ASSERT_EQ(output, expected);
-}
-
-TEST(ExecutorTests, MultiThreadedExecutorSingleTaskSucceeds) {
- // Arrange
- std::string expected(RUNNABLE_0_TEXT.c_str());
-
- std::unique_ptr<location::nearby::windows::Executor> executor =
- std::make_unique<location::nearby::windows::Executor>(2);
-
- // Container to note threads that ran
- std::unique_ptr<std::vector<DWORD>> threadIds =
- std::make_unique<std::vector<DWORD>>();
-
- std::shared_ptr<std::string> output = std::make_shared<std::string>();
-
- threadIds->push_back(GetCurrentThreadId());
-
- // Act
- executor->Execute([output, &threadIds]() {
- threadIds->push_back(GetCurrentThreadId());
- output->append(RUNNABLE_0_TEXT.c_str());
- });
-
- executor->Shutdown();
-
- // Assert
- // We should've run 1 time on the main thread, and 5 times on the
- // workerThread
- ASSERT_EQ(threadIds->size(), 2);
- // We should still be on the main thread
- ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
- // We should've run the task
- ASSERT_EQ(*output.get(), expected);
-}
-
-TEST(ExecutorTests, MultiThreadedExecutorMultipleTasksSucceeds) {
- // Arrange
- std::unique_ptr<location::nearby::windows::Executor> executor =
- std::make_unique<location::nearby::windows::Executor>(2);
-
- // Container to note threads that ran
- std::unique_ptr<std::vector<DWORD>> threadIds =
- std::make_unique<std::vector<DWORD>>();
-
- std::shared_ptr<std::string> output = std::make_shared<std::string>();
-
- threadIds->push_back(GetCurrentThreadId());
-
- // Act
- for (int index = 0; index < 5; index++) {
- executor->Execute([&output, &threadIds, index]() {
- threadIds->push_back(GetCurrentThreadId());
- char buffer[128];
- snprintf(buffer, sizeof(buffer), "%s %d, ", RUNNABLE_TEXT.c_str(), index);
- output->append(std::string(buffer));
- });
- }
-
- executor->Shutdown();
-
- // Assert
- // We should've run 1 time on the main thread, and 5 times on the
- // workerThread
- ASSERT_EQ(threadIds->size(), 6);
- // We should still be on the main thread
- ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
-}
-
-TEST(ExecutorTests, MultiThreadedExecutorSingleTaskAfterShutdownFails) {
- // Arrange
- std::string expected("");
-
- std::unique_ptr<location::nearby::windows::Executor> executor =
- std::make_unique<location::nearby::windows::Executor>(2);
-
- // Container to note threads that ran
- std::unique_ptr<std::vector<DWORD>> threadIds =
- std::make_unique<std::vector<DWORD>>();
-
- std::shared_ptr<std::string> output = std::make_shared<std::string>();
-
- threadIds->push_back(GetCurrentThreadId());
-
- executor->Shutdown();
-
- // Act
- executor->Execute([output, &threadIds]() {
- threadIds->push_back(GetCurrentThreadId());
- output->append(RUNNABLE_0_TEXT.c_str());
- });
-
- // Assert
- // We should've run 1 time on the main thread, and 5 times on the
- // workerThread
- ASSERT_EQ(threadIds->size(), 1);
- // We should still be on the main thread
- ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
- // We should've run the task
- ASSERT_EQ(*output.get(), expected);
-}
-
-TEST(ExecutorTests, MultiThreadedExecutorNegativeThreadsThrows) {
- // Arrange
- // Act
- // Assert
- EXPECT_THROW(
- {
- try {
- auto result =
- std::make_unique<location::nearby::windows::Executor>(-1);
- } catch (const std::invalid_argument::exception& e) {
- // and this tests that it has the correct message
- EXPECT_STREQ(INVALID_ARGUMENT_TEXT, e.what());
- throw;
- }
- },
- std::invalid_argument);
-}
-
-TEST(ExecutorTests, MultiThreadedExecutorTooManyThreadsThrows) {
- // Arrange
- // Act
- // Assert
- EXPECT_THROW(
- {
- try {
- auto result =
- std::make_unique<location::nearby::windows::Executor>(65);
- } catch (const location::nearby::windows::ThreadPoolException& e) {
- // and this tests that it has the correct message
- EXPECT_STREQ(THREADPOOL_MAX_SIZE_TEXT, e.what());
- throw;
- }
- },
- location::nearby::windows::ThreadPoolException);
-}
-
-TEST(ExecutorTests,
- MultiThreadedExecutorMultipleTasksLargeNumberOfThreadsSucceeds) {
- // Arrange
- std::unique_ptr<location::nearby::windows::Executor> executor =
- std::make_unique<location::nearby::windows::Executor>(
- MAXIMUM_WAIT_OBJECTS - 1);
-
- // Container to note threads that ran
- std::vector<DWORD> threadIds = std::vector<DWORD>();
-
- std::shared_ptr<std::string> output = std::make_shared<std::string>();
-
- threadIds.push_back(GetCurrentThreadId());
-
- CRITICAL_SECTION testCriticalSection;
- InitializeCriticalSection(&testCriticalSection);
-
- // Act
- for (int index = 0; index < 250; index++) {
- executor->Execute(
- [output, &threadIds, index, &testCriticalSection]() mutable {
- DWORD id = GetCurrentThreadId();
-
- EnterCriticalSection(&testCriticalSection);
-
- threadIds.push_back(id);
- output->append(RUNNABLE_TEXT);
- output->append(std::to_string(index));
- output->append(RUNNABLE_SEPARATOR_TEXT);
-
- LeaveCriticalSection(&testCriticalSection);
- // Using rand since this is in a critical section
- // and windows doesn't have a rand_r anyway
- auto sleepTime = (std::rand() % 101) + 1; // NOLINT
-
- Sleep(sleepTime);
- });
- }
-
- executor->Shutdown();
- DeleteCriticalSection(&testCriticalSection);
-
- // Assert
- // We should still be on the main thread
- ASSERT_EQ(GetCurrentThreadId(), threadIds.at(0));
-
- std::sort(threadIds.begin(), threadIds.end());
- int64_t uniqueIds =
- std::unique(threadIds.begin(), threadIds.end()) - threadIds.begin();
-
- ASSERT_EQ(uniqueIds, 64);
- // We should've run 1 time on the main thread, and 200 times on the
- // workerThreads
- ASSERT_EQ(threadIds.size(), 251);
-}
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/future.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/future.h
deleted file mode 100644
index 6dee7e37f65..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/future.h
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_FUTURE_H_
-#define PLATFORM_IMPL_WINDOWS_FUTURE_H_
-
-#include "platform/api/future.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-// A Future represents the result of an asynchronous computation.
-//
-// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html
-template <typename T>
-class Future : public api::Future<T> {
- public:
- // TODO(b/184975123): replace with real implementation.
- ~Future() override = default;
-
- // throws Exception::kInterrupted, Exception::kExecution
- // TODO(b/184975123): replace with real implementation.
- ExceptionOr<T> Get() override { return ExceptionOr<T>{Exception::kFailed}; }
-
- // throws Exception::kInterrupted, Exception::kExecution
- // throws Exception::kTimeout if timeout is exceeded while waiting for
- // result.
- // TODO(b/184975123): replace with real implementation.
- ExceptionOr<T> Get(absl::Duration timeout) override {
- return ExceptionOr<T>{Exception::kFailed};
- }
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_WINDOWS_FUTURE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/BUILD b/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/BUILD
deleted file mode 100644
index bdd07fa8be8..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/BUILD
+++ /dev/null
@@ -1,42 +0,0 @@
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# https://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-licenses(["notice"])
-
-cc_library(
- name = "types",
- compatible_with = ["//buildenv/target:non_prod"],
- linkopts = [
- "advapi32.lib",
- "comdlg32.lib",
- "gdi32.lib",
- "kernel32.lib",
- "odbc32.lib",
- "odbccp32.lib",
- "ole32.lib",
- "oleaut32.lib",
- "shell32.lib",
- "user32.lib",
- "uuid.lib",
- "winmm.lib",
- "winspool.lib",
- "comsuppwd.lib",
- "setupapi.lib",
- "dnsapi.lib",
- ],
- textual_hdrs = glob(["**/*.h"]),
- visibility = [
- "//third_party/nearby_connections/connections/windows:__subpackages__",
- "//platform/impl/windows:__subpackages__",
- ],
-)
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/input_file.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/input_file.h
deleted file mode 100644
index 1ed3982141c..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/input_file.h
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_INPUT_FILE_H_
-#define PLATFORM_IMPL_WINDOWS_INPUT_FILE_H_
-
-#include "platform/api/input_file.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/exception.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-// An InputFile represents a readable file on the system.
-class InputFile : public api::InputFile {
- public:
- // TODO(b/184975123): replace with real implementation.
- ~InputFile() override = default;
- // TODO(b/184975123): replace with real implementation.
- std::string GetFilePath() const override { return "Un-implemented"; }
- // TODO(b/184975123): replace with real implementation.
- std::int64_t GetTotalSize() const override { return 0; }
-
- // throws Exception::kIo
- // TODO(b/184975123): replace with real implementation.
- ExceptionOr<ByteArray> Read(std::int64_t size) override {
- return ExceptionOr<ByteArray>(Exception::kFailed);
- }
- // throws Exception::kIo
- // TODO(b/184975123): replace with real implementation.
- Exception Close() override { return Exception{}; }
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_WINDOWS_INPUT_FILE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/input_file_test.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/input_file_test.cc
deleted file mode 100644
index eb2bf8115cd..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/input_file_test.cc
+++ /dev/null
@@ -1,152 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/windows/input_file.h"
-
-#include "gtest/gtest.h"
-#include "platform/base/exception.h"
-#include "platform/base/payload_id.h"
-#include "platform/impl/windows/test_utils.h"
-#include "platform/public/logging.h"
-
-class InputFileTests : public testing::Test {
- protected:
- // You can define per-test set-up logic as usual.
- void SetUp() override {
- location::nearby::PayloadId payloadId(TEST_PAYLOAD_ID);
-
- hFile_ = CreateFileA(
- test_utils::GetPayloadPath(payloadId).c_str(), // name of the write
- GENERIC_WRITE, // open for writing
- 0, // do not share
- NULL, // default security
- CREATE_ALWAYS, // create new file only
- FILE_ATTRIBUTE_NORMAL, // normal file
- NULL); // no attr. template
-
- if (hFile_ == INVALID_HANDLE_VALUE) {
- NEARBY_LOG(ERROR,
- "Failed to create OutputFile with payloadId: %s and error: %d",
- test_utils::GetPayloadPath(payloadId).c_str(), GetLastError());
- }
-
- const char* buffer = TEST_STRING;
- DWORD bytesWritten;
-
- WriteFile(hFile_, buffer, lstrlenA(buffer) * sizeof(char), &bytesWritten,
- nullptr);
-
- CloseHandle(hFile_);
- }
-
- // You can define per-test tear-down logic as usual.
- void TearDown() override {
- location::nearby::PayloadId payloadId(TEST_PAYLOAD_ID);
- if (FileExists(test_utils::GetPayloadPath(payloadId).c_str())) {
- DeleteFileA(test_utils::GetPayloadPath(payloadId).c_str());
- }
- }
-
- BOOL FileExists(const char* szPath) {
- DWORD dwAttrib = GetFileAttributesA(szPath);
-
- return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
- !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
- }
-
- private:
- HANDLE hFile_ = nullptr;
-};
-
-TEST_F(InputFileTests, SuccessfulCreation) {
- location::nearby::PayloadId payloadId(TEST_PAYLOAD_ID);
- std::unique_ptr<location::nearby::api::InputFile> inputFile = nullptr;
-
- inputFile = location::nearby::api::ImplementationPlatform::CreateInputFile(
- payloadId, strlen(TEST_STRING));
-
- EXPECT_NE(inputFile, nullptr);
- EXPECT_EQ(inputFile->Close(),
- location::nearby::Exception{location::nearby::Exception::kSuccess});
-}
-
-TEST_F(InputFileTests, SuccessfulGetFilePath) {
- location::nearby::PayloadId payloadId(TEST_PAYLOAD_ID);
- std::unique_ptr<location::nearby::api::InputFile> inputFile = nullptr;
- std::string fileName;
-
- inputFile = location::nearby::api::ImplementationPlatform::CreateInputFile(
- payloadId, strlen(TEST_STRING));
-
- fileName = inputFile->GetFilePath();
-
- EXPECT_EQ(inputFile->Close(),
- location::nearby::Exception{location::nearby::Exception::kSuccess});
-
- EXPECT_EQ(fileName, test_utils::GetPayloadPath(payloadId).c_str());
-}
-
-TEST_F(InputFileTests, SuccessfulGetTotalSize) {
- location::nearby::PayloadId payloadId(TEST_PAYLOAD_ID);
- std::unique_ptr<location::nearby::api::InputFile> inputFile = nullptr;
- int64_t size = -1;
-
- inputFile = location::nearby::api::ImplementationPlatform::CreateInputFile(
- payloadId, strlen(TEST_STRING));
-
- size = inputFile->GetTotalSize();
-
- EXPECT_EQ(inputFile->Close(),
- location::nearby::Exception{location::nearby::Exception::kSuccess});
-
- EXPECT_EQ(size, strlen(TEST_STRING));
-}
-
-TEST_F(InputFileTests, SuccessfulRead) {
- location::nearby::PayloadId payloadId(TEST_PAYLOAD_ID);
- std::unique_ptr<location::nearby::api::InputFile> inputFile = nullptr;
-
- inputFile = location::nearby::api::ImplementationPlatform::CreateInputFile(
- payloadId, strlen(TEST_STRING));
-
- auto fileSize = inputFile->GetTotalSize();
- auto dataRead = inputFile->Read(fileSize);
-
- EXPECT_TRUE(dataRead.ok());
- EXPECT_EQ(inputFile->Close(),
- location::nearby::Exception{location::nearby::Exception::kSuccess});
-
- EXPECT_STREQ(std::string(dataRead.result()).c_str(), TEST_STRING);
-}
-
-TEST_F(InputFileTests, FailedRead) {
- location::nearby::PayloadId payloadId(TEST_PAYLOAD_ID);
- std::unique_ptr<location::nearby::api::InputFile> inputFile = nullptr;
-
- inputFile = location::nearby::api::ImplementationPlatform::CreateInputFile(
- payloadId, strlen(TEST_STRING));
-
- auto fileSize = inputFile->GetTotalSize();
- EXPECT_NE(fileSize, -1);
-
- auto dataRead = inputFile->Read(fileSize);
- EXPECT_TRUE(dataRead.ok());
-
- dataRead = inputFile->Read(fileSize);
- std::string data = std::string(dataRead.result());
-
- inputFile->Close();
-
- EXPECT_STREQ(data.c_str(), "");
-}
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/listenable_future.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/listenable_future.h
deleted file mode 100644
index 954fe01badb..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/listenable_future.h
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_LISTENABLE_FUTURE_H_
-#define PLATFORM_IMPL_WINDOWS_LISTENABLE_FUTURE_H_
-
-#include "platform/api/listenable_future.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-// A Future that accepts completion listeners.
-//
-// https://guava.dev/releases/20.0/api/docs/com/google/common/util/concurrent/ListenableFuture.html
-template <typename T>
-class ListenableFuture : public api::ListenableFuture<T> {
- public:
- // TODO(b/184975123): replace with real implementation.
- ~ListenableFuture() override = default;
-
- // TODO(b/184975123): replace with real implementation.
- void AddListener(Runnable runnable, api::Executor* executor) {}
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_WINDOWS_LISTENABLE_FUTURE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/log_message.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/log_message.cc
deleted file mode 100644
index 06801f3fc3d..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/log_message.cc
+++ /dev/null
@@ -1,73 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/windows/log_message.h"
-
-#include <algorithm>
-
-#include "base/stringprintf.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-api::LogMessage::Severity min_log_severity_ = api::LogMessage::Severity::kInfo;
-
-inline absl::LogSeverity ConvertSeverity(api::LogMessage::Severity severity) {
- switch (severity) {
- // api::LogMessage::Severity kVerbose and kInfo is mapped to
- // absl::LogSeverity kInfo since absl::LogSeverity doesn't have kVerbose
- // level.
- case api::LogMessage::Severity::kVerbose:
- case api::LogMessage::Severity::kInfo:
- return absl::LogSeverity::kInfo;
- case api::LogMessage::Severity::kWarning:
- return absl::LogSeverity::kWarning;
- case api::LogMessage::Severity::kError:
- return absl::LogSeverity::kError;
- case api::LogMessage::Severity::kFatal:
- return absl::LogSeverity::kFatal;
- }
-}
-
-LogMessage::LogMessage(const char* file, int line, Severity severity)
- : log_streamer_(ConvertSeverity(severity), file, line) {}
-
-LogMessage::~LogMessage() = default;
-
-void LogMessage::Print(const char* format, ...) {
- va_list ap;
- va_start(ap, format);
- std::string result;
- StringAppendV(&result, format, ap);
- log_streamer_.stream() << result;
- va_end(ap);
-}
-
-std::ostream& LogMessage::Stream() { return log_streamer_.stream(); }
-
-} // namespace windows
-
-namespace api {
-
-void LogMessage::SetMinLogSeverity(Severity severity) {
- windows::min_log_severity_ = severity;
-}
-
-bool LogMessage::ShouldCreateLogMessage(Severity severity) {
- return severity >= windows::min_log_severity_;
-}
-} // namespace api
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/log_message.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/log_message.h
deleted file mode 100644
index 62db640912d..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/log_message.h
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_LOG_MESSAGE_H_
-#define PLATFORM_IMPL_WINDOWS_LOG_MESSAGE_H_
-
-#include "base/check.h"
-#include "platform/api/log_message.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-// See documentation in
-// cpp/platform/api/log_message.h
-class LogMessage : public api::LogMessage {
- public:
- LogMessage(const char* file, int line, Severity severity);
- ~LogMessage() override;
-
- void Print(const char* format, ...) override;
-
- std::ostream& Stream() override;
-
- private:
- absl::LogStreamer log_streamer_;
- static api::LogMessage::Severity min_log_severity_;
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_WINDOWS_LOG_MESSAGE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/mutex.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/mutex.h
deleted file mode 100644
index 956b67207be..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/mutex.h
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright 2021 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-#ifndef PLATFORM_IMPL_WINDOWS_MUTEX_H_
-#define PLATFORM_IMPL_WINDOWS_MUTEX_H_
-#include <windows.h>
-#include <stdio.h>
-#include <synchapi.h>
-
-#include <memory>
-#include <mutex> // NOLINT
-
-#include "absl/memory/memory.h"
-#include "absl/synchronization/mutex.h"
-#include "platform/api/mutex.h"
-namespace location {
-namespace nearby {
-namespace windows {
-
-// A lock is a tool for controlling access to a shared resource by multiple
-// threads.
-// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/Lock.html
-class ABSL_LOCKABLE Mutex : public api::Mutex {
- public:
- explicit Mutex(Mode mode) : mode_(mode) {}
- ~Mutex() override = default;
- Mutex(Mutex&&) = delete;
- Mutex& operator=(Mutex&&) = delete;
- Mutex(const Mutex&) = delete;
- Mutex& operator=(const Mutex&) = delete;
-
- void Lock() ABSL_EXCLUSIVE_LOCK_FUNCTION() override {
- if (mode_ == Mode::kRegularNoCheck) mutex_.ForgetDeadlockInfo();
- if (mode_ == Mode::kRegular || mode_ == Mode::kRegularNoCheck) {
- mutex_.Lock();
- } else {
- recursive_mutex_.lock();
- }
- }
-
- void Unlock() ABSL_UNLOCK_FUNCTION() override {
- if (mode_ == Mode::kRegular || mode_ == Mode::kRegularNoCheck) {
- mutex_.Unlock();
- } else {
- recursive_mutex_.unlock();
- }
- }
-
- private:
- friend class ConditionVariable;
- absl::Mutex mutex_;
- std::recursive_mutex recursive_mutex_; // The actual mutex allocation
- Mode mode_;
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-#endif // PLATFORM_IMPL_WINDOWS_MUTEX_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/mutex_test.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/mutex_test.cc
deleted file mode 100644
index ff9ea464c17..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/mutex_test.cc
+++ /dev/null
@@ -1,109 +0,0 @@
-// Copyright 2021 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/windows/mutex.h"
-
-#include <future> // NOLINT
-
-#include "gtest/gtest.h"
-
-class MutexTests : public testing::Test {
- public:
- class MutexTest {
- public:
- MutexTest(location::nearby::windows::Mutex& mutex) : mutex_(mutex) {}
-
- std::future<bool> WaitForLock() { // NOLINT
- return std::async(
- std::launch::async,
- // for this lambda you need C++14
- [this]() mutable {
- std::unique_lock<std::mutex> lck(mutex_.GetWindowsMutex());
- return true;
- });
- }
-
- void PostEvent() {
- std::lock_guard<std::mutex> guard(mutex_.GetWindowsMutex());
- mutex_.Unlock();
- }
-
- private:
- location::nearby::windows::Mutex& mutex_;
- };
-};
-
-TEST_F(MutexTests, SuccessfulRecursiveCreation) {
- // Arrange
- location::nearby::windows::Mutex mutex = location::nearby::windows::Mutex(
- location::nearby::windows::Mutex::Mode::kRecursive);
-
- // Act
- std::recursive_mutex& actual = mutex.GetWindowsRecursiveMutex();
-
- // Assert
- ASSERT_TRUE(actual.native_handle() != nullptr);
-}
-
-TEST_F(MutexTests, SuccessfulCreation) {
- // Arrange
- location::nearby::windows::Mutex mutex(
- location::nearby::windows::Mutex::Mode::kRegular);
-
- // Act
- std::mutex& actual = mutex.GetWindowsMutex();
-
- // Assert
- ASSERT_TRUE(actual.native_handle() != nullptr);
-}
-
-TEST_F(MutexTests, SuccessfulSignal) {
- // Arrange
- location::nearby::windows::Mutex mutex(
- location::nearby::windows::Mutex::Mode::kRegular);
-
- location::nearby::windows::Mutex& mutexRef = mutex;
- MutexTest mutexTest(mutexRef);
-
- mutex.Lock();
-
- // Act
- auto result = mutexTest.WaitForLock();
- mutex.Unlock();
-
- // Assert
- ASSERT_TRUE(result.get());
-}
-
-TEST_F(MutexTests, SuccessfulRecursiveSignal) {
- // Arrange
- location::nearby::windows::Mutex mutex(
- location::nearby::windows::Mutex::Mode::kRecursive);
-
- location::nearby::windows::Mutex& mutexRef = mutex;
- MutexTest mutexTest(mutexRef);
-
- mutex.Lock();
- mutex.Lock();
- mutex.Lock();
-
- // Act
- auto result = mutexTest.WaitForLock();
- mutex.Unlock();
- mutex.Unlock();
- mutex.Unlock();
-
- // Assert
- ASSERT_TRUE(result.get());
-}
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/output_file.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/output_file.h
deleted file mode 100644
index 9ad479b6c1b..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/output_file.h
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_OUTPUT_FILE_H_
-#define PLATFORM_IMPL_WINDOWS_OUTPUT_FILE_H_
-
-#include "platform/api/output_file.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/exception.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-// An OutputFile represents a writable file on the system.
-class OutputFile : public api::OutputFile {
- public:
- // TODO(b/184975123): replace with real implementation.
- ~OutputFile() override = default;
-
- // throws Exception::kIo
- // TODO(b/184975123): replace with real implementation.
- Exception Write(const ByteArray& data) override { return Exception{}; }
- // throws Exception::kIo
- // TODO(b/184975123): replace with real implementation.
- Exception Flush() override { return Exception{}; }
- // throws Exception::kIo
- // TODO(b/184975123): replace with real implementation.
- Exception Close() override { return Exception{}; }
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_WINDOWS_OUTPUT_FILE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/output_file_test.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/output_file_test.cc
deleted file mode 100644
index 18e47f93739..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/output_file_test.cc
+++ /dev/null
@@ -1,90 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/windows/output_file.h"
-
-#include "gtest/gtest.h"
-#include "platform/api/platform.h"
-#include "platform/base/exception.h"
-#include "platform/base/payload_id.h"
-#include "platform/impl/windows/test_utils.h"
-
-class OutputFileTests : public testing::Test {
- protected:
- // You can define per-test set-up logic as usual.
- void SetUp() override {
- location::nearby::PayloadId payloadId(TEST_PAYLOAD_ID);
- if (FileExists(test_utils::GetPayloadPath(payloadId).c_str())) {
- DeleteFileA(test_utils::GetPayloadPath(payloadId).c_str());
- }
- }
-
- // You can define per-test tear-down logic as usual.
- void TearDown() override {
- location::nearby::PayloadId payloadId(TEST_PAYLOAD_ID);
- if (FileExists(test_utils::GetPayloadPath(payloadId).c_str())) {
- DeleteFileA(test_utils::GetPayloadPath(payloadId).c_str());
- }
- }
-
- BOOL FileExists(const char* szPath) {
- DWORD dwAttrib = GetFileAttributesA(szPath);
-
- return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
- !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
- }
-};
-
-TEST_F(OutputFileTests, SuccessfulCreation) {
- location::nearby::PayloadId payloadId(TEST_PAYLOAD_ID);
- std::unique_ptr<location::nearby::api::OutputFile> outputFile = nullptr;
-
- EXPECT_NO_THROW(
- outputFile =
- location::nearby::api::ImplementationPlatform::CreateOutputFile(
- payloadId));
-
- EXPECT_NE(outputFile, nullptr);
- EXPECT_NO_THROW(outputFile->Close());
-}
-
-TEST_F(OutputFileTests, SuccessfulClose) {
- location::nearby::PayloadId payloadId(TEST_PAYLOAD_ID);
- std::unique_ptr<location::nearby::api::OutputFile> outputFile = nullptr;
-
- EXPECT_NO_THROW(
- outputFile =
- location::nearby::api::ImplementationPlatform::CreateOutputFile(
- payloadId));
-
- EXPECT_NO_THROW(outputFile->Close());
-
- DeleteFileA(test_utils::GetPayloadPath(payloadId).c_str());
-}
-
-TEST_F(OutputFileTests, SuccessfulWrite) {
- location::nearby::PayloadId payloadId(TEST_PAYLOAD_ID);
- location::nearby::ByteArray data(std::string(TEST_STRING));
- std::unique_ptr<location::nearby::api::OutputFile> outputFile = nullptr;
-
- EXPECT_NO_THROW(
- outputFile =
- location::nearby::api::ImplementationPlatform::CreateOutputFile(
- payloadId));
-
- EXPECT_NO_THROW(outputFile->Write(data));
- EXPECT_NO_THROW(outputFile->Close());
-
- DeleteFileA(test_utils::GetPayloadPath(payloadId).c_str());
-}
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/platform.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/platform.cc
deleted file mode 100644
index 5d117cf6978..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/platform.cc
+++ /dev/null
@@ -1,174 +0,0 @@
-// Copyright 2021 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/api/platform.h"
-
-#include <shlobj.h>
-
-#include "platform/impl/shared/count_down_latch.h"
-#include "platform/impl/shared/file.h"
-#include "platform/impl/windows/atomic_boolean.h"
-#include "platform/impl/windows/atomic_reference.h"
-#include "platform/impl/windows/ble.h"
-#include "platform/impl/windows/bluetooth_adapter.h"
-#include "platform/impl/windows/bluetooth_classic_medium.h"
-#include "platform/impl/windows/cancelable.h"
-#include "platform/impl/windows/condition_variable.h"
-#include "platform/impl/windows/executor.h"
-#include "platform/impl/windows/future.h"
-#include "platform/impl/windows/listenable_future.h"
-#include "platform/impl/windows/log_message.h"
-#include "platform/impl/windows/mutex.h"
-#include "platform/impl/windows/scheduled_executor.h"
-#include "platform/impl/windows/server_sync.h"
-#include "platform/impl/windows/settable_future.h"
-#include "platform/impl/windows/submittable_executor.h"
-#include "platform/impl/windows/webrtc.h"
-#include "platform/impl/windows/wifi.h"
-#include "platform/impl/windows/wifi_lan.h"
-
-namespace location {
-namespace nearby {
-namespace api {
-namespace {
-
-std::string GetPayloadPath(PayloadId payload_id) {
- PWSTR basePath;
-
- // Retrieves the full path of a known folder identified by the folder's
- // KNOWNFOLDERID.
- // https://docs.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetknownfolderpath
- SHGetKnownFolderPath(
- FOLDERID_Downloads, // rfid: A reference to the KNOWNFOLDERID that
- // identifies the folder.
- 0, // dwFlags: Flags that specify special retrieval options.
- NULL, // hToken: An access token that represents a particular user.
- &basePath); // ppszPath: When this method returns, contains the address
- // of a pointer to a null-terminated Unicode string that
- // specifies the path of the known folder. The calling
- // process is responsible for freeing this resource once it
- // is no longer needed by calling CoTaskMemFree, whether
- // SHGetKnownFolderPath succeeds or not.
-
- char* fullpathUTF8 = new char((wcslen(basePath) + 1) * sizeof(char));
- wcstombs(fullpathUTF8, basePath, (wcslen(basePath) + 1) * sizeof(char));
- std::string fullPath = std::string(fullpathUTF8);
- auto retval = absl::StrCat(fullPath += "/", payload_id);
- return retval;
-}
-} // namespace
-
-std::unique_ptr<AtomicBoolean> ImplementationPlatform::CreateAtomicBoolean(
- bool initial_value) {
- return absl::make_unique<windows::AtomicBoolean>();
-}
-
-std::unique_ptr<AtomicUint32> ImplementationPlatform::CreateAtomicUint32(
- std::uint32_t value) {
- return absl::make_unique<windows::AtomicUint32>();
-}
-
-std::unique_ptr<CountDownLatch> ImplementationPlatform::CreateCountDownLatch(
- std::int32_t count) {
- return absl::make_unique<shared::CountDownLatch>(count);
-}
-
-std::unique_ptr<Mutex> ImplementationPlatform::CreateMutex(Mutex::Mode mode) {
- return absl::make_unique<windows::Mutex>(mode);
-}
-
-std::unique_ptr<ConditionVariable>
-ImplementationPlatform::CreateConditionVariable(Mutex* mutex) {
- return absl::make_unique<windows::ConditionVariable>(mutex);
-}
-
-std::unique_ptr<InputFile> ImplementationPlatform::CreateInputFile(
- PayloadId payload_id, std::int64_t total_size) {
- return absl::make_unique<shared::InputFile>(GetPayloadPath(payload_id),
- total_size);
-}
-
-std::unique_ptr<OutputFile> ImplementationPlatform::CreateOutputFile(
- PayloadId payload_id) {
- return absl::make_unique<shared::OutputFile>(GetPayloadPath(payload_id));
-}
-
-// TODO(b/184975123): replace with real implementation.
-std::unique_ptr<LogMessage> ImplementationPlatform::CreateLogMessage(
- const char* file, int line, LogMessage::Severity severity) {
- return absl::make_unique<windows::LogMessage>(file, line, severity);
-}
-
-std::unique_ptr<SubmittableExecutor>
-ImplementationPlatform::CreateSingleThreadExecutor() {
- return absl::make_unique<windows::SubmittableExecutor>();
-}
-
-std::unique_ptr<SubmittableExecutor>
-ImplementationPlatform::CreateMultiThreadExecutor(
- std::int32_t max_concurrency) {
- return absl::make_unique<windows::SubmittableExecutor>(max_concurrency);
-}
-
-std::unique_ptr<ScheduledExecutor>
-ImplementationPlatform::CreateScheduledExecutor() {
- return absl::make_unique<windows::ScheduledExecutor>();
-}
-
-std::unique_ptr<BluetoothAdapter>
-ImplementationPlatform::CreateBluetoothAdapter() {
- return absl::make_unique<windows::BluetoothAdapter>();
-}
-
-std::unique_ptr<BluetoothClassicMedium>
-ImplementationPlatform::CreateBluetoothClassicMedium(
- nearby::api::BluetoothAdapter& adapter) {
- return absl::make_unique<windows::BluetoothClassicMedium>(adapter);
-}
-
-// TODO(b/184975123): replace with real implementation.
-std::unique_ptr<BleMedium> ImplementationPlatform::CreateBleMedium(
- BluetoothAdapter& adapter) {
- return absl::make_unique<windows::BleMedium>();
-}
-
-// TODO(b/184975123): replace with real implementation.
-std::unique_ptr<ble_v2::BleMedium> ImplementationPlatform::CreateBleV2Medium(
- BluetoothAdapter&) {
- return nullptr;
-}
-
-// TODO(b/184975123): replace with real implementation.
-std::unique_ptr<ServerSyncMedium>
-ImplementationPlatform::CreateServerSyncMedium() {
- return std::unique_ptr<windows::ServerSyncMedium>();
-}
-
-// TODO(b/184975123): replace with real implementation.
-std::unique_ptr<WifiMedium> ImplementationPlatform::CreateWifiMedium() {
- return std::unique_ptr<WifiMedium>();
-}
-
-std::unique_ptr<WifiLanMedium> ImplementationPlatform::CreateWifiLanMedium() {
- return absl::make_unique<windows::WifiLanMedium>();
-}
-
-// TODO(b/184975123): replace with real implementation.
-std::unique_ptr<WebRtcMedium> ImplementationPlatform::CreateWebRtcMedium() {
- return absl::make_unique<windows::WebRtcMedium>();
-}
-
-} // namespace api
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/runner.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/runner.h
deleted file mode 100644
index 911168a832a..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/runner.h
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_RUNNER_H_
-#define PLATFORM_IMPL_WINDOWS_RUNNER_H_
-
-#include "platform/base/runnable.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-class ThreadPool;
-
-class Runner {
- public:
- Runner(std::function<void()> runnable)
- : thread_pool_(nullptr), runnable_(runnable) {}
- void Run() { runnable_(); }
- ~Runner(){}
- ThreadPool* thread_pool_;
-
- private:
- std::function<void()> runnable_;
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_WINDOWS_RUNNER_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/scheduled_executor.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/scheduled_executor.cc
deleted file mode 100644
index 53f23e7edc1..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/scheduled_executor.cc
+++ /dev/null
@@ -1,149 +0,0 @@
-// Copyright 2021 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/windows/scheduled_executor.h"
-
-#include "platform/impl/windows/cancelable.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-class ScheduledExecutorException : public std::runtime_error {
- public:
- ScheduledExecutorException() : std::runtime_error("") {}
- ScheduledExecutorException(const std::string& message)
- : std::runtime_error(message) {}
- virtual const char* what() const throw() {
- return "WaitableTimer creation failed";
- }
-};
-
-class TimerData {
- public:
- TimerData(ScheduledExecutor* scheduledExecutor,
- std::function<void()> runnable, HANDLE waitableTimer)
- : scheduled_executor_(scheduledExecutor),
- runnable_(std::move(runnable)),
- waitable_timer_handle_(waitableTimer) {}
-
- ScheduledExecutor* GetScheduledExecutor() { return scheduled_executor_; }
- std::function<void()> GetRunnable() { return runnable_; }
- HANDLE GetWaitableTimerHandle() { return waitable_timer_handle_; }
-
- private:
- ScheduledExecutor* scheduled_executor_;
- std::function<void()> runnable_;
- HANDLE waitable_timer_handle_;
-};
-
-void WINAPI ScheduledExecutor::_TimerProc(LPVOID argToCompletionRoutine,
- DWORD dwTimerLowValue,
- DWORD dwTimerHighValue) {
- TimerData* timerData;
- DWORD threadId = GetCurrentThreadId();
-
- _ASSERT(argToCompletionRoutine != NULL);
- if (NULL == argToCompletionRoutine) {
- NEARBY_LOGS(ERROR)
- << __func__
- << ": TimerProc argument argToCompletionRoutine was null.";
-
- return;
- }
-
- timerData = static_cast<TimerData*>(argToCompletionRoutine);
- timerData->GetScheduledExecutor()->Execute(timerData->GetRunnable());
-
- // Get the waitable timer and destroy it
- CloseHandle(timerData->GetWaitableTimerHandle());
- free(timerData);
- return;
-}
-
-ScheduledExecutor::ScheduledExecutor()
- : executor_(std::make_unique<nearby::windows::Executor>()),
- shut_down_(false) {}
-
-// Cancelable is kept both in the executor context, and in the caller context.
-// We want Cancelable to live until both caller and executor are done with it.
-// Exclusive ownership model does not work for this case;
-// using std:shared_ptr<> instead of std::unique_ptr<>.
-std::shared_ptr<api::Cancelable> ScheduledExecutor::Schedule(
- Runnable&& runnable, absl::Duration duration) {
- if (shut_down_) {
- NEARBY_LOGS(ERROR)
- << __func__
- << ": Attempt to Schedule on a shut down executor.";
-
- return nullptr;
- }
-
- // Create the waitable timer
- // Create a name for this timer
- // TODO: (jfcarroll) construct a timer name based on ??
- char buffer[TIMER_NAME_BUFFER_SIZE];
-
- snprintf(buffer, TIMER_NAME_BUFFER_SIZE, "PID:%ld", GetCurrentProcessId());
-
- HANDLE waitableTimer = CreateWaitableTimerA(NULL, true, buffer);
-
- if (waitableTimer == NULL) {
- throw ScheduledExecutorException("WaitableTimer creation failed");
- }
-
- waitable_timers_.push_back(waitableTimer);
-
- // Create the delay value - due time
- LARGE_INTEGER dueTime;
- dueTime.QuadPart = -(absl::ToChronoNanoseconds(duration).count() / 100);
-
- TimerData* timerData = new TimerData(this, runnable, waitableTimer);
-
- BOOL result = SetWaitableTimer(waitableTimer, &dueTime, 0, _TimerProc,
- timerData, false);
-
- if (result == 0) {
- NEARBY_LOGS(ERROR) << "Error: " << __func__ << ": Failed to set the timer.";
- return nullptr;
- }
-
- return std::make_shared<nearby::windows::Cancelable>(waitableTimer);
-}
-
-// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-
-void ScheduledExecutor::Execute(Runnable&& runnable) {
- if (shut_down_) {
- NEARBY_LOGS(ERROR) << __func__
- << ": Attempt to Execute on a shut down executor.";
- return;
- }
-
- executor_->Execute(std::move(runnable));
-}
-
-// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#shutdown--
-void ScheduledExecutor::Shutdown() {
- if (!shut_down_) {
- shut_down_ = true;
- executor_->Shutdown();
- return;
- }
- NEARBY_LOGS(ERROR) << __func__
- << ": Attempt to Shutdown on a shut down executor.";
-}
-} // namespace windows
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/scheduled_executor.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/scheduled_executor.h
deleted file mode 100644
index 68db9148119..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/scheduled_executor.h
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_SCHEDULED_EXECUTOR_H_
-#define PLATFORM_IMPL_WINDOWS_SCHEDULED_EXECUTOR_H_
-
-#include <windows.h>
-
-#include "platform/api/scheduled_executor.h"
-#include "platform/impl/windows/executor.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-#define TIMER_NAME_BUFFER_SIZE 64
-
-// An Executor that can schedule commands to run after a given delay, or to
-// execute periodically.
-//
-// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html
-class ScheduledExecutor : public api::ScheduledExecutor {
- public:
- ScheduledExecutor();
-
- ~ScheduledExecutor() override = default;
-
- // Cancelable is kept both in the executor context, and in the caller context.
- // We want Cancelable to live until both caller and executor are done with it.
- // Exclusive ownership model does not work for this case;
- // using std:shared_ptr<> instead if std::unique_ptr<>.
- std::shared_ptr<api::Cancelable> Schedule(Runnable&& runnable,
- absl::Duration duration) override;
-
- // https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-
- void Execute(Runnable&& runnable) override;
-
- // https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#shutdown--
- void Shutdown() override;
-
- private:
- static void WINAPI _TimerProc(LPVOID lpArgToCompletionRoutine,
- DWORD dwTimerLowValue, DWORD dwTimerHighValue);
-
- std::unique_ptr<nearby::windows::Executor> executor_;
- std::vector<HANDLE> waitable_timers_;
- std::atomic_bool shut_down_;
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_WINDOWS_SCHEDULED_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/scheduled_executor_test.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/scheduled_executor_test.cc
deleted file mode 100644
index 4a52c207f27..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/scheduled_executor_test.cc
+++ /dev/null
@@ -1,174 +0,0 @@
-// Copyright 2021 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-#include "platform/impl/windows/scheduled_executor.h"
-
-#include <utility>
-
-#include "platform/impl/windows/test_data.h"
-
-#include "gtest/gtest.h"
-
-TEST(ScheduledExecutorTests, ExecuteSucceeds) {
- // Arrange
- std::string expected(RUNNABLE_0_TEXT.c_str());
-
- std::unique_ptr<location::nearby::windows::ScheduledExecutor>
- submittableExecutor =
- std::make_unique<location::nearby::windows::ScheduledExecutor>();
- std::string output = std::string();
- // Container to note threads that ran
- std::unique_ptr<std::vector<DWORD>> threadIds =
- std::make_unique<std::vector<DWORD>>();
-
- threadIds->push_back(GetCurrentThreadId());
-
- // Act
- submittableExecutor->Execute([&output, &threadIds]() {
- threadIds->push_back(GetCurrentThreadId());
- output.append(RUNNABLE_0_TEXT.c_str());
- });
-
- submittableExecutor->Shutdown();
-
- // Assert
- // We should've run 1 time on the main thread, and 1 times on the
- // workerThread
- ASSERT_EQ(threadIds->size(), 2);
- // We should still be on the main thread
- ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
- // We should've run all runnables on the worker thread
- ASSERT_EQ(output, expected);
-}
-
-TEST(ScheduledExecutorTests, ScheduleSucceeds) {
- // Arrange
- std::string expected(RUNNABLE_0_TEXT.c_str());
-
- std::unique_ptr<location::nearby::windows::ScheduledExecutor>
- submittableExecutor =
- std::make_unique<location::nearby::windows::ScheduledExecutor>();
- std::string output = std::string();
- // Container to note threads that ran
- std::unique_ptr<std::vector<DWORD>> threadIds =
- std::make_unique<std::vector<DWORD>>();
-
- threadIds->push_back(GetCurrentThreadId());
-
- std::chrono::system_clock::time_point timeNow =
- std::chrono::system_clock::now();
- std::chrono::system_clock::time_point timeExecuted;
-
- // Act
- submittableExecutor->Schedule(
- [&output, &threadIds, &timeExecuted]() {
- timeExecuted = std::chrono::system_clock::now();
- threadIds->push_back(GetCurrentThreadId());
- output.append(RUNNABLE_0_TEXT.c_str());
- },
- absl::Milliseconds(50));
-
- SleepEx(100, true); // Yield the thread
-
- submittableExecutor->Shutdown();
-
- auto difference = std::chrono::duration_cast<std::chrono::milliseconds>(
- timeExecuted - timeNow)
- .count();
-
- // Assert
- // We should've run 1 time on the main thread, and 1 times on the
- // workerThread
- ASSERT_TRUE(difference >= 50) << "difference was: " << difference;
- ASSERT_TRUE(difference < 100) << "difference was: " << difference;
-
- ASSERT_EQ(threadIds->size(), 2);
- // We should still be on the main thread
- ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
- // We should've run all runnables on the worker thread
- ASSERT_EQ(output, expected);
-}
-
-TEST(ScheduledExecutorTests, CancelSucceeds) {
- // Arrange
- std::string expected("");
-
- std::unique_ptr<location::nearby::windows::ScheduledExecutor>
- submittableExecutor =
- std::make_unique<location::nearby::windows::ScheduledExecutor>();
- std::string output = std::string();
- // Container to note threads that ran
- std::unique_ptr<std::vector<DWORD>> threadIds =
- std::make_unique<std::vector<DWORD>>();
-
- threadIds->push_back(GetCurrentThreadId());
-
- // Act
- auto cancelable = submittableExecutor->Schedule(
- [&output, &threadIds]() {
- threadIds->push_back(GetCurrentThreadId());
- output.append(RUNNABLE_0_TEXT.c_str());
- },
- absl::Milliseconds(1000));
-
- SleepEx(100, true); // Yield the thread
-
- auto actual = cancelable->Cancel();
-
- submittableExecutor->Shutdown();
-
- // Assert
- ASSERT_TRUE(actual);
- ASSERT_EQ(threadIds->size(), 1);
- // We should still be on the main thread
- ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
- // We should've run all runnables on the worker thread
- ASSERT_EQ(output, expected);
-}
-
-TEST(ScheduledExecutorTests, CancelAfterStartedFails) {
- // Arrange
- std::string expected(RUNNABLE_0_TEXT.c_str());
-
- std::unique_ptr<location::nearby::windows::ScheduledExecutor>
- submittableExecutor =
- std::make_unique<location::nearby::windows::ScheduledExecutor>();
- std::string output = std::string();
- // Container to note threads that ran
- std::unique_ptr<std::vector<DWORD>> threadIds =
- std::make_unique<std::vector<DWORD>>();
-
- threadIds->push_back(GetCurrentThreadId());
-
- // Act
- auto cancelable = submittableExecutor->Schedule(
- [&output, &threadIds]() {
- threadIds->push_back(GetCurrentThreadId());
- output.append(RUNNABLE_0_TEXT.c_str());
- },
- absl::Milliseconds(100));
-
- SleepEx(1000, true); // Yield the thread
-
- auto actual = cancelable->Cancel();
-
- submittableExecutor->Shutdown();
-
- // Assert
- ASSERT_FALSE(actual);
- ASSERT_EQ(threadIds->size(), 2);
- // We should still be on the main thread
- ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
- // We should've run all runnables on the worker thread
- ASSERT_EQ(output, expected);
-}
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/server_sync.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/server_sync.h
deleted file mode 100644
index ec59745f365..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/server_sync.h
+++ /dev/null
@@ -1,90 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_SERVER_SYNC_H_
-#define PLATFORM_IMPL_WINDOWS_SERVER_SYNC_H_
-
-#include "platform/api/server_sync.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-// Abstraction that represents a Nearby endpoint exchanging data through
-// ServerSync Medium.
-class ServerSyncDevice : public api::ServerSyncDevice {
- public:
- // TODO(b/184975123): replace with real implementation.
- ~ServerSyncDevice() override = default;
-
- // TODO(b/184975123): replace with real implementation.
- std::string GetName() const override { return "Un-implemented"; }
- // TODO(b/184975123): replace with real implementation.
- std::string GetGuid() const override { return "Un-implemented"; }
- // TODO(b/184975123): replace with real implementation.
- std::string GetOwnGuid() const override { return "Un-implemented"; }
-};
-
-// Container of operations that can be performed over the Chrome Sync medium.
-class ServerSyncMedium : public api::ServerSyncMedium {
- public:
- // TODO(b/184975123): replace with real implementation.
- ~ServerSyncMedium() override = default;
-
- // TODO(b/184975123): replace with real implementation.
- bool StartAdvertising(absl::string_view service_id,
- absl::string_view endpoint_id,
- const ByteArray& endpoint_info) override {
- return false;
- }
- // TODO(b/184975123): replace with real implementation.
- void StopAdvertising(absl::string_view service_id) override {}
-
- class DiscoveredDeviceCallback
- : public api::ServerSyncMedium::DiscoveredDeviceCallback {
- public:
- // TODO(b/184975123): replace with real implementation.
- ~DiscoveredDeviceCallback() override = default;
-
- // Called on a new ServerSyncDevice discovery.
- // TODO(b/184975123): replace with real implementation.
- void OnDeviceDiscovered(api::ServerSyncDevice* device,
- absl::string_view service_id,
- absl::string_view endpoint_id,
- const ByteArray& endpoint_info) override {}
- // Called when ServerSyncDevice is no longer reachable.
- // TODO(b/184975123): replace with real implementation.
- void OnDeviceLost(api::ServerSyncDevice* device,
- absl::string_view service_id) override {}
- };
-
- // Returns true once the Chrome Sync scan has been initiated.
- // TODO(b/184975123): replace with real implementation.
- bool StartDiscovery(absl::string_view service_id,
- const api::ServerSyncMedium::DiscoveredDeviceCallback&
- discovered_device_callback) override {
- return false;
- }
- // Returns true once Chrome Sync scan for service_id is well and truly
- // stopped; after this returns, there must be no more invocations of the
- // DiscoveredDeviceCallback passed in to startScanning() for service_id.
- // TODO(b/184975123): replace with real implementation.
- void StopDiscovery(absl::string_view service_id) override {}
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_WINDOWS_SERVER_SYNC_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/settable_future.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/settable_future.h
deleted file mode 100644
index 99f9a02c059..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/settable_future.h
+++ /dev/null
@@ -1,51 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_SETTABLE_FUTURE_H_
-#define PLATFORM_IMPL_WINDOWS_SETTABLE_FUTURE_H_
-
-#include "platform/api/settable_future.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-// A SettableFuture is a type of Future whose result can be set.
-//
-// https://google.github.io/guava/releases/20.0/api/docs/com/google/common/util/concurrent/SettableFuture.html
-template <typename T>
-class SettableFuture : public api::SettableFuture<T> {
- public:
- // TODO(b/184975123): replace with real implementation.
- ~SettableFuture() override = default;
-
- // Completes the future successfully. The value is returned to any waiters.
- // Returns true, if value was set.
- // Returns false, if Future is already in "done" state.
- // TODO(b/184975123): replace with real implementation.
- bool Set(T value) override { return false; }
-
- // Completes the future unsuccessfully. The exception value is returned to any
- // waiters.
- // Returns true, if exception was set.
- // Returns false, if Future is already in "done" state.
- // TODO(b/184975123): replace with real implementation.
- bool SetException(Exception exception) override { return false; }
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_WINDOWS_SETTABLE_FUTURE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/submittable_executor.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/submittable_executor.cc
deleted file mode 100644
index ddba0e5a76f..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/submittable_executor.cc
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright 2021 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/windows/submittable_executor.h"
-
-#include "platform/impl/windows/executor.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-SubmittableExecutor::SubmittableExecutor() : SubmittableExecutor(1) {}
-
-SubmittableExecutor::SubmittableExecutor(int32_t max_concurrancy)
- : executor_(std::make_unique<nearby::windows::Executor>(max_concurrancy)),
- shut_down_(false) {}
-
-bool SubmittableExecutor::DoSubmit(Runnable&& wrapped_callable) {
- if (!shut_down_) {
- executor_->Execute(std::move(wrapped_callable));
- return true;
- }
-
- NEARBY_LOGS(ERROR) << "Error: " << __func__
- << ": Attempt to DoSubmit on a shutdown executor.";
-
- return false;
-}
-
-// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-
-void SubmittableExecutor::Execute(Runnable&& runnable) {
- if (!shut_down_) {
- executor_->Execute(std::move(runnable));
- } else {
- NEARBY_LOGS(ERROR) << "Error: " << __func__
- << ": Attempt to Execute on a shutdown executor.";
- }
-}
-
-// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#shutdown--
-void SubmittableExecutor::Shutdown() {
- if (!shut_down_) {
- executor_->Shutdown();
- shut_down_ = true;
- }
-
- NEARBY_LOGS(ERROR) << "Error: " << __func__
- << ": Attempt to Shutdown on a shutdown executor.";
-}
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/submittable_executor.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/submittable_executor.h
deleted file mode 100644
index dad778c4b2a..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/submittable_executor.h
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_SUBMITTABLE_EXECUTOR_H_
-#define PLATFORM_IMPL_WINDOWS_SUBMITTABLE_EXECUTOR_H_
-
-#include "platform/api/submittable_executor.h"
-#include "platform/impl/windows/executor.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-// Main interface to be used by platform as a base class for
-// - MultiThreadExecutorWrapper
-// - SingleThreadExecutorWrapper
-// Platform must override bool submit(std::function<void()>) method.
-class SubmittableExecutor : public api::SubmittableExecutor {
- public:
- SubmittableExecutor();
- SubmittableExecutor(int32_t maxConcurrancy);
- ~SubmittableExecutor() override = default;
-
- // Submit a callable (with no delay).
- // Returns true, if callable was submitted, false otherwise.
- // Callable is not submitted if shutdown is in progress.
- bool DoSubmit(Runnable&& wrapped_callable) override;
-
- // https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-
- void Execute(Runnable&& runnable) override;
-
- // https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#shutdown--
- void Shutdown() override;
-
- private:
- std::unique_ptr<nearby::windows::Executor> executor_;
- std::atomic_bool shut_down_;
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_WINDOWS_SUBMITTABLE_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/submittable_executor_test.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/submittable_executor_test.cc
deleted file mode 100644
index 779f57319bf..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/submittable_executor_test.cc
+++ /dev/null
@@ -1,240 +0,0 @@
-// Copyright 2021 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-#include "platform/impl/windows/submittable_executor.h"
-
-#include <utility>
-
-#include "platform/impl/windows/test_data.h"
-
-#include "gtest/gtest.h"
-
-TEST(SubmittableExecutorTests, SingleThreadedExecuteSucceeds) {
- // Arrange
- std::string expected(RUNNABLE_0_TEXT.c_str());
-
- std::unique_ptr<location::nearby::windows::SubmittableExecutor>
- submittableExecutor =
- std::make_unique<location::nearby::windows::SubmittableExecutor>();
- std::string output = std::string();
- // Container to note threads that ran
- std::unique_ptr<std::vector<DWORD>> threadIds =
- std::make_unique<std::vector<DWORD>>();
-
- threadIds->push_back(GetCurrentThreadId());
-
- // Act
- submittableExecutor->Execute([&output, &threadIds]() {
- threadIds->push_back(GetCurrentThreadId());
- output.append(RUNNABLE_0_TEXT.c_str());
- });
-
- submittableExecutor->Shutdown();
-
- // Assert
- // We should've run 1 time on the main thread, and 1 times on the
- // workerThread
- ASSERT_EQ(threadIds->size(), 2);
- // We should still be on the main thread
- ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
- // We should've run all runnables on the worker thread
- ASSERT_EQ(output, expected);
-}
-
-TEST(SubmittableExecutorTests, SingleThreadedExecuteAfterShutdownFails) {
- // Arrange
- std::string expected("");
-
- std::unique_ptr<location::nearby::windows::SubmittableExecutor>
- submittableExecutor =
- std::make_unique<location::nearby::windows::SubmittableExecutor>();
- std::string output = std::string();
- // Container to note threads that ran
- std::unique_ptr<std::vector<DWORD>> threadIds =
- std::make_unique<std::vector<DWORD>>();
-
- threadIds->push_back(GetCurrentThreadId());
-
- submittableExecutor->Shutdown();
-
- // Act
- submittableExecutor->Execute([&output, &threadIds]() {
- threadIds->push_back(GetCurrentThreadId());
- output.append(RUNNABLE_0_TEXT.c_str());
- });
-
- // Assert
- // We should've run 1 time on the main thread, and 0 times on the
- // workerThread
- ASSERT_EQ(threadIds->size(), 1);
- // We should still be on the main thread
- ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
- // We should've run all runnables on the worker thread
- ASSERT_EQ(output, expected);
-}
-
-TEST(SubmittableExecutorTests, SingleThreadedDoSubmitSucceeds) {
- // Arrange
- std::string expected(RUNNABLE_0_TEXT.c_str());
-
- std::unique_ptr<location::nearby::windows::SubmittableExecutor>
- submittableExecutor =
- std::make_unique<location::nearby::windows::SubmittableExecutor>();
- std::string output = std::string();
- // Container to note threads that ran
- std::unique_ptr<std::vector<DWORD>> threadIds =
- std::make_unique<std::vector<DWORD>>();
-
- threadIds->push_back(GetCurrentThreadId());
-
- // Act
- auto result = submittableExecutor->DoSubmit([&output, &threadIds]() {
- threadIds->push_back(GetCurrentThreadId());
- output.append(RUNNABLE_0_TEXT.c_str());
- });
-
- submittableExecutor->Shutdown();
-
- // Assert
- // We should've said we were going to run this one
- ASSERT_TRUE(result);
- // We should've run 1 time on the main thread, and 1 times on the
- // workerThread
- ASSERT_EQ(threadIds->size(), 2);
- // We should still be on the main thread
- ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
- // We should've run all runnables on the worker thread
- ASSERT_EQ(output, expected);
-}
-
-TEST(SubmittableExecutorTests,
- SingleThreadedDoSubmitAfterShutdownReturnsFalse) {
- // Arrange
- std::string expected("");
-
- std::unique_ptr<location::nearby::windows::SubmittableExecutor>
- submittableExecutor =
- std::make_unique<location::nearby::windows::SubmittableExecutor>();
- std::unique_ptr<std::string> output = std::make_unique<std::string>();
- // Container to note threads that ran
- std::unique_ptr<std::vector<DWORD>> threadIds =
- std::make_unique<std::vector<DWORD>>();
-
- threadIds->push_back(GetCurrentThreadId());
-
- submittableExecutor->Shutdown();
-
- // Act
- auto result = submittableExecutor->DoSubmit([&output, &threadIds]() {
- threadIds->push_back(GetCurrentThreadId());
- output->append(RUNNABLE_0_TEXT.c_str());
- });
-
- // Assert
- // We should've said we were going to run this one
- ASSERT_FALSE(result);
- // We should've run 1 time on the main thread, and 1 times on the
- // workerThread
- ASSERT_EQ(threadIds->size(), 1);
- // We should still be on the main thread
- ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
- // We should've run all runnables on the worker thread
- ASSERT_EQ(*output.get(), expected);
-}
-
-TEST(SubmittableExecutorTests, SingleThreadedExecuteMultipleTasksSucceeds) {
- // Arrange
- std::string expected(RUNNABLE_ALL_TEXT.c_str());
-
- std::unique_ptr<location::nearby::windows::SubmittableExecutor>
- submittableExecutor =
- std::make_unique<location::nearby::windows::SubmittableExecutor>();
- std::unique_ptr<std::string> output = std::make_unique<std::string>();
- // Container to note threads that ran
- std::unique_ptr<std::vector<DWORD>> threadIds =
- std::make_unique<std::vector<DWORD>>();
-
- threadIds->push_back(GetCurrentThreadId());
-
- // Act
- for (int index = 0; index < 5; index++) {
- submittableExecutor->Execute([&output, &threadIds, index]() {
- threadIds->push_back(GetCurrentThreadId());
- char buffer[128];
- snprintf(buffer, sizeof(buffer), "%s%d, ", RUNNABLE_TEXT.c_str(), index);
- output->append(std::string(buffer));
- });
- }
-
- submittableExecutor->Shutdown();
-
- // Assert
- // We should've run 1 time on the main thread, and 5 times on the
- // workerThread
- ASSERT_EQ(threadIds->size(), 6);
- // We should still be on the main thread
- ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
- // We should've run all runnables on the worker thread
- auto workerThreadId = threadIds->at(1);
- for (int index = 1; index < threadIds->size(); index++) {
- ASSERT_EQ(threadIds->at(index), workerThreadId);
- }
-
- // We should of run them in the order submitted
- ASSERT_EQ(*output.get(), expected);
-}
-
-TEST(SubmittableExecutorTests, SingleThreadedDoSubmitMultipleTasksSucceeds) {
- // Arrange
- std::string expected(RUNNABLE_ALL_TEXT.c_str());
-
- std::unique_ptr<location::nearby::windows::SubmittableExecutor>
- submittableExecutor =
- std::make_unique<location::nearby::windows::SubmittableExecutor>();
- std::unique_ptr<std::string> output = std::make_unique<std::string>();
- // Container to note threads that ran
- std::unique_ptr<std::vector<DWORD>> threadIds =
- std::make_unique<std::vector<DWORD>>();
-
- threadIds->push_back(GetCurrentThreadId());
-
- // Act
- bool result = true;
- for (int index = 0; index < 5; index++) {
- result &= submittableExecutor->DoSubmit([&output, &threadIds, index]() {
- threadIds->push_back(GetCurrentThreadId());
- char buffer[128];
- snprintf(buffer, sizeof(buffer), "%s%d, ", RUNNABLE_TEXT.c_str(), index);
- output->append(std::string(buffer));
- });
- }
-
- submittableExecutor->Shutdown();
-
- // Assert
- // All of these should have submitted
- ASSERT_TRUE(result);
- // We should've run 1 time on the main thread, and 5 times on the
- // workerThread
- ASSERT_EQ(threadIds->size(), 6);
- // We should still be on the main thread
- ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
- // We should've run all runnables on the worker thread
- auto workerThreadId = threadIds->at(1);
- for (int index = 1; index < threadIds->size(); index++) {
- ASSERT_EQ(threadIds->at(index), workerThreadId);
- }
-
- // We should of run them in the order submitted
- ASSERT_EQ(*output.get(), expected);
-}
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/system_clock.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/system_clock.cc
deleted file mode 100644
index ac72ab1bc0a..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/system_clock.cc
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright 2021 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_SYSTEM_CLOCK_H_
-#define PLATFORM_IMPL_WINDOWS_SYSTEM_CLOCK_H_
-
-#include "platform/api/system_clock.h"
-
-namespace location {
-namespace nearby {
-
-// Initialize global system state.
-void SystemClock::Init() { }
-
-// Returns current absolute time. It is guaranteed to be monotonic.
-absl::Time SystemClock::ElapsedRealtime() {
- return absl::FromUnixNanos(
- std::chrono::duration_cast<std::chrono::nanoseconds>(
- std::chrono::steady_clock::now().time_since_epoch())
- .count());
-}
-
-// Pauses current thread for the specified duration.
-Exception SystemClock::Sleep(absl::Duration duration) {
- absl::SleepFor(duration);
- return {Exception::kSuccess};
-}
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_WINDOWS_SYSTEM_CLOCK_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/test_utils.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/test_utils.cc
deleted file mode 100644
index 9bd73b5e077..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/test_utils.cc
+++ /dev/null
@@ -1,57 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/windows/test_utils.h"
-
-#include <shlobj.h>
-
-#include "absl/strings/str_cat.h"
-
-namespace test_utils {
-std::wstring StringToWideString(const std::string& s) {
- int len;
- int slength = (int)s.length() + 1;
- len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
- wchar_t* buf = new wchar_t[len];
- MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
- std::wstring r(buf);
- delete[] buf;
- return r;
-}
-
-std::string GetPayloadPath(location::nearby::PayloadId payload_id) {
- PWSTR basePath;
-
- // Retrieves the full path of a known folder identified by the folder's
- // KNOWNFOLDERID.
- // https://docs.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetknownfolderpath
- SHGetKnownFolderPath(
- FOLDERID_Downloads, // rfid: A reference to the KNOWNFOLDERID that
- // identifies the folder.
- 0, // dwFlags: Flags that specify special retrieval options.
- NULL, // hToken: An access token that represents a particular user.
- &basePath); // ppszPath: When this method returns, contains the address
- // of a pointer to a null-terminated Unicode string that
- // specifies the path of the known folder. The calling
- // process is responsible for freeing this resource once it
- // is no longer needed by calling CoTaskMemFree, whether
- // SHGetKnownFolderPath succeeds or not.
-
- char* fullpathUTF8 = new char((wcslen(basePath) + 1) * sizeof(char));
- wcstombs(fullpathUTF8, basePath, (wcslen(basePath) + 1) * sizeof(char));
- std::string fullPath = std::string(fullpathUTF8);
- auto retval = absl::StrCat(fullPath += "/", payload_id);
- return retval;
-}
-} // namespace test_utils
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/test_utils.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/test_utils.h
deleted file mode 100644
index ef95b1d836e..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/test_utils.h
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_TEST_UTILS_H_
-#define PLATFORM_IMPL_WINDOWS_TEST_UTILS_H_
-
-#include <Windows.h>
-#include <stdio.h>
-
-#include <string>
-#include <xstring>
-
-#include "platform/base/payload_id.h"
-
-#define TEST_BUFFER_SIZE 256
-#define TEST_PAYLOAD_ID 64l
-#define TEST_STRING \
- "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas " \
- "eleifend nisl at magna maximus, id finibus mauris ultrices. Mauris " \
- "interdum efficitur turpis eget auctor. Nullam commodo metus et ante " \
- "bibendum molestie. Donec iaculis ante nec diam rutrum egestas. Proin " \
- "maximus metus luctus rutrum congue. Integer et eros nunc. Etiam purus " \
- "neque, tincidunt eu elementum in, pharetra sit amet magna. Quisque " \
- "consequat aliquam aliquam. Vestibulum ante ipsum primis in faucibus orci " \
- "luctus et ultrices posuere cubilia curae; Maecenas a semper eros, a " \
- "auctor mi. In luctus diam sem, eu pretium nisi porttitor ac. Sed cursus, " \
- "arcu in bibendum feugiat, leo erat finibus massa, ut tincidunt magna nunc " \
- "eu tellus. Cras feugiat ornare vestibulum. Nullam at ipsum vestibulum " \
- "sapien luctus dictum ac vel ligula."
-
-namespace test_utils {
-std::wstring StringToWideString(const std::string& s);
-std::string GetPayloadPath(location::nearby::PayloadId payload_id);
-} // namespace test_utils
-
-#endif // PLATFORM_IMPL_WINDOWS_TEST_UTILS_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/thread_pool.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/thread_pool.cc
deleted file mode 100644
index 963188cfc05..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/thread_pool.cc
+++ /dev/null
@@ -1,531 +0,0 @@
-// Copyright 2021 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/windows/thread_pool.h"
-
-#include <stdio.h>
-
-#include <iomanip>
-#include <iostream>
-
-#include "platform/impl/windows/runner.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-#define POOL_NAME_BUFFER_SIZE 64
-#define EVENT_NAME_BUFFER_SIZE 64
-
-__declspec(align(8)) volatile long ThreadPool::instance_ = // NOLINT
- 0; // NOLINT because the Windows function takes a volatile long
-
-DWORD WINAPI ThreadPool::_ThreadProc(LPVOID pParam) {
- DWORD wait;
- ThreadPool* pool;
- DWORD threadId = GetCurrentThreadId();
- HANDLE waits[2];
- std::unique_ptr<Runner> runner;
-
- _ASSERT(pParam != NULL);
- if (NULL == pParam) {
- NEARBY_LOGS(ERROR) << __func__ << ": pParam must not be null.";
- return -1;
- }
-
- NEARBY_LOGS(VERBOSE) << "Info: " << __func__
- << ": Starting thread id: " << threadId;
-
- pool = static_cast<ThreadPool*>(pParam);
- waits[0] = pool->GetWaitHandle(threadId);
- waits[1] = pool->GetShutdownHandle();
-
-loop_here:
- wait = WaitForMultipleObjects(2, waits, FALSE, INFINITE);
- if (wait == 1) {
- if (pool->CheckThreadStop()) {
- if (pool->GetWorkingThreadCount() < 1) {
- NEARBY_LOGS(VERBOSE) << "Info: " << __func__
- << ": Pool is being destroyed, and working thread "
- "count is 0, thread exiting.";
-
- return 0;
- }
- }
- }
-
- // a new function was added, go and get it
- runner = nullptr;
-
- NEARBY_LOGS(VERBOSE) << "Info: " << __func__ << ": On thread id: " << threadId
- << ", checking for work.";
-
- if (pool->GetThreadProc(threadId, std::move(runner))) {
- pool->BusyNotify(threadId);
- runner->Run();
- pool->FinishNotify(threadId); // tell the pool, i am now free
- }
-
- goto loop_here;
-
- NEARBY_LOGS(VERBOSE) << "Info: " << __func__ << ": Thread shutdown occurred.";
-
- return 0;
-}
-
-ThreadPool::ThreadPool(int nPoolSize, bool bCreateNow)
- : function_list_(std::make_unique<FunctionList>()),
- thread_map_(std::make_unique<ThreadMap>()),
- thread_handles_(nullptr),
- wait_for_threads_to_die_ms_(500),
- notify_shutdown_(nullptr) {
- // The MAXIMUM_WAIT_OBJECTS is the limiting factor, currently
- // windows has a max of 64. This means we can only wait on up
- // to 64 threads, anything more gives undesirable results.
- if (nPoolSize > 63) {
- NEARBY_LOGS(ERROR) << __func__ << ": Thread pool max size exceeded.";
- throw ThreadPoolException("Thread pool max size exceeded.");
- }
-
- pool_state_ = State::Destroyed;
- pool_size_ = nPoolSize;
-
- InitializeCriticalSection(&critical_section_);
-
- if (bCreateNow) {
- if (!Create()) {
- NEARBY_LOGS(ERROR) << __func__ << ": Thread pool creation failed.";
- throw ThreadPoolException("Thread pool creation failed.");
- }
- }
-}
-
-bool ThreadPool::Create() {
- if (pool_state_ != State::Destroyed) {
- // To create a new pool, destroy the existing one first
- NEARBY_LOGS(ERROR) << __func__
- << ": Attempt to create a new thread pool before "
- "destroying the old one.";
- return false;
- }
-
- char buffer[POOL_NAME_BUFFER_SIZE];
- snprintf(buffer, POOL_NAME_BUFFER_SIZE, "Pool%d",
- (uint32_t)(InterlockedIncrement(
- &ThreadPool::instance_))); // InterlockedIncrement done here
- // since there's no access to the
- // instance_ var except through the
- // interlocked functions
- pool_name_ = std::string(buffer);
-
- // create the event which will signal the threads to stop
- std::string eventName;
- notify_shutdown_ = CreateEvent(NULL, TRUE, FALSE, NULL);
- _ASSERT(notify_shutdown_ != NULL);
- if (!notify_shutdown_) {
- NEARBY_LOGS(ERROR) << "Error: " << __func__
- << ": Failed to create thread shut down event.";
-
- return false;
- }
-
- SYSTEM_INFO sysinfo;
- GetSystemInfo(&sysinfo);
- int numCPU = sysinfo.dwNumberOfProcessors;
-
- int threadsToCreate = 0;
-
- // We are going to initially allocate the first n
- // threads based on the number of logical cores
- if (pool_size_ > numCPU) {
- threadsToCreate = STARTUP_THREAD_COUNT;
- } else {
- threadsToCreate = pool_size_;
- }
-
- thread_handles_ = new HANDLE[pool_size_];
-
- // create the threads
- for (int index = 0; index < threadsToCreate; index++) {
- CreateThreadPoolThread(&thread_handles_[index]);
- }
-
- pool_state_ = State::Ready;
- return true;
-}
-
-ThreadPool::~ThreadPool() {
- Destroy();
- ReleaseMemory();
- DeleteCriticalSection(&critical_section_);
-}
-
-DWORD ThreadPool::CreateThreadPoolThread(HANDLE* handles) {
- HANDLE thread;
- DWORD threadId;
- std::unique_ptr<ThreadData> threadData = std::make_unique<ThreadData>();
-
- char buffer[EVENT_NAME_BUFFER_SIZE];
-
- snprintf(buffer, EVENT_NAME_BUFFER_SIZE, "PID:%ld IID:%d TDX:%d",
- GetCurrentProcessId(),
- (uint32_t)(InterlockedAdd(&ThreadPool::instance_, 0)),
- (int)thread_map_->size());
-
- thread = CreateThread(NULL, 0, ThreadPool::_ThreadProc, this,
- CREATE_SUSPENDED, &threadId);
-
- _ASSERT(NULL != thread);
-
- if (NULL == thread) {
- NEARBY_LOGS(ERROR) << "Error: " << __func__ << ": Failed to create thread.";
- return NULL;
- }
-
- if (thread) {
- // add the entry to the map of threads
- EnterCriticalSection(&critical_section_);
-
- threadData->free = true;
- threadData->wait_handle = CreateEventA(NULL, TRUE, FALSE, buffer);
-
- threadData->thread_handle = thread;
- threadData->thread_id = threadId;
-
- thread_map_->insert(ThreadMap::value_type(threadId, std::move(threadData)));
- *handles = thread;
- LeaveCriticalSection(&critical_section_);
-
- ResumeThread(thread);
-
- NEARBY_LOGS(VERBOSE) << "Info: " << __func__
- << ": Thread created, handle: " << thread
- << ", id: " << threadId;
-
- return threadId;
- } else {
- NEARBY_LOGS(ERROR) << "Error: " << __func__ << ": Failed to create thread.";
- return NULL;
- }
-}
-
-void ThreadPool::ReleaseMemory() {
- // empty all collections
- EnterCriticalSection(&critical_section_);
-
- NEARBY_LOGS(VERBOSE) << "Info: " << __func__
- << ": Clearing the function list.";
-
- function_list_->clear();
-
- NEARBY_LOGS(VERBOSE) << "Info: " << __func__ << ": Clearing the thread map.";
-
- thread_map_->clear();
-
- LeaveCriticalSection(&critical_section_);
-}
-
-void ThreadPool::Destroy() {
- if (pool_state_ == State::Destroying || pool_state_ == State::Destroyed)
- return;
-
- NEARBY_LOGS(VERBOSE) << "Info: " << __func__ << ": Destroying thread pool.";
-
- pool_state_ = State::Destroying;
-
- bool notDone = true;
-
- EnterCriticalSection(&critical_section_);
-
- ThreadMap::iterator iter = thread_map_->begin();
- int index = 0;
-
- // Build an array of handles
- while (iter != thread_map_->end()) {
- thread_handles_[index] = iter->second->thread_handle;
- index++;
- iter++;
- }
-
- LeaveCriticalSection(&critical_section_);
-
- // tell all threads to shutdown.
- _ASSERT(NULL != notify_shutdown_);
- SetEvent(GetShutdownHandle());
-
- NEARBY_LOGS(VERBOSE) << "Info: " << __func__
- << ": Setting waits for the threads to exit.";
-
- if (pool_size_ == 1) {
- // Waits until the specified object is in the signaled state or the time-out
- // interval elapses.
- // https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitforsingleobject
- auto wait = WaitForSingleObject(
- thread_handles_[0], // A handle to the object
- INFINITE // The time-out interval, in milliseconds.
- );
- } else {
- auto wait =
- // Waits until one or all of the specified objects are in the signaled
- // state or the time-out interval elapses.
- // https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitformultipleobjects
- WaitForMultipleObjects(
- index, // The number of object handles in the array.
- thread_handles_, // An array of object handles.
- true, // If this parameter is TRUE, the function returns when the
- // state of all objects in the handles array are signaled.
- INFINITE // The time-out interval, in milliseconds.
- );
- }
-
- NEARBY_LOGS(VERBOSE) << "Info: " << __func__ << ": All threads have exited.";
-
- delete[] thread_handles_;
-
- // close the shutdown event
- CloseHandle(notify_shutdown_);
- notify_shutdown_ = NULL;
-
- EnterCriticalSection(&critical_section_);
-
- ThreadMap::iterator threadMapIterator;
-
- // walk through the events and threads and close them all
- for (threadMapIterator = thread_map_->begin();
- threadMapIterator != thread_map_->end(); threadMapIterator++) {
- NEARBY_LOGS(VERBOSE) << "Info: " << __func__ << ": Closing thread handle: "
- << threadMapIterator->second->thread_handle
- << " thread id: "
- << threadMapIterator->second->thread_id
- << " wait_handle: "
- << threadMapIterator->second->wait_handle;
-
- CloseHandle(threadMapIterator->second->wait_handle);
- CloseHandle(threadMapIterator->second->thread_handle);
- }
-
- LeaveCriticalSection(&critical_section_);
-
- NEARBY_LOGS(VERBOSE) << "Info: " << __func__
- << ": Sending the shutdown event.";
-
- ReleaseMemory(); // free any remaining UserPoolData objects
-
- InterlockedDecrement(&ThreadPool::instance_);
-
- pool_state_ = State::Destroyed;
-}
-
-int ThreadPool::GetPoolSize() { return pool_size_; }
-
-void ThreadPool::SetPoolSize(int nSize) {
- _ASSERT(nSize > 0);
-
- if (nSize <= 0) {
- NEARBY_LOGS(ERROR)
- << __func__ << ": 0 or negative value is not a valid thread pool size.";
- return;
- }
-
- pool_size_ = nSize;
-}
-
-HANDLE ThreadPool::GetShutdownHandle() { return notify_shutdown_; }
-
-bool ThreadPool::GetThreadProc(DWORD threadId,
- std::unique_ptr<Runner>&& runner) {
- // get the first function info in the function list
- FunctionList::iterator functionListIterator;
- bool haveAnotherRunner = false;
-
- EnterCriticalSection(&critical_section_);
-
- functionListIterator = function_list_->begin();
-
- if (functionListIterator != function_list_->end()) {
- runner = std::move(*functionListIterator);
-
- NEARBY_LOGS(VERBOSE) << "Info: " << __func__
- << ": popping runner from the front.";
-
- function_list_->pop_front(); // remove the function from the list
-
- haveAnotherRunner = true;
- } else {
- thread_map_->at(threadId)->free = true;
- ResetEvent(thread_map_->at(threadId)->wait_handle);
- }
-
- LeaveCriticalSection(&critical_section_);
-
- return haveAnotherRunner;
-}
-
-void ThreadPool::FinishNotify(DWORD threadId) {
- ThreadMap::iterator threadMapIterator;
-
- EnterCriticalSection(&critical_section_);
-
- threadMapIterator = thread_map_->find(threadId);
-
- if (threadMapIterator == thread_map_->end()) // if search found no elements
- {
- _ASSERT(!"No matching thread found.");
- NEARBY_LOGS(ERROR) << __func__ << ": No matching thread found.";
- } else {
- thread_map_->at(threadId)->free = true;
-
- if (!function_list_->empty()) {
- // there are some more functions that need servicing, lets do that.
- // By not doing anything here we are letting the thread go back and
- // check the function list and pick up a function and execute it.
- thread_map_->at(threadId)->free = false;
- } else {
- ResetEvent(thread_map_->at(threadId)->wait_handle);
- }
- }
-
- LeaveCriticalSection(&critical_section_);
-}
-
-void ThreadPool::BusyNotify(DWORD threadId) {
- ThreadMap::iterator iter;
-
- EnterCriticalSection(&critical_section_);
-
- iter = thread_map_->find(threadId);
-
- if (iter == thread_map_->end()) // if search found no elements
- {
- _ASSERT(!"No matching thread found.");
- } else {
- thread_map_->at(threadId)->free = false;
- }
-
- LeaveCriticalSection(&critical_section_);
-}
-
-bool ThreadPool::Run(std::unique_ptr<Runner> runner) {
- if (pool_state_ == State::Destroying || pool_state_ == State::Destroyed)
- return false;
-
- _ASSERT(runner != NULL);
-
- AddRunner(std::move(runner));
-
- // See if any threads are free
- ThreadMap::iterator iterator;
- std::unique_ptr<ThreadData> threadData;
-
- bool freeThreadFound = false;
-
- EnterCriticalSection(&critical_section_);
-
- for (iterator = thread_map_->begin(); iterator != thread_map_->end();
- iterator++) {
- if (iterator->second->free) {
- // here is a free thread, put it to work
- iterator->second->free = false;
- SetEvent(iterator->second->wait_handle);
- // this thread will now call GetThreadProc() and pick up the next
- // function in the list.
- freeThreadFound = true;
- break;
- }
- }
-
- if (!freeThreadFound && thread_map_->size() < pool_size_) {
- // We haven't used up all of our threads, go ahead and spin up another one
- DWORD threadId =
- CreateThreadPoolThread(&thread_handles_[thread_map_->size()]);
- thread_map_->at(threadId)->free = false;
- SetEvent(thread_map_->at(threadId)->wait_handle);
- }
-
- LeaveCriticalSection(&critical_section_);
-
- return true;
-}
-
-void ThreadPool::AddRunner(std::unique_ptr<Runner> runner) {
- // add it to the list
- runner->thread_pool_ = this;
-
- NEARBY_LOGS(VERBOSE) << "Info: " << __func__
- << ": pushing new runner to the back.";
-
- EnterCriticalSection(&critical_section_);
-
- function_list_->push_back(std::move(runner));
-
- LeaveCriticalSection(&critical_section_);
-}
-
-HANDLE ThreadPool::GetWaitHandle(DWORD dwThreadId) {
- HANDLE hWait = NULL;
- ThreadMap::iterator iter;
-
- EnterCriticalSection(&critical_section_);
-
- iter = thread_map_->find(dwThreadId);
-
- if (iter != thread_map_->end()) // if search found no elements
- {
- hWait = thread_map_->at(dwThreadId)->wait_handle;
- }
-
- LeaveCriticalSection(&critical_section_);
-
- return hWait;
-}
-
-bool ThreadPool::CheckThreadStop() {
- EnterCriticalSection(&critical_section_);
-
- bool bRet =
- (pool_state_ == State::Destroying || pool_state_ == State::Destroyed);
-
- LeaveCriticalSection(&critical_section_);
-
- return bRet;
-}
-
-int ThreadPool::GetWorkingThreadCount() {
- ThreadMap::iterator iter;
-
- int nCount = 0;
-
- EnterCriticalSection(&critical_section_);
-
- for (iter = thread_map_->begin(); iter != thread_map_->end(); iter++) {
- if (function_list_->empty()) {
- iter->second->free = true;
- }
-
- if (!iter->second->free) {
- nCount++;
- }
- }
-
- LeaveCriticalSection(&critical_section_);
-
- return nCount;
-}
-
-State ThreadPool::GetState() { return pool_state_; }
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/thread_pool.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/thread_pool.h
deleted file mode 100644
index d40efc0bc53..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/thread_pool.h
+++ /dev/null
@@ -1,106 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-#ifndef PLATFORM_IMPL_WINDOWS_THREAD_POOL_H_
-#define PLATFORM_IMPL_WINDOWS_THREAD_POOL_H_
-#include <windows.h>
-
-#include <functional>
-#include <list>
-#include <map>
-#include <stdexcept>
-
-#include "platform/impl/windows/runner.h"
-namespace location {
-namespace nearby {
-namespace windows {
-
-// This is the number of threads that will be started initially if the pool
-// size is greater than 4, or if the pool size is greater than the number
-// of cores present, including virtual cores
-#define STARTUP_THREAD_COUNT 4
-
-class ThreadPoolException : public std::runtime_error {
- public:
- ThreadPoolException() : std::runtime_error("") {}
- ThreadPoolException(const std::string& message)
- : std::runtime_error(message), message_(message) {}
- virtual const char* what() const throw() {
- return message_.c_str();
- }
-
- private:
- const std::string message_;
-};
-
-// all functions passed in by clients will be initially stored in this list.
-typedef std::list<std::unique_ptr<Runner>> FunctionList;
-// info about threads in the pool will be saved using this struct.
-typedef struct tagThreadData {
- bool free;
- HANDLE wait_handle;
- HANDLE thread_handle;
- DWORD thread_id;
-} ThreadData;
-// info about all threads belonging to this pool will be stored in this map
-typedef std::map<DWORD, std::unique_ptr<ThreadData>>
- ThreadMap;
-enum class State {
- Ready, // has been created
- Destroying, // in the process of getting destroyed, no request is processed /
- // accepted
- Destroyed // Destroyed, no threads are available, request can still be queued
-};
-class ThreadPool {
- public:
- ThreadPool(int nPoolSize, bool bCreateNow);
- virtual ~ThreadPool();
- bool Create(); // creates the thread pool
- void Destroy(); // destroy the thread pool
- int GetPoolSize();
- void SetPoolSize(int);
- bool Run(std::unique_ptr<Runner> runObject);
- bool CheckThreadStop();
- int GetWorkingThreadCount();
- State GetState();
-
- private:
- static DWORD WINAPI _ThreadProc(LPVOID);
- std::unique_ptr<FunctionList> function_list_;
- std::unique_ptr<ThreadMap> thread_map_;
- HANDLE* thread_handles_ = nullptr;
- int pool_size_;
- int wait_for_threads_to_die_ms_; // In milli-seconds
- std::string pool_name_; // To assist in logging and debug
- HANDLE notify_shutdown_; // notifies threads that a new function
- // is added
- volatile State pool_state_;
- static __declspec(
- align(8)) volatile long instance_; // NOLINT Windows function takes
- // volatile long
- CRITICAL_SECTION critical_section_;
-
- bool GetThreadProc(DWORD dwThreadId, std::unique_ptr<Runner>&& runner);
- void FinishNotify(DWORD dwThreadId);
- void BusyNotify(DWORD dwThreadId);
- void ReleaseMemory();
- HANDLE GetWaitHandle(DWORD dwThreadId);
- HANDLE GetShutdownHandle();
- void AddRunner(std::unique_ptr<Runner> runner);
- DWORD CreateThreadPoolThread(HANDLE* handles);
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-#endif // PLATFORM_IMPL_WINDOWS_THREAD_POOL_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/utils.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/utils.cc
deleted file mode 100644
index aba74eb97b2..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/utils.cc
+++ /dev/null
@@ -1,127 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/windows/utils.h"
-
-// Windows headers
-#include <strsafe.h>
-
-// Standard C/C++ headers
-#include <codecvt>
-#include <exception>
-#include <string>
-
-// Third party headers
-#include "absl/strings/ascii.h"
-#include "absl/strings/str_format.h"
-
-// Nearby connections headers
-#include "platform/api/crypto.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-std::string uint64_to_mac_address_string(uint64_t bluetoothAddress) {
- std::string buffer = absl::StrFormat(
- "%2llx:%2llx:%2llx:%2llx:%2llx:%2llx", bluetoothAddress >> 40,
- (bluetoothAddress >> 32) & 0xff, (bluetoothAddress >> 24) & 0xff,
- (bluetoothAddress >> 16) & 0xff, (bluetoothAddress >> 8) & 0xff,
- bluetoothAddress & 0xff);
-
- return absl::AsciiStrToUpper(buffer);
-}
-
-std::wstring string_to_wstring(std::string str) {
- std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
- return converter.from_bytes(str);
-}
-
-std::string wstring_to_string(std::wstring wstr) {
- std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
- return converter.to_bytes(wstr);
-}
-
-ByteArray Sha256(absl::string_view input, size_t size) {
- ByteArray hash = location::nearby::Crypto::Sha256(input);
- return ByteArray{hash.data(), size};
-}
-
-uint16 InspectableReader::ReadUint16(IInspectable inspectable) {
- auto property_value =
- inspectable.try_as<winrt::Windows::Foundation::IPropertyValue>();
- if (property_value == nullptr) {
- throw std::invalid_argument("no property value interface.");
- }
- if (property_value.Type() !=
- winrt::Windows::Foundation::PropertyType::UInt16) {
- throw std::invalid_argument("not uin16 data type.");
- }
-
- return property_value.GetUInt16();
-}
-
-uint32 InspectableReader::ReadUint32(IInspectable inspectable) {
- auto property_value =
- inspectable.try_as<winrt::Windows::Foundation::IPropertyValue>();
- if (property_value == nullptr) {
- throw std::invalid_argument("no property value interface.");
- }
- if (property_value.Type() !=
- winrt::Windows::Foundation::PropertyType::UInt32) {
- throw std::invalid_argument("not uin32 data type.");
- }
-
- return property_value.GetUInt32();
-}
-
-std::string InspectableReader::ReadString(IInspectable inspectable) {
- auto property_value =
- inspectable.try_as<winrt::Windows::Foundation::IPropertyValue>();
- if (property_value == nullptr) {
- throw std::invalid_argument("no property value interface.");
- }
- if (property_value.Type() !=
- winrt::Windows::Foundation::PropertyType::String) {
- throw std::invalid_argument("not string data type.");
- }
-
- return wstring_to_string(property_value.GetString().c_str());
-}
-
-std::vector<std::string> InspectableReader::ReadStringArray(
- IInspectable inspectable) {
- std::vector<std::string> result;
- auto property_value =
- inspectable.try_as<winrt::Windows::Foundation::IPropertyValue>();
- if (property_value == nullptr) {
- throw std::invalid_argument("no property value interface.");
- }
- if (property_value.Type() !=
- winrt::Windows::Foundation::PropertyType::StringArray) {
- throw std::invalid_argument("not string array data type.");
- }
-
- winrt::com_array<winrt::hstring> strings;
- property_value.GetStringArray(strings);
-
- for (winrt::hstring str : strings) {
- result.push_back(winrt::to_string(str));
- }
- return result;
-}
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/utils.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/utils.h
deleted file mode 100644
index 054678da5fb..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/utils.h
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_UTILS_H_
-#define PLATFORM_IMPL_WINDOWS_UTILS_H_
-
-#include <Windows.h>
-#include <stdio.h>
-
-#include <string>
-
-#include "absl/strings/string_view.h"
-#include "platform/base/byte_array.h"
-#include "platform/impl/windows/generated/winrt/Windows.Foundation.h"
-#include "platform/impl/windows/generated/winrt/base.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-using winrt::Windows::Foundation::IInspectable;
-
-std::string uint64_to_mac_address_string(uint64_t bluetoothAddress);
-
-// Helpers to windows platform
-std::wstring string_to_wstring(std::string str);
-std::string wstring_to_string(std::wstring wstr);
-ByteArray Sha256(absl::string_view input, size_t size);
-
-namespace Constants {
-// The Id of the Service Name SDP attribute
-const uint16_t SdpServiceNameAttributeId = 0x100;
-
-// The SDP Type of the Service Name SDP attribute.
-// The first byte in the SDP Attribute encodes the SDP Attribute Type as
-// follows:
-// - the Attribute Type size in the least significant 3 bits,
-// - the SDP Attribute Type value in the most significant 5 bits.
-const char SdpServiceNameAttributeType = (4 << 3) | 5;
-} // namespace Constants
-
-class InspectableReader {
- public:
- static uint16 ReadUint16(IInspectable inspectable);
- static uint32 ReadUint32(IInspectable inspectable);
- static std::string ReadString(IInspectable inspectable);
- static std::vector<std::string> ReadStringArray(IInspectable inspectable);
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_WINDOWS_UTILS_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/utils_test.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/utils_test.cc
deleted file mode 100644
index 96df927e1f0..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/utils_test.cc
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/windows/utils.h"
-
-#include "gtest/gtest.h"
-
-using location::nearby::windows::uint64_to_mac_address_string;
-
-TEST(UtilsTests, MacAddressToString) {
- // Arrange
- const uint64_t input = 0x000034363bc78c71;
- std::string expected = "34:36:3B:C7:8C:71";
-
- // Act
- std::string result = uint64_to_mac_address_string(input);
-
- // Assert
- EXPECT_EQ(result, expected);
-}
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/webrtc.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/webrtc.h
deleted file mode 100644
index 24aa5a92466..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/webrtc.h
+++ /dev/null
@@ -1,78 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_WEBRTC_H_
-#define PLATFORM_IMPL_WINDOWS_WEBRTC_H_
-
-#include "platform/api/webrtc.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-class WebRtcSignalingMessenger : public api::WebRtcSignalingMessenger {
- public:
- // TODO(b/184975123): replace with real implementation.
- ~WebRtcSignalingMessenger() override = default;
-
- // TODO(b/184975123): replace with real implementation.
- bool SendMessage(absl::string_view peer_id,
- const ByteArray& message) override {
- return false;
- }
-
- // TODO(b/184975123): replace with real implementation.
- bool StartReceivingMessages(
- api::WebRtcSignalingMessenger::OnSignalingMessageCallback
- on_message_callback,
- api::WebRtcSignalingMessenger::OnSignalingCompleteCallback
- on_complete_callback) override {
- return false;
- }
- // TODO(b/184975123): replace with real implementation.
- void StopReceivingMessages() override {}
-};
-
-class WebRtcMedium : public api::WebRtcMedium {
- public:
- // TODO(b/184975123): replace with real implementation.
- ~WebRtcMedium() override = default;
-
- // Gets the default two-letter country code associated with current locale.
- // For example, en_US locale resolves to "US".
- // TODO(b/184975123): replace with real implementation.
- const std::string GetDefaultCountryCode() override {
- return "Un-implemented";
- }
-
- // Creates and returns a new webrtc::PeerConnectionInterface object via
- // |callback|.
- // TODO(b/184975123): replace with real implementation.
- void CreatePeerConnection(webrtc::PeerConnectionObserver* observer,
- PeerConnectionCallback callback) override {}
-
- // Returns a signaling messenger for sending WebRTC signaling messages.
- // TODO(b/184975123): replace with real implementation.
- std::unique_ptr<api::WebRtcSignalingMessenger> GetSignalingMessenger(
- absl::string_view self_id,
- const connections::LocationHint& location_hint) override {
- return nullptr;
- }
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_WINDOWS_WEBRTC_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/wifi.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/wifi.h
deleted file mode 100644
index 00ca53580d0..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/wifi.h
+++ /dev/null
@@ -1,98 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_WIFI_H_
-#define PLATFORM_IMPL_WINDOWS_WIFI_H_
-
-#include "platform/api/wifi.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-// Represents a WiFi network found during a call to WifiMedium#scan().
-class WifiScanResult : public api::WifiScanResult {
- public:
- // TODO(b/184975123): replace with real implementation.
- ~WifiScanResult() override = default;
-
- // Gets the SSID of this WiFi network.
- // TODO(b/184975123): replace with real implementation.
- std::string GetSsid() const override { return "Un-implemented"; }
- // Gets the signal strength of this WiFi network in dBm.
- // TODO(b/184975123): replace with real implementation.
- std::int32_t GetSignalStrengthDbm() const override { return 0; }
- // Gets the frequency band of this WiFi network in MHz.
- // TODO(b/184975123): replace with real implementation.
- std::int32_t GetFrequencyMhz() const override { return 0; }
- // Gets the authentication type of this WiFi network.
- // TODO(b/184975123): replace with real implementation.
- api::WifiAuthType GetAuthType() const override {
- return api::WifiAuthType::kUnknown;
- }
-};
-
-// Container of operations that can be performed over the WiFi medium.
-class WifiMedium : public api::WifiMedium {
- public:
- // TODO(b/184975123): replace with real implementation.
- ~WifiMedium() override = default;
-
- class ScanResultCallback : public api::WifiMedium::ScanResultCallback {
- public:
- // TODO(b/184975123): replace with real implementation.
- ~ScanResultCallback() override = default;
-
- // TODO(b/184975123): replace with real implementation.
- void OnScanResults(
- const std::vector<api::WifiScanResult>& scan_results) override {}
- };
-
- // Does not take ownership of the passed-in scan_result_callback -- destroying
- // that is up to the caller.
- // TODO(b/184975123): replace with real implementation.
- bool Scan(const api::WifiMedium::ScanResultCallback& scan_result_callback)
- override {
- return false;
- }
-
- // If 'password' is an empty string, none has been provided. Returns
- // WifiConnectionStatus::CONNECTED on success, or the appropriate failure code
- // otherwise.
- // TODO(b/184975123): replace with real implementation.
- api::WifiConnectionStatus ConnectToNetwork(
- absl::string_view ssid, absl::string_view password,
- api::WifiAuthType auth_type) override {
- return api::WifiConnectionStatus::kUnknown;
- }
-
- // Blocks until it's certain of there being a connection to the internet, or
- // returns false if it fails to do so.
- //
- // How this method wants to verify said connection is totally up to it (so it
- // can feel free to ping whatever server, download whatever resource, etc.
- // that it needs to gain confidence that the internet is reachable hereon in).
- // TODO(b/184975123): replace with real implementation.
- bool VerifyInternetConnectivity() override { return false; }
-
- // Returns the local device's IP address in the IPv4 dotted-quad format.
- // TODO(b/184975123): replace with real implementation.
- std::string GetIpAddress() override { return "Un-implemented"; }
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_WINDOWS_WIFI_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/wifi_lan.h b/chromium/third_party/nearby/src/cpp/platform/impl/windows/wifi_lan.h
deleted file mode 100644
index 5485367b7e0..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/wifi_lan.h
+++ /dev/null
@@ -1,342 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_IMPL_WINDOWS_WIFI_LAN_H_
-#define PLATFORM_IMPL_WINDOWS_WIFI_LAN_H_
-
-// Windows headers
-#include <windows.h> // NOLINT
-#include <win32/windns.h> // NOLINT
-
-// Standard C/C++ headers
-#include <exception>
-#include <functional>
-#include <memory>
-#include <string>
-
-// Nearby connections headers
-#include "absl/base/thread_annotations.h"
-#include "absl/container/flat_hash_map.h"
-#include "absl/container/flat_hash_set.h"
-#include "absl/synchronization/mutex.h"
-#include "platform/api/wifi_lan.h"
-#include "platform/base/exception.h"
-#include "platform/base/input_stream.h"
-#include "platform/base/output_stream.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/mutex.h"
-
-// WinRT headers
-#include "platform/impl/windows/generated/winrt/Windows.Devices.Enumeration.h"
-#include "platform/impl/windows/generated/winrt/Windows.Foundation.Collections.h"
-#include "platform/impl/windows/generated/winrt/Windows.Foundation.h"
-#include "platform/impl/windows/generated/winrt/Windows.Networking.Connectivity.h"
-#include "platform/impl/windows/generated/winrt/Windows.Networking.ServiceDiscovery.Dnssd.h"
-#include "platform/impl/windows/generated/winrt/Windows.Networking.Sockets.h"
-#include "platform/impl/windows/generated/winrt/Windows.Storage.Streams.h"
-#include "platform/impl/windows/generated/winrt/base.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-using winrt::fire_and_forget;
-using winrt::Windows::Devices::Enumeration::DeviceInformation;
-using winrt::Windows::Devices::Enumeration::DeviceInformationKind;
-using winrt::Windows::Devices::Enumeration::DeviceInformationUpdate;
-using winrt::Windows::Devices::Enumeration::DeviceWatcher;
-using winrt::Windows::Foundation::IInspectable;
-using winrt::Windows::Foundation::Collections::IMapView;
-using winrt::Windows::Networking::HostName;
-using winrt::Windows::Networking::Connectivity::NetworkInformation;
-using winrt::Windows::Networking::ServiceDiscovery::Dnssd::
- DnssdRegistrationResult;
-using winrt::Windows::Networking::ServiceDiscovery::Dnssd::
- DnssdRegistrationStatus;
-using winrt::Windows::Networking::ServiceDiscovery::Dnssd::DnssdServiceInstance;
-using winrt::Windows::Networking::Sockets::StreamSocket;
-using winrt::Windows::Networking::Sockets::StreamSocketListener;
-using winrt::Windows::Networking::Sockets::
- StreamSocketListenerConnectionReceivedEventArgs;
-using winrt::Windows::Networking::Sockets::StreamSocketListenerInformation;
-using winrt::Windows::Storage::Streams::Buffer;
-using winrt::Windows::Storage::Streams::DataReader;
-using winrt::Windows::Storage::Streams::IBuffer;
-using winrt::Windows::Storage::Streams::IInputStream;
-using winrt::Windows::Storage::Streams::InputStreamOptions;
-using winrt::Windows::Storage::Streams::IOutputStream;
-
-// WifiLanSocket wraps the socket functions to read and write stream.
-// In WiFi LAN, A WifiLanSocket will be passed to StartAcceptingConnections's
-// call back when StreamSocketListener got connect. When call API to connect to
-// remote WiFi LAN service, also will return a WifiLanSocket to caller.
-class WifiLanSocket : public api::WifiLanSocket {
- public:
- explicit WifiLanSocket(StreamSocket socket);
- WifiLanSocket(WifiLanSocket&) = default;
- WifiLanSocket(WifiLanSocket&&) = default;
- ~WifiLanSocket() override;
- WifiLanSocket& operator=(const WifiLanSocket&) = default;
- WifiLanSocket& operator=(WifiLanSocket&&) = default;
-
- // Returns the InputStream of the WifiLanSocket.
- // On error, returned stream will report Exception::kIo on any operation.
- //
- // The returned object is not owned by the caller, and can be invalidated once
- // the WifiLanSocket object is destroyed.
- InputStream& GetInputStream() override;
-
- // Returns the OutputStream of the WifiLanSocket.
- // On error, returned stream will report Exception::kIo on any operation.
- //
- // The returned object is not owned by the caller, and can be invalidated once
- // the WifiLanSocket object is destroyed.
- OutputStream& GetOutputStream() override;
-
- // Returns Exception::kIo on error, Exception::kSuccess otherwise.
- Exception Close() override;
-
- private:
- // A simple wrapper to handle input stream of socket
- class SocketInputStream : public InputStream {
- public:
- SocketInputStream(IInputStream input_stream);
- ~SocketInputStream() = default;
-
- ExceptionOr<ByteArray> Read(std::int64_t size) override;
- ExceptionOr<size_t> Skip(size_t offset) override;
- Exception Close() override;
-
- private:
- IInputStream input_stream_{nullptr};
- };
-
- // A simple wrapper to handle output stream of socket
- class SocketOutputStream : public OutputStream {
- public:
- SocketOutputStream(IOutputStream output_stream);
- ~SocketOutputStream() = default;
-
- Exception Write(const ByteArray& data) override;
- Exception Flush() override;
- Exception Close() override;
-
- private:
- IOutputStream output_stream_{nullptr};
- };
-
- // Internal properties
- StreamSocket stream_soket_{nullptr};
- SocketInputStream input_stream_{nullptr};
- SocketOutputStream output_stream_{nullptr};
-};
-
-// WifiLanServerSocket provides the support to server socket, this server socket
-// accepts connection from clients.
-class WifiLanServerSocket : public api::WifiLanServerSocket {
- public:
- explicit WifiLanServerSocket(int port = 0);
- WifiLanServerSocket(WifiLanServerSocket&) = default;
- WifiLanServerSocket(WifiLanServerSocket&&) = default;
- ~WifiLanServerSocket() override;
- WifiLanServerSocket& operator=(const WifiLanServerSocket&) = default;
- WifiLanServerSocket& operator=(WifiLanServerSocket&&) = default;
-
- // Returns ip address.
- std::string GetIPAddress() const override;
-
- // Returns port.
- int GetPort() const override;
-
- // Sets port
- void SetPort(int port) { port_ = port; }
-
- StreamSocketListener GetSocketListener() const {
- return stream_socket_listener_;
- }
-
- // Blocks until either:
- // - at least one incoming connection request is available, or
- // - ServerSocket is closed.
- // On success, returns connected socket, ready to exchange data.
- // Returns nullptr on error.
- // Once error is reported, it is permanent, and ServerSocket has to be closed.
- std::unique_ptr<api::WifiLanSocket> Accept() override;
-
- // Called by the server side of a connection before passing ownership of
- // WifiLanServerSocker to user, to track validity of a pointer to this
- // server socket.
- void SetCloseNotifier(std::function<void()> notifier);
-
- // Returns Exception::kIo on error, Exception::kSuccess otherwise.
- Exception Close() override;
-
- // Binds to local port
- bool listen();
-
- private:
- // The listener is accepting incoming connections
- fire_and_forget Listener_ConnectionReceived(
- StreamSocketListener listener,
- StreamSocketListenerConnectionReceivedEventArgs const& args);
-
- // Retrieves IP addresses from local machine
- std::vector<std::string> GetIpAddresses();
-
- mutable absl::Mutex mutex_;
- absl::CondVar cond_;
- std::deque<StreamSocket> pending_sockets_ ABSL_GUARDED_BY(mutex_);
- StreamSocketListener stream_socket_listener_{nullptr};
- winrt::event_token listener_event_token_{};
-
- // Close notifier
- std::function<void()> close_notifier_ = nullptr;
-
- // IP addresses of the computer. mDNS uses them to advertise.
- std::vector<std::string> ip_addresses_{};
-
- // Cache socket not be picked by upper layer
- int port_ = 0;
- bool closed_ = false;
-};
-
-// Container of operations that can be performed over the WifiLan medium.
-class WifiLanMedium : public api::WifiLanMedium {
- public:
- ~WifiLanMedium() override = default;
-
- // Starts to advertising
- bool StartAdvertising(const NsdServiceInfo& nsd_service_info) override;
-
- // Stops to advertising
- bool StopAdvertising(const NsdServiceInfo& nsd_service_info) override;
-
- // Starts to discovery
- bool StartDiscovery(const std::string& service_type,
- DiscoveredServiceCallback callback) override;
-
- // Returns true once WifiLan discovery for service_type is well and truly
- // stopped; after this returns, there must be no more invocations of the
- // DiscoveredServiceCallback passed in to StartDiscovery() for service_type.
- bool StopDiscovery(const std::string& service_type) override;
-
- std::unique_ptr<api::WifiLanSocket> ConnectToService(
- const NsdServiceInfo& remote_service_info,
- CancellationFlag* cancellation_flag) override;
-
- std::unique_ptr<api::WifiLanSocket> ConnectToService(
- const std::string& ip_address, int port,
- CancellationFlag* cancellation_flag) override;
-
- std::unique_ptr<api::WifiLanServerSocket> ListenForService(
- int port = 0) override;
-
- // DnsServiceDeRegister is a async process, after operation finish, callback
- // will call this method to notify the waiting method StopAdvertising to
- // continue.
- void NotifyDnsServiceUnregistered(DWORD status);
-
- private:
- // mDNS text attributes
- static constexpr std::string_view KEY_ENDPOINT_INFO = "n";
-
- // mDNS information for advertising and discovery
- static constexpr std::wstring_view MDNS_HOST_NAME = L"Windows.local";
- static constexpr std::string_view MDNS_INSTANCE_NAME_FORMAT = "%s.%slocal";
- static constexpr std::string_view MDNS_DEVICE_SELECTOR_FORMAT =
- "System.Devices.AepService.ProtocolId:=\"{4526e8c1-8aac-4153-9b16-"
- "55e86ada0e54}\" "
- "AND System.Devices.Dnssd.ServiceName:=\"%s._tcp\" AND "
- "System.Devices.Dnssd.Domain:=\"local\"";
-
- // Nsd status
- static const int MEDIUM_STATUS_IDLE = 0;
- static const int MEDIUM_STATUS_ACCEPTING = (1 << 0);
- static const int MEDIUM_STATUS_ADVERTISING = (1 << 1);
- static const int MEDIUM_STATUS_DISCOVERING = (1 << 2);
-
- // In the class, not using ENUM to describe the mDNS states, because a little
- // complicate to combine all states based on accepting, advertising and
- // discovery.
- bool IsIdle() { return medium_status_ == 0; }
-
- bool IsAccepting() { return (medium_status_ & MEDIUM_STATUS_ACCEPTING) != 0; }
-
- bool IsAdvertising() {
- return (medium_status_ & MEDIUM_STATUS_ADVERTISING) != 0;
- }
-
- bool IsDiscovering() {
- return (medium_status_ & MEDIUM_STATUS_DISCOVERING) != 0;
- }
-
- // From mDNS device information, to build NsdServiceInfo.
- // the properties are from DeviceInformation and DeviceInformationUpdate.
- // The API gets IP addresses, service name and text attributes of mDNS
- // from these properties,
- NsdServiceInfo GetNsdServiceInformation(
- IMapView<winrt::hstring, IInspectable> properties);
-
- // mDNS callbacks for advertising and discovery
- fire_and_forget Watcher_DeviceAdded(DeviceWatcher sender,
- DeviceInformation deviceInfo);
- fire_and_forget Watcher_DeviceUpdated(
- DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate);
- fire_and_forget Watcher_DeviceRemoved(
- DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate);
- static void Advertising_StopCompleted(DWORD Status, PVOID pQueryContext,
- PDNS_SERVICE_INSTANCE pInstance);
-
- // Gets error message from exception pointer
- std::string GetErrorMessage(std::exception_ptr eptr);
-
- //
- // Dns-sd related properties
- //
-
- // Advertising properties
- DnssdServiceInstance dnssd_service_instance_{nullptr};
- DnssdRegistrationResult dnssd_regirstraion_result_{nullptr};
-
- // Stop advertising properties
- DNS_SERVICE_INSTANCE dns_service_instance_{nullptr};
- DNS_SERVICE_REGISTER_REQUEST dns_service_register_request_;
- std::unique_ptr<std::wstring> dns_service_instance_name_{nullptr};
- std::unique_ptr<CountDownLatch> dns_service_stop_latch_;
- DWORD dns_service_stop_status_;
-
- // Discovery properties
- DeviceWatcher device_watcher_{nullptr};
- winrt::event_token device_watcher_added_event_token;
- winrt::event_token device_watcher_updated_event_token;
- winrt::event_token device_watcher_removed_event_token;
-
- // callback for discovery
- api::WifiLanMedium::DiscoveredServiceCallback discovered_service_callback_;
-
- // Protects to access some members
- absl::Mutex mutex_;
-
- // Medium Status
- int medium_status_ = MEDIUM_STATUS_IDLE;
-
- // Keep the server socket listener pointer
- WifiLanServerSocket* server_socket_ptr_ ABSL_GUARDED_BY(mutex_) = nullptr;
-};
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_IMPL_WINDOWS_WIFI_LAN_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/wifi_lan_medium.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/wifi_lan_medium.cc
deleted file mode 100644
index f702fd7baaf..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/wifi_lan_medium.cc
+++ /dev/null
@@ -1,463 +0,0 @@
-// Copyright 2021 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/windows/wifi_lan.h"
-
-// Windows headers
-#include <windows.h>
-
-// Standard C/C++ headers
-#include <codecvt>
-#include <locale>
-#include <string>
-
-// ABSL headers
-#include "absl/strings/str_format.h"
-
-// Nearby connections headers
-#include "platform/base/cancellation_flag_listener.h"
-#include "platform/impl/windows/utils.h"
-#include "platform/public/logging.h"
-#include "platform/public/mutex_lock.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-bool WifiLanMedium::StartAdvertising(const NsdServiceInfo& nsd_service_info) {
- absl::MutexLock lock(&mutex_);
-
- if (!IsAccepting()) {
- NEARBY_LOGS(WARNING)
- << "cannot start advertising without accepting connetions.";
- return false;
- }
-
- if (IsAdvertising()) {
- NEARBY_LOGS(WARNING)
- << "cannot start advertising again when it is running.";
- return false;
- }
-
- if (nsd_service_info.GetTxtRecord(KEY_ENDPOINT_INFO.data()).empty()) {
- NEARBY_LOGS(ERROR) << "cannot start advertising without endpoint info.";
- return false;
- }
-
- if (nsd_service_info.GetServiceName().empty()) {
- NEARBY_LOGS(ERROR) << "cannot start advertising without service name.";
- return false;
- }
-
- std::string instance_name = absl::StrFormat(
- MDNS_INSTANCE_NAME_FORMAT.data(), nsd_service_info.GetServiceName(),
- nsd_service_info.GetServiceType());
-
- NEARBY_LOGS(INFO) << "mDNS instance name is " << instance_name;
-
- dnssd_service_instance_ = DnssdServiceInstance{
- string_to_wstring(instance_name),
- nullptr, // let windows use default computer's local name
- (uint16)nsd_service_info.GetPort()};
-
- // Add TextRecords from NsdServiceInfo
- auto text_attributes = dnssd_service_instance_.TextAttributes();
-
- auto text_records = nsd_service_info.GetTxtRecords();
- auto it = text_records.begin();
- while (it != text_records.end()) {
- text_attributes.Insert(string_to_wstring(it->first),
- string_to_wstring(it->second));
- it++;
- }
-
- dnssd_regirstraion_result_ = dnssd_service_instance_
- .RegisterStreamSocketListenerAsync(
- server_socket_ptr_->GetSocketListener())
- .get();
-
- if (dnssd_regirstraion_result_.HasInstanceNameChanged()) {
- NEARBY_LOGS(WARNING) << "advertising instance name was changed due to have "
- "same name instance was running.";
- // stop the service and return false
- StopAdvertising(nsd_service_info);
- return false;
- }
-
- if (dnssd_regirstraion_result_.Status() == DnssdRegistrationStatus::Success) {
- NEARBY_LOGS(INFO) << "started to advertising.";
- medium_status_ |= MEDIUM_STATUS_ADVERTISING;
- return true;
- }
-
- // Clean up
- NEARBY_LOGS(ERROR)
- << "failed to start advertising due to registration failure.";
- dnssd_service_instance_ = nullptr;
- dnssd_regirstraion_result_ = nullptr;
- return false;
-}
-
-// Win32 call only can use globel function or static method in class
-void WifiLanMedium::Advertising_StopCompleted(DWORD Status, PVOID pQueryContext,
- PDNS_SERVICE_INSTANCE pInstance) {
- NEARBY_LOGS(INFO) << "unregister with status=" << Status;
- try {
- WifiLanMedium* medium = static_cast<WifiLanMedium*>(pQueryContext);
- medium->NotifyDnsServiceUnregistered(Status);
- } catch (...) {
- NEARBY_LOGS(ERROR) << "failed to notify the stop of DNS service instance."
- << Status;
- }
-}
-
-void WifiLanMedium::NotifyDnsServiceUnregistered(DWORD status) {
- if (dns_service_stop_latch_.get() != nullptr) {
- dns_service_stop_status_ = status;
- dns_service_stop_latch_.get()->CountDown();
- }
-}
-
-bool WifiLanMedium::StopAdvertising(const NsdServiceInfo& nsd_service_info) {
- // Need to use Win32 API to deregister the Dnssd instance
- if (!IsAdvertising()) {
- NEARBY_LOGS(WARNING)
- << "Cannot stop advertising because no advertising is running.";
- return false;
- }
-
- // Init DNS service instance
- std::string instance_name = absl::StrFormat(
- MDNS_INSTANCE_NAME_FORMAT.data(), nsd_service_info.GetServiceName(),
- nsd_service_info.GetServiceType());
- int port = nsd_service_info.GetPort();
- dns_service_instance_name_ =
- std::make_unique<std::wstring>(string_to_wstring(instance_name));
-
- dns_service_instance_.pszInstanceName =
- (LPWSTR)dns_service_instance_name_->c_str();
- dns_service_instance_.pszHostName = (LPWSTR)MDNS_HOST_NAME.data();
- dns_service_instance_.wPort = port;
-
- // Init DNS service register request
- dns_service_register_request_.Version = DNS_QUERY_REQUEST_VERSION1;
- dns_service_register_request_.InterfaceIndex =
- 0; // all interfaces will be considered
- dns_service_register_request_.unicastEnabled = false;
- dns_service_register_request_.hCredentials = NULL;
- dns_service_register_request_.pServiceInstance = &dns_service_instance_;
- dns_service_register_request_.pQueryContext = this; // callback use it
- dns_service_register_request_.pRegisterCompletionCallback =
- WifiLanMedium::Advertising_StopCompleted;
-
- dns_service_stop_latch_ = std::make_unique<CountDownLatch>(1);
- DWORD status = DnsServiceDeRegister(&dns_service_register_request_, nullptr);
-
- if (status != DNS_REQUEST_PENDING) {
- NEARBY_LOGS(ERROR) << "failed to stop mDNS advertising for service type ="
- << nsd_service_info.GetServiceType();
- return false;
- }
-
- // Wait for stop finish
- dns_service_stop_latch_.get()->Await();
- dns_service_stop_latch_ = nullptr;
- if (dns_service_stop_status_ != 0) {
- NEARBY_LOGS(INFO) << "failed to stop mDNS advertising for service type ="
- << nsd_service_info.GetServiceType();
- return false;
- }
-
- NEARBY_LOGS(INFO) << "succeeded to stop mDNS advertising for service type ="
- << nsd_service_info.GetServiceType();
- medium_status_ &= (~MEDIUM_STATUS_ADVERTISING);
- return true;
-}
-
-// Returns true once the WifiLan discovery has been initiated.
-bool WifiLanMedium::StartDiscovery(const std::string& service_type,
- DiscoveredServiceCallback callback) {
- if (IsDiscovering()) {
- NEARBY_LOGS(WARNING) << "discovery already running for service type ="
- << service_type;
- return false;
- }
-
- std::string selector =
- absl::StrFormat(MDNS_DEVICE_SELECTOR_FORMAT.data(), service_type);
-
- std::vector<winrt::hstring> requestedProperties{
- L"System.Devices.IpAddress",
- L"System.Devices.Dnssd.HostName",
- L"System.Devices.Dnssd.InstanceName",
- L"System.Devices.Dnssd.PortNumber",
- L"System.Devices.Dnssd.ServiceName",
- L"System.Devices.Dnssd.TextAttributes"};
-
- device_watcher_ = DeviceInformation::CreateWatcher(
- string_to_wstring(selector), requestedProperties,
- DeviceInformationKind::AssociationEndpointService);
-
- device_watcher_added_event_token =
- device_watcher_.Added({this, &WifiLanMedium::Watcher_DeviceAdded});
- device_watcher_updated_event_token =
- device_watcher_.Updated({this, &WifiLanMedium::Watcher_DeviceUpdated});
- device_watcher_removed_event_token =
- device_watcher_.Removed({this, &WifiLanMedium::Watcher_DeviceRemoved});
-
- device_watcher_.Start();
- discovered_service_callback_ = std::move(callback);
- medium_status_ |= MEDIUM_STATUS_DISCOVERING;
-
- NEARBY_LOGS(INFO) << "started to discovery.";
-
- return true;
-}
-
-// Returns true once WifiLan discovery for service_id is well and truly
-// stopped; after this returns, there must be no more invocations of the
-// DiscoveredServiceCallback passed in to StartDiscovery() for service_id.
-bool WifiLanMedium::StopDiscovery(const std::string& service_type) {
- if (!IsDiscovering()) {
- NEARBY_LOGS(WARNING) << "no discovering service to stop.";
- return false;
- }
- device_watcher_.Stop();
- device_watcher_.Added(device_watcher_added_event_token);
- device_watcher_.Updated(device_watcher_updated_event_token);
- device_watcher_.Removed(device_watcher_removed_event_token);
- medium_status_ &= (~MEDIUM_STATUS_DISCOVERING);
- device_watcher_ = nullptr;
- return true;
-}
-
-std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
- const NsdServiceInfo& remote_service_info,
- CancellationFlag* cancellation_flag) {
- NEARBY_LOGS(ERROR)
- << "connect to service by NSD service info. service type is "
- << remote_service_info.GetServiceType();
-
- return ConnectToService(remote_service_info.GetIPAddress(),
- remote_service_info.GetPort(), cancellation_flag);
-}
-
-std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
- const std::string& ip_address, int port,
- CancellationFlag* cancellation_flag) {
- if (ip_address.empty() || port == 0) {
- NEARBY_LOGS(ERROR) << "no valid service address and port to connect.";
- return nullptr;
- }
-
- HostName host_name{string_to_wstring(ip_address)};
- winrt::hstring service_name{winrt::to_hstring(port)};
-
- StreamSocket socket{};
-
- // setup cancel listener
- if (cancellation_flag != nullptr) {
- if (cancellation_flag->Cancelled()) {
- NEARBY_LOGS(INFO) << "connect has been cancelled to service "
- << ip_address << ":" << port;
- return nullptr;
- }
-
- location::nearby::CancellationFlagListener cancellationFlagListener(
- cancellation_flag, [socket]() { socket.CancelIOAsync().get(); });
- }
-
- // connection to the service
- try {
- socket.ConnectAsync(host_name, service_name).get();
- // connected need to keep connection
-
- std::unique_ptr<WifiLanSocket> wifi_lan_socket =
- std::make_unique<WifiLanSocket>(socket);
-
- NEARBY_LOGS(INFO) << "connected to remote service " << ip_address << ":"
- << port;
- return wifi_lan_socket;
- } catch (...) {
- NEARBY_LOGS(ERROR) << "failed to connect remote service " << ip_address
- << ":" << port;
- }
-
- return nullptr;
-}
-
-std::unique_ptr<api::WifiLanServerSocket> WifiLanMedium::ListenForService(
- int port) {
- absl::MutexLock lock(&mutex_);
-
- // check current status
- if (IsAccepting()) {
- NEARBY_LOGS(WARNING) << "accepting connections already started on port "
- << server_socket_ptr_->GetPort();
- return nullptr;
- }
-
- std::unique_ptr<WifiLanServerSocket> server_socket =
- std::make_unique<WifiLanServerSocket>(port);
- server_socket_ptr_ = server_socket.get();
-
- server_socket->SetCloseNotifier([this]() {
- absl::MutexLock lock(&mutex_);
- NEARBY_LOGS(INFO) << "server socket was closed on port "
- << server_socket_ptr_->GetPort();
- medium_status_ &= (~MEDIUM_STATUS_ACCEPTING);
- server_socket_ptr_ = nullptr;
- });
-
- if (server_socket->listen()) {
- medium_status_ |= MEDIUM_STATUS_ACCEPTING;
- NEARBY_LOGS(INFO) << "started to listen serive on port " << port;
- return server_socket;
- }
-
- NEARBY_LOGS(ERROR) << "Failed to listen service on port " << port;
-
- return nullptr;
-}
-
-NsdServiceInfo WifiLanMedium::GetNsdServiceInformation(
- IMapView<winrt::hstring, IInspectable> properties) {
- NsdServiceInfo nsd_service_info{};
-
- // Service name information
- IInspectable inspectable =
- properties.TryLookup(L"System.Devices.Dnssd.InstanceName");
- if (inspectable == nullptr) {
- NEARBY_LOGS(WARNING)
- << "no service name information in device information.";
- return nsd_service_info;
- }
- nsd_service_info.SetServiceName(InspectableReader::ReadString(inspectable));
-
- // IP Address information
- inspectable = properties.TryLookup(L"System.Devices.IPAddress");
- if (inspectable == nullptr) {
- NEARBY_LOGS(WARNING) << "no IP address information in device information.";
- return nsd_service_info;
- }
-
- auto ipaddresses = InspectableReader::ReadStringArray(inspectable);
- if (ipaddresses.size() == 0) {
- NEARBY_LOGS(WARNING) << "no IP address information in device information.";
- return nsd_service_info;
- }
-
- std::string ip_address = ipaddresses[0];
-
- // read IP port
- inspectable = properties.TryLookup(L"System.Devices.Dnssd.PortNumber");
- if (inspectable == nullptr) {
- NEARBY_LOGS(WARNING) << "no IP port information in device information.";
- return nsd_service_info;
- }
-
- int port = InspectableReader::ReadUint16(inspectable);
- nsd_service_info.SetIPAddress(ip_address);
- nsd_service_info.SetPort(port);
-
- // read text record
- inspectable = properties.TryLookup(L"System.Devices.Dnssd.TextAttributes");
- if (inspectable == nullptr) {
- NEARBY_LOGS(WARNING)
- << "no text attributes information in device information.";
- return nsd_service_info;
- }
-
- auto text_attributes = InspectableReader::ReadStringArray(inspectable);
- for (auto text_attribute : text_attributes) {
- // text attribute in format key=value
- int pos = text_attribute.find("=");
- if (pos <= 0 || pos == text_attribute.size() - 1) {
- NEARBY_LOGS(WARNING) << "found invalid text attribute " << text_attribute;
- continue;
- }
-
- std::string key = text_attribute.substr(0, pos);
- std::string value = text_attribute.substr(pos + 1);
- nsd_service_info.SetTxtRecord(key, value);
- }
-
- return nsd_service_info;
-}
-
-fire_and_forget WifiLanMedium::Watcher_DeviceAdded(
- DeviceWatcher sender, DeviceInformation deviceInfo) {
- // need to read IP address and port information from deviceInfo
- NsdServiceInfo nsd_service_info =
- GetNsdServiceInformation(deviceInfo.Properties());
-
- NEARBY_LOGS(INFO) << "device added for service name "
- << nsd_service_info.GetServiceName();
-
- std::string endpoint =
- nsd_service_info.GetTxtRecord(KEY_ENDPOINT_INFO.data());
- if (endpoint.empty()) {
- return fire_and_forget{};
- }
-
- discovered_service_callback_.service_discovered_cb(nsd_service_info);
-
- return fire_and_forget();
-}
-fire_and_forget WifiLanMedium::Watcher_DeviceUpdated(
- DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate) {
- // TODO(b/200421481): discovery servcie callback needs to support device
- // update.
- NsdServiceInfo nsd_service_info =
- GetNsdServiceInformation(deviceInfoUpdate.Properties());
- NEARBY_LOGS(INFO) << "device updated for service name "
- << nsd_service_info.GetServiceName();
-
- return fire_and_forget();
-}
-fire_and_forget WifiLanMedium::Watcher_DeviceRemoved(
- DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate) {
- // need to read IP address and port information from deviceInfo
- NsdServiceInfo nsd_service_info =
- GetNsdServiceInformation(deviceInfoUpdate.Properties());
-
- NEARBY_LOGS(INFO) << "device removed for service name "
- << nsd_service_info.GetServiceName();
-
- std::string endpoint =
- nsd_service_info.GetTxtRecord(KEY_ENDPOINT_INFO.data());
- if (endpoint.empty()) {
- return fire_and_forget{};
- }
-
- discovered_service_callback_.service_lost_cb(nsd_service_info);
-
- return fire_and_forget();
-}
-
-std::string WifiLanMedium::GetErrorMessage(std::exception_ptr eptr) {
- try {
- if (eptr) {
- std::rethrow_exception(eptr);
- } else {
- return "";
- }
- } catch (const std::exception& e) {
- return e.what();
- }
-}
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/wifi_lan_server_socket.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/wifi_lan_server_socket.cc
deleted file mode 100644
index 5d181329246..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/wifi_lan_server_socket.cc
+++ /dev/null
@@ -1,180 +0,0 @@
-// Copyright 2021 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/windows/utils.h"
-#include "platform/impl/windows/wifi_lan.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-WifiLanServerSocket::WifiLanServerSocket(int port) : port_(port) {}
-
-WifiLanServerSocket::~WifiLanServerSocket() { Close(); }
-
-// Returns ip address.
-std::string WifiLanServerSocket::GetIPAddress() const {
- if (stream_socket_listener_ == nullptr) {
- return {};
- }
-
- auto host_names = NetworkInformation::GetHostNames();
- for (auto host_name : host_names) {
- if (host_name.IPInformation() != nullptr &&
- host_name.IPInformation().NetworkAdapter() != nullptr) {
- return wstring_to_string(host_name.ToString().c_str());
- }
- }
-
- return {};
-}
-
-// Returns port.
-int WifiLanServerSocket::GetPort() const {
- if (stream_socket_listener_ == nullptr) {
- return 0;
- }
-
- return std::stoi(stream_socket_listener_.Information().LocalPort().c_str());
-}
-
-// Blocks until either:
-// - at least one incoming connection request is available, or
-// - ServerSocket is closed.
-// On success, returns connected socket, ready to exchange data.
-// Returns nullptr on error.
-// Once error is reported, it is permanent, and ServerSocket has to be closed.
-std::unique_ptr<api::WifiLanSocket> WifiLanServerSocket::Accept() {
- absl::MutexLock lock(&mutex_);
- while (!closed_ && pending_sockets_.empty()) {
- cond_.Wait(&mutex_);
- }
- if (closed_) return {};
-
- StreamSocket wifi_lan_socket = pending_sockets_.front();
- pending_sockets_.pop_front();
- return std::make_unique<WifiLanSocket>(wifi_lan_socket);
-}
-
-void WifiLanServerSocket::SetCloseNotifier(std::function<void()> notifier) {
- close_notifier_ = std::move(notifier);
-}
-
-// Returns Exception::kIo on error, Exception::kSuccess otherwise.
-Exception WifiLanServerSocket::Close() {
- try {
- absl::MutexLock lock(&mutex_);
- if (closed_) {
- return {Exception::kSuccess};
- }
- if (stream_socket_listener_ != nullptr) {
- stream_socket_listener_.ConnectionReceived(listener_event_token_);
- stream_socket_listener_.Close();
- stream_socket_listener_ = nullptr;
-
- if (!pending_sockets_.empty()) {
- auto it = pending_sockets_.begin();
- while (it != pending_sockets_.end()) {
- it->Close();
- }
- }
-
- cond_.SignalAll();
- }
- closed_ = true;
- if (close_notifier_ != nullptr) {
- close_notifier_();
- }
- return {Exception::kSuccess};
- } catch (...) {
- return {Exception::kIo};
- }
-}
-
-bool WifiLanServerSocket::listen() {
- // Check IP address
- ip_addresses_ = GetIpAddresses();
-
- if (ip_addresses_.empty()) {
- NEARBY_LOGS(WARNING) << "failed to start accepting connection without IP "
- "addresses configured on computer.";
- return false;
- }
-
- // Save connection callback
- stream_socket_listener_ = StreamSocketListener();
-
- // Setup callback
- listener_event_token_ = stream_socket_listener_.ConnectionReceived(
- {this, &WifiLanServerSocket::Listener_ConnectionReceived});
-
- try {
- stream_socket_listener_.BindServiceNameAsync(winrt::to_hstring(port_))
- .get();
- if (port_ == 0) {
- port_ =
- std::stoi(stream_socket_listener_.Information().LocalPort().c_str());
- }
-
- return true;
- } catch (...) {
- // Cannot bind to the preferred port, will let system to assign port.
- NEARBY_LOGS(WARNING) << "cannot accept connection on preferred port.";
- }
-
- try {
- stream_socket_listener_.BindServiceNameAsync({}).get();
- // need to save the port information
- port_ =
- std::stoi(stream_socket_listener_.Information().LocalPort().c_str());
- return true;
- } catch (...) {
- // Cannot bind to the preferred port, will let system to assign port.
- NEARBY_LOGS(ERROR) << "cannot bind to any port.";
- }
-
- return false;
-}
-
-fire_and_forget WifiLanServerSocket::Listener_ConnectionReceived(
- StreamSocketListener listener,
- StreamSocketListenerConnectionReceivedEventArgs const& args) {
- absl::MutexLock lock(&mutex_);
-
- if (closed_) {
- return fire_and_forget{};
- }
-
- pending_sockets_.push_back(args.Socket());
- cond_.SignalAll();
- return fire_and_forget{};
-}
-
-// Retrieves IP addresses from local machine
-std::vector<std::string> WifiLanServerSocket::GetIpAddresses() {
- std::vector<std::string> result{};
- auto host_names = NetworkInformation::GetHostNames();
- for (auto host_name : host_names) {
- if (host_name.IPInformation() != nullptr &&
- host_name.IPInformation().NetworkAdapter() != nullptr) {
- result.push_back(wstring_to_string(host_name.ToString().c_str()));
- }
- }
- return result;
-}
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/wifi_lan_socket.cc b/chromium/third_party/nearby/src/cpp/platform/impl/windows/wifi_lan_socket.cc
deleted file mode 100644
index 0b8358de5b1..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/wifi_lan_socket.cc
+++ /dev/null
@@ -1,142 +0,0 @@
-// Copyright 2021 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/impl/windows/wifi_lan.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace windows {
-
-WifiLanSocket::WifiLanSocket(StreamSocket socket) {
- stream_soket_ = socket;
- input_stream_ = SocketInputStream(socket.InputStream());
- output_stream_ = SocketOutputStream(socket.OutputStream());
-}
-
-WifiLanSocket::~WifiLanSocket() {
- if (stream_soket_ != nullptr) {
- try {
- Close();
- } catch (...) {
- NEARBY_LOGS(ERROR) << "Failed to destructor class WifiLanSocket.";
- }
- }
-}
-
-InputStream& WifiLanSocket::GetInputStream() { return input_stream_; }
-
-OutputStream& WifiLanSocket::GetOutputStream() { return output_stream_; }
-
-Exception WifiLanSocket::Close() {
- try {
- if (stream_soket_ != nullptr) {
- stream_soket_.Close();
- }
- return {Exception::kSuccess};
- } catch (...) {
- return {Exception::kIo};
- }
-}
-
-// SocketInputStream
-WifiLanSocket::SocketInputStream::SocketInputStream(IInputStream input_stream) {
- input_stream_ = input_stream;
-}
-
-ExceptionOr<ByteArray> WifiLanSocket::SocketInputStream::Read(
- std::int64_t size) {
- try {
- Buffer buffer = Buffer(size);
-
- auto ibuffer =
- input_stream_.ReadAsync(buffer, size, InputStreamOptions::None).get();
-
- if (ibuffer.Length() != size) {
- NEARBY_LOGS(WARNING) << "Only got part of data of needed.";
- }
-
- ByteArray data((char*)ibuffer.data(), ibuffer.Length());
-
- return ExceptionOr(data);
- } catch (...) {
- return Exception{Exception::kIo};
- }
-}
-
-ExceptionOr<size_t> WifiLanSocket::SocketInputStream::Skip(size_t offset) {
- try {
- Buffer buffer = Buffer(offset);
-
- auto ibuffer =
- input_stream_.ReadAsync(buffer, offset, InputStreamOptions::None).get();
- return ExceptionOr((size_t)ibuffer.Length());
- } catch (...) {
- return Exception{Exception::kIo};
- }
-}
-
-Exception WifiLanSocket::SocketInputStream::Close() {
- try {
- input_stream_.Close();
- } catch (...) {
- return {Exception::kIo};
- }
-
- return {Exception::kSuccess};
-}
-
-// SocketOutputStream
-WifiLanSocket::SocketOutputStream::SocketOutputStream(
- IOutputStream output_stream) {
- output_stream_ = output_stream;
-}
-
-Exception WifiLanSocket::SocketOutputStream::Write(const ByteArray& data) {
- Buffer buffer = Buffer(data.size());
- std::memcpy(buffer.data(), data.data(), data.size());
- buffer.Length(data.size());
-
- try {
- output_stream_.WriteAsync(buffer).get();
- } catch (...) {
- return {Exception::kIo};
- }
-
- return {Exception::kSuccess};
-}
-
-Exception WifiLanSocket::SocketOutputStream::Flush() {
- try {
- output_stream_.FlushAsync().get();
- } catch (...) {
- return {Exception::kIo};
- }
-
- return {Exception::kSuccess};
-}
-
-Exception WifiLanSocket::SocketOutputStream::Close() {
- try {
- output_stream_.Close();
- } catch (...) {
- return {Exception::kIo};
- }
-
- return {Exception::kSuccess};
-}
-
-} // namespace windows
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/BUILD b/chromium/third_party/nearby/src/cpp/platform/public/BUILD
deleted file mode 100644
index d1e122de05c..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/BUILD
+++ /dev/null
@@ -1,189 +0,0 @@
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# https://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-load("//tools/build_defs/cc:cc_fake_binary.bzl", "cc_fake_binary")
-
-licenses(["notice"])
-
-cc_library(
- name = "types",
- srcs = [
- "monitored_runnable.cc",
- "pending_job_registry.cc",
- "pipe.cc",
- ],
- hdrs = [
- "atomic_boolean.h",
- "atomic_reference.h",
- "cancelable.h",
- "cancelable_alarm.h",
- "cancellable_task.h",
- "condition_variable.h",
- "core_config.h",
- "count_down_latch.h",
- "crypto.h",
- "file.h",
- "future.h",
- "lockable.h",
- "logging.h",
- "monitored_runnable.h",
- "multi_thread_executor.h",
- "mutex.h",
- "mutex_lock.h",
- "pending_job_registry.h",
- "pipe.h",
- "scheduled_executor.h",
- "settable_future.h",
- "single_thread_executor.h",
- "submittable_executor.h",
- "system_clock.h",
- "thread_check_callable.h",
- "thread_check_runnable.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- visibility = [
- "//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
- "//analytics:__subpackages__",
- "//core:__subpackages__",
- "//platform/base:__pkg__",
- "//platform/impl/windows:__subpackages__",
- "//platform/public:__pkg__",
- ],
- deps = [
- ":logging",
- "//absl/base:core_headers",
- "//absl/time",
- "//platform/api:platform",
- "//platform/api:types",
- "//platform/base",
- "//platform/base:logging",
- "//platform/base:util",
- ],
-)
-
-cc_library(
- name = "comm",
- srcs = [
- "ble.cc",
- "bluetooth_classic.cc",
- "file.cc",
- "wifi_lan.cc",
- ],
- hdrs = [
- "ble.h",
- "bluetooth_adapter.h",
- "bluetooth_classic.h",
- "webrtc.h",
- "wifi_lan.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- copts = ["-DCORE_ADAPTER_DLL"],
- visibility = [
- "//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
- "//analytics:__subpackages__",
- "//core:__subpackages__",
- "//platform/public:__pkg__",
- ],
- deps = [
- ":logging",
- ":types",
- "//absl/container:flat_hash_map",
- "//absl/strings",
- "//platform/api:comm",
- "//platform/api:platform",
- "//platform/base",
- "//platform/base:cancellation_flag",
- "//proto/connections:offline_wire_formats_portable_proto",
- "//webrtc/api:libjingle_peerconnection_api",
- ],
-)
-
-cc_library(
- name = "logging",
- hdrs = [
- "logging.h",
- ],
- compatible_with = ["//buildenv/target:non_prod"],
- copts = ["-DCORE_ADAPTER_DLL"],
- visibility = [
- "//analytics:__subpackages__",
- "//core:__subpackages__",
- "//platform:__subpackages__",
- "//proto/analytics:__subpackages__",
- ],
- deps = [
- "//platform/base:logging",
- ],
-)
-
-cc_test(
- name = "public_test",
- size = "small",
- timeout = "moderate",
- srcs = [
- "atomic_boolean_test.cc",
- "atomic_reference_test.cc",
- "ble_test.cc",
- "bluetooth_adapter_test.cc",
- "bluetooth_classic_test.cc",
- "cancelable_alarm_test.cc",
- "condition_variable_test.cc",
- "count_down_latch_test.cc",
- "crypto_test.cc",
- "future_test.cc",
- "logging_test.cc",
- "multi_thread_executor_test.cc",
- "mutex_test.cc",
- "pipe_test.cc",
- "scheduled_executor_test.cc",
- "single_thread_executor_test.cc",
- "wifi_lan_test.cc",
- ],
- copts = ["-DCORE_ADAPTER_DLL"],
- shard_count = 16,
- deps = [
- ":comm",
- ":logging",
- ":types",
- "//testing/base/public:gunit_main",
- "//absl/strings",
- "//absl/synchronization",
- "//absl/time",
- "//platform/base",
- "//platform/base:test_util",
- "//platform/impl/g3", # build_cleaner: keep
- ],
-)
-
-cc_fake_binary(
- name = "thread_check_nocompile",
- srcs = ["thread_check_nocompile.cc"],
- deps = [
- ":types",
- "//absl/time",
- ],
-)
-
-py_test(
- name = "thread_check_nocompile_test",
- size = "large",
- srcs = ["thread_check_nocompile_test.py"],
- data = ["thread_check_nocompile"],
- python_version = "PY3",
- srcs_version = "PY3",
- tags = ["non_compile_test"],
- deps = [
- "//testing/pybase",
- "//testing/pybase:fake_target_util",
- ],
-)
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/atomic_boolean.h b/chromium/third_party/nearby/src/cpp/platform/public/atomic_boolean.h
deleted file mode 100644
index 7c727d5574f..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/atomic_boolean.h
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_ATOMIC_BOOLEAN_H_
-#define PLATFORM_PUBLIC_ATOMIC_BOOLEAN_H_
-
-#include <memory>
-
-#include "platform/api/atomic_boolean.h"
-#include "platform/api/platform.h"
-
-namespace location {
-namespace nearby {
-
-// A boolean value that may be updated atomically.
-// See documentation in
-// cpp/platform/api/atomic_boolean.h
-class AtomicBoolean final : public api::AtomicBoolean {
- public:
- using Platform = api::ImplementationPlatform;
- explicit AtomicBoolean(bool value = false)
- : impl_(Platform::CreateAtomicBoolean(value)) {}
- ~AtomicBoolean() override = default;
- AtomicBoolean(AtomicBoolean&&) = default;
- AtomicBoolean& operator=(AtomicBoolean&&) = default;
-
- bool Get() const override { return impl_->Get(); }
- bool Set(bool value) override { return impl_->Set(value); }
-
- explicit operator bool() const { return Get(); }
-
- private:
- std::unique_ptr<api::AtomicBoolean> impl_;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_ATOMIC_BOOLEAN_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/atomic_boolean_test.cc b/chromium/third_party/nearby/src/cpp/platform/public/atomic_boolean_test.cc
deleted file mode 100644
index 8dcb6ed9aa0..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/atomic_boolean_test.cc
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/public/atomic_boolean.h"
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-
-namespace location {
-namespace nearby {
-namespace {
-
-TEST(AtomicBooleanTest, SetReturnsPrevoiusValue) {
- AtomicBoolean value(false);
- EXPECT_FALSE(value.Set(true));
- EXPECT_TRUE(value.Set(true));
-}
-
-TEST(AtomicBooleanTest, GetReturnsWhatWasSet) {
- AtomicBoolean value(false);
- EXPECT_FALSE(value.Set(true));
- EXPECT_TRUE(value.Get());
-}
-
-TEST(AtomicBooleanTest, ImplicitGetTrueValue) {
- AtomicBoolean value(true);
-
- EXPECT_TRUE(value);
-}
-
-TEST(AtomicBooleanTest, ImplicitGetFalseValue) {
- AtomicBoolean value(false);
-
- EXPECT_FALSE(value);
-}
-} // namespace
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/atomic_reference.h b/chromium/third_party/nearby/src/cpp/platform/public/atomic_reference.h
deleted file mode 100644
index 8f8aaf38460..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/atomic_reference.h
+++ /dev/null
@@ -1,87 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_ATOMIC_REFERENCE_H_
-#define PLATFORM_PUBLIC_ATOMIC_REFERENCE_H_
-
-#include <memory>
-#include <type_traits>
-
-#include "platform/api/atomic_reference.h"
-#include "platform/api/platform.h"
-#include "platform/public/mutex.h"
-#include "platform/public/mutex_lock.h"
-
-namespace location {
-namespace nearby {
-
-// An object reference that may be updated atomically.
-template <typename, typename = void>
-class AtomicReference;
-
-// Platform-based atomic type, for something convertible to std::uint32_t.
-template <typename T>
-class AtomicReference<T, std::enable_if_t<sizeof(T) <= sizeof(std::uint32_t) &&
- std::is_trivially_copyable<T>::value>>
- final {
- public:
- using Platform = api::ImplementationPlatform;
- explicit AtomicReference(T value)
- : impl_(Platform::CreateAtomicUint32(static_cast<std::uint32_t>(value))) {
- }
- ~AtomicReference() = default;
- AtomicReference(AtomicReference&&) = default;
- AtomicReference& operator=(AtomicReference&&) = default;
-
- T Get() const { return static_cast<T>(impl_->Get()); }
- void Set(T value) { impl_->Set(static_cast<std::uint32_t>(value)); }
-
- private:
- std::unique_ptr<api::AtomicUint32> impl_;
-};
-
-// Atomic type that is using Platform mutex to provide atomicity.
-// Supports any copyable type.
-template <typename T>
-class AtomicReference<T,
- std::enable_if_t<(sizeof(T) > sizeof(std::uint32_t) ||
- !std::is_trivially_copyable<T>::value)>>
- final {
- public:
- explicit AtomicReference(T value) {
- MutexLock lock(&mutex_);
- value_ = std::move(value);
- }
- void Set(T value) {
- MutexLock lock(&mutex_);
- value_ = std::move(value);
- }
- T Get() const& {
- MutexLock lock(&mutex_);
- return value_;
- }
- T&& Get() const&& {
- MutexLock lock(&mutex_);
- return std::move(value_);
- }
-
- private:
- mutable Mutex mutex_;
- T value_;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_ATOMIC_REFERENCE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/atomic_reference_test.cc b/chromium/third_party/nearby/src/cpp/platform/public/atomic_reference_test.cc
deleted file mode 100644
index af888cadf1c..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/atomic_reference_test.cc
+++ /dev/null
@@ -1,89 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/public/atomic_reference.h"
-
-#include "gtest/gtest.h"
-
-namespace location {
-namespace nearby {
-namespace {
-
-struct BigSizedStruct {
- int data[100]{};
-};
-
-enum TestEnum {
- kValue1 = 1,
- kValue2 = 2,
-};
-
-enum class ScopedTestEnum {
- kValue1 = 1,
- kValue2 = 2,
-};
-
-bool operator==(const BigSizedStruct& a, const BigSizedStruct& b) {
- return memcmp(a.data, b.data, sizeof(BigSizedStruct::data)) == 0;
-}
-
-bool operator!=(const BigSizedStruct& a, const BigSizedStruct& b) {
- return !(a == b);
-}
-
-} // namespace
-
-TEST(AtomicReferenceTest, SupportIntegralTypes) {
- AtomicReference<int> atomic_ref({});
- atomic_ref.Set(5);
- EXPECT_EQ(atomic_ref.Get(), 5);
-}
-
-TEST(AtomicReferenceTest, SupportEnum) {
- AtomicReference<TestEnum> atomic_ref({});
- atomic_ref.Set(TestEnum::kValue1);
- EXPECT_EQ(atomic_ref.Get(), TestEnum::kValue1);
-}
-
-TEST(AtomicReferenceTest, SupportScopedEnum) {
- AtomicReference<ScopedTestEnum> atomic_ref({});
- atomic_ref.Set(ScopedTestEnum::kValue1);
- EXPECT_EQ(atomic_ref.Get(), ScopedTestEnum::kValue1);
-}
-
-TEST(AtomicReferenceTest, SetTakesCopyOfValue) {
- // Default constructor is zero-initalizing all data in BigSizedStruct.
- BigSizedStruct v1;
- AtomicReference<BigSizedStruct> atomic_ref({});
- v1.data[0] = 5; // Changing value before calling set() will affect stored
- v1.data[7] = 3; // value.
- atomic_ref.Set(v1);
- v1.data[1] = 6; // Changing value after calling set() will not affect stored
- v1.data[5] = 4; // value.
- BigSizedStruct v2 = atomic_ref.Get();
- EXPECT_NE(v1, v2);
- v1.data[1] = 0;
- v1.data[5] = 0;
- EXPECT_EQ(v2, v1);
-}
-
-TEST(AtomicReferenceTest, SupportObjects) {
- std::string s{"test"};
- AtomicReference<std::string> atomic_ref({});
- atomic_ref.Set(s);
- EXPECT_EQ(s, atomic_ref.Get());
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/ble.cc b/chromium/third_party/nearby/src/cpp/platform/public/ble.cc
deleted file mode 100644
index 9ce398ae647..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/ble.cc
+++ /dev/null
@@ -1,138 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/public/ble.h"
-
-#include "platform/public/logging.h"
-#include "platform/public/mutex_lock.h"
-
-namespace location {
-namespace nearby {
-
-bool BleMedium::StartAdvertising(
- const std::string& service_id, const ByteArray& advertisement_bytes,
- const std::string& fast_advertisement_service_uuid) {
- return impl_->StartAdvertising(service_id, advertisement_bytes,
- fast_advertisement_service_uuid);
-}
-
-bool BleMedium::StopAdvertising(const std::string& service_id) {
- return impl_->StopAdvertising(service_id);
-}
-
-bool BleMedium::StartScanning(
- const std::string& service_id,
- const std::string& fast_advertisement_service_uuid,
- DiscoveredPeripheralCallback callback) {
- {
- MutexLock lock(&mutex_);
- discovered_peripheral_callback_ = std::move(callback);
- peripherals_.clear();
- }
- return impl_->StartScanning(
- service_id, fast_advertisement_service_uuid,
- {
- .peripheral_discovered_cb =
- [this](api::BlePeripheral& peripheral,
- const std::string& service_id, bool fast_advertisement) {
- MutexLock lock(&mutex_);
- auto pair = peripherals_.emplace(
- &peripheral, absl::make_unique<ScanningInfo>());
- auto& context = *pair.first->second;
- if (pair.second) {
- context.peripheral = BlePeripheral(&peripheral);
- discovered_peripheral_callback_.peripheral_discovered_cb(
- context.peripheral, service_id,
- context.peripheral.GetAdvertisementBytes(service_id),
- fast_advertisement);
- }
- },
- .peripheral_lost_cb =
- [this](api::BlePeripheral& peripheral,
- const std::string& service_id) {
- MutexLock lock(&mutex_);
- if (peripherals_.empty()) return;
- auto context = peripherals_.find(&peripheral);
- if (context == peripherals_.end()) return;
- NEARBY_LOG(INFO, "Removing peripheral=%p, impl=%p",
- &(context->second->peripheral), &peripheral);
- discovered_peripheral_callback_.peripheral_lost_cb(
- context->second->peripheral, service_id);
- },
- });
-}
-
-bool BleMedium::StopScanning(const std::string& service_id) {
- {
- MutexLock lock(&mutex_);
- discovered_peripheral_callback_ = {};
- peripherals_.clear();
- NEARBY_LOG(INFO, "Ble Scanning disabled: impl=%p", &GetImpl());
- }
- return impl_->StopScanning(service_id);
-}
-
-bool BleMedium::StartAcceptingConnections(const std::string& service_id,
- AcceptedConnectionCallback callback) {
- {
- MutexLock lock(&mutex_);
- accepted_connection_callback_ = std::move(callback);
- }
- return impl_->StartAcceptingConnections(
- service_id,
- {
- .accepted_cb =
- [this](api::BleSocket& socket, const std::string& service_id) {
- MutexLock lock(&mutex_);
- auto pair = sockets_.emplace(
- &socket, absl::make_unique<AcceptedConnectionInfo>());
- auto& context = *pair.first->second;
- if (!pair.second) {
- NEARBY_LOG(INFO, "Accepting (again) socket=%p, impl=%p",
- &context.socket, &socket);
- } else {
- context.socket = BleSocket(&socket);
- NEARBY_LOG(INFO, "Accepting socket=%p, impl=%p",
- &context.socket, &socket);
- }
- accepted_connection_callback_.accepted_cb(context.socket,
- service_id);
- },
- });
-}
-
-bool BleMedium::StopAcceptingConnections(const std::string& service_id) {
- {
- MutexLock lock(&mutex_);
- accepted_connection_callback_ = {};
- sockets_.clear();
- NEARBY_LOG(INFO, "Ble accepted connection disabled: impl=%p", &GetImpl());
- }
- return impl_->StopAcceptingConnections(service_id);
-}
-
-BleSocket BleMedium::Connect(BlePeripheral& peripheral,
- const std::string& service_id,
- CancellationFlag* cancellation_flag) {
- {
- MutexLock lock(&mutex_);
- NEARBY_LOG(INFO, "BleMedium::Connect: peripheral=%p [impl=%p]", &peripheral,
- &peripheral.GetImpl());
- }
- return BleSocket(
- impl_->Connect(peripheral.GetImpl(), service_id, cancellation_flag));
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/ble.h b/chromium/third_party/nearby/src/cpp/platform/public/ble.h
deleted file mode 100644
index 49fa93f6a44..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/ble.h
+++ /dev/null
@@ -1,166 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_BLE_H_
-#define PLATFORM_PUBLIC_BLE_H_
-
-#include "absl/container/flat_hash_map.h"
-#include "platform/api/ble.h"
-#include "platform/api/platform.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/cancellation_flag.h"
-#include "platform/base/input_stream.h"
-#include "platform/base/output_stream.h"
-#include "platform/public/bluetooth_adapter.h"
-#include "platform/public/mutex.h"
-
-namespace location {
-namespace nearby {
-
-class BleSocket final {
- public:
- BleSocket() = default;
- BleSocket(const BleSocket&) = default;
- BleSocket& operator=(const BleSocket&) = default;
- explicit BleSocket(api::BleSocket* socket) : impl_(socket) {}
- explicit BleSocket(std::unique_ptr<api::BleSocket> socket)
- : impl_(socket.release()) {}
- ~BleSocket() = default;
-
- // Returns the InputStream of the BleSocket.
- // On error, returned stream will report Exception::kIo on any operation.
- //
- // The returned object is not owned by the caller, and can be invalidated once
- // the BleSocket object is destroyed.
- InputStream& GetInputStream() { return impl_->GetInputStream(); }
-
- // Returns the OutputStream of the BleSocket.
- // On error, returned stream will report Exception::kIo on any operation.
- //
- // The returned object is not owned by the caller, and can be invalidated once
- // the BleSocket object is destroyed.
- OutputStream& GetOutputStream() { return impl_->GetOutputStream(); }
-
- // Returns Exception::kIo on error, Exception::kSuccess otherwise.
- Exception Close() { return impl_->Close(); }
-
- BlePeripheral GetRemotePeripheral() {
- return BlePeripheral(impl_->GetRemotePeripheral());
- }
-
- // Returns true if a socket is usable. If this method returns false,
- // it is not safe to call any other method.
- // NOTE(socket validity):
- // Socket created by a default public constructor is not valid, because
- // it is missing platform implementation.
- // The only way to obtain a valid socket is through connection, such as
- // an object returned by BleMedium::Connect
- // These methods may also return an invalid socket if connection failed for
- // any reason.
- bool IsValid() const { return impl_ != nullptr; }
-
- // Returns reference to platform implementation.
- // This is used to communicate with platform code, and for debugging purposes.
- // Returned reference will remain valid for while BleSocket object is
- // itself valid. Typically BleSocket lifetime matches duration of the
- // connection, and is controlled by end user, since they hold the instance.
- api::BleSocket& GetImpl() { return *impl_; }
-
- private:
- std::shared_ptr<api::BleSocket> impl_;
-};
-
-// Container of operations that can be performed over the BLE medium.
-class BleMedium final {
- public:
- using Platform = api::ImplementationPlatform;
- struct DiscoveredPeripheralCallback {
- std::function<void(BlePeripheral& peripheral, const std::string& service_id,
- const ByteArray& advertisement_bytes,
- bool fast_advertisement)>
- peripheral_discovered_cb =
- DefaultCallback<BlePeripheral&, const std::string&,
- const ByteArray&, bool>();
- std::function<void(BlePeripheral& peripheral,
- const std::string& service_id)>
- peripheral_lost_cb =
- DefaultCallback<BlePeripheral&, const std::string&>();
- };
- struct ScanningInfo {
- BlePeripheral peripheral;
- };
-
- struct AcceptedConnectionCallback {
- std::function<void(BleSocket& socket, const std::string& service_id)>
- accepted_cb = DefaultCallback<BleSocket&, const std::string&>();
- };
- struct AcceptedConnectionInfo {
- BleSocket socket;
- };
-
- explicit BleMedium(BluetoothAdapter& adapter)
- : impl_(Platform::CreateBleMedium(adapter.GetImpl())),
- adapter_(adapter) {}
- ~BleMedium() = default;
-
- // Returns true once the BLE advertising has been initiated.
- bool StartAdvertising(const std::string& service_id,
- const ByteArray& advertisement_bytes,
- const std::string& fast_advertisement_service_uuid);
- bool StopAdvertising(const std::string& service_id);
-
- // Returns true once the BLE scan has been initiated.
- bool StartScanning(const std::string& service_id,
- const std::string& fast_advertisement_service_uuid,
- DiscoveredPeripheralCallback callback);
-
- // Returns true once BLE scanning for service_id is well and truly stopped;
- // after this returns, there must be no more invocations of the
- // DiscoveredPeripheralCallback passed in to StartScanning() for service_id.
- bool StopScanning(const std::string& service_id);
-
- // Returns true once BLE socket connection requests to service_id can be
- // accepted.
- bool StartAcceptingConnections(const std::string& service_id,
- AcceptedConnectionCallback callback);
- bool StopAcceptingConnections(const std::string& service_id);
-
- // Returns a new BleSocket. On Success, BleSocket::IsValid()
- // returns true.
- BleSocket Connect(BlePeripheral& peripheral, const std::string& service_id,
- CancellationFlag* cancellation_flag);
-
- bool IsValid() const { return impl_ != nullptr; }
-
- api::BleMedium& GetImpl() { return *impl_; }
- BluetoothAdapter& GetAdapter() { return adapter_; }
-
- private:
- Mutex mutex_;
- std::unique_ptr<api::BleMedium> impl_;
- BluetoothAdapter& adapter_;
- absl::flat_hash_map<api::BlePeripheral*, std::unique_ptr<ScanningInfo>>
- peripherals_ ABSL_GUARDED_BY(mutex_);
- absl::flat_hash_map<api::BleSocket*, std::unique_ptr<AcceptedConnectionInfo>>
- sockets_ ABSL_GUARDED_BY(mutex_);
- DiscoveredPeripheralCallback discovered_peripheral_callback_
- ABSL_GUARDED_BY(mutex_);
- AcceptedConnectionCallback accepted_connection_callback_
- ABSL_GUARDED_BY(mutex_);
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_BLE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/ble_test.cc b/chromium/third_party/nearby/src/cpp/platform/public/ble_test.cc
deleted file mode 100644
index 4c2173b4313..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/ble_test.cc
+++ /dev/null
@@ -1,305 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/public/ble.h"
-
-#include <memory>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "platform/base/medium_environment.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace {
-
-using FeatureFlags = FeatureFlags::Flags;
-
-constexpr FeatureFlags kTestCases[] = {
- FeatureFlags{
- .enable_cancellation_flag = true,
- },
- FeatureFlags{
- .enable_cancellation_flag = false,
- },
-};
-
-constexpr absl::Duration kWaitDuration = absl::Milliseconds(1000);
-constexpr absl::string_view kServiceID{"com.google.location.nearby.apps.test"};
-constexpr absl::string_view kAdvertisementString{"\x0a\x0b\x0c\x0d"};
-constexpr absl::string_view kFastAdvertisementServiceUuid{"\xf3\xfe"};
-
-class BleMediumTest : public ::testing::TestWithParam<FeatureFlags> {
- protected:
- using DiscoveredPeripheralCallback = BleMedium::DiscoveredPeripheralCallback;
- using AcceptedConnectionCallback = BleMedium::AcceptedConnectionCallback;
-
- BleMediumTest() { env_.Stop(); }
-
- MediumEnvironment& env_{MediumEnvironment::Instance()};
-};
-
-TEST_P(BleMediumTest, CanStartAcceptingConnectionsAndConnect) {
- FeatureFlags feature_flags = GetParam();
- env_.SetFeatureFlags(feature_flags);
- env_.Start();
- BluetoothAdapter adapter_a_;
- BluetoothAdapter adapter_b_;
- BleMedium ble_a{adapter_a_};
- BleMedium ble_b{adapter_b_};
- std::string service_id(kServiceID);
- ByteArray advertisement_bytes{std::string(kAdvertisementString)};
- std::string fast_advertisement_service_uuid(kFastAdvertisementServiceUuid);
- CountDownLatch found_latch(1);
- CountDownLatch accepted_latch(1);
- CancellationFlag flag;
-
- BlePeripheral* discovered_peripheral = nullptr;
- ble_a.StartScanning(
- service_id, fast_advertisement_service_uuid,
- DiscoveredPeripheralCallback{
- .peripheral_discovered_cb =
- [&found_latch, &discovered_peripheral](
- BlePeripheral& peripheral, const std::string& service_id,
- const ByteArray& advertisement_bytes,
- bool fast_advertisement) {
- NEARBY_LOG(
- INFO,
- "Peripheral discovered: %s, %p, fast advertisement: %d",
- peripheral.GetName().c_str(), &peripheral,
- fast_advertisement);
- discovered_peripheral = &peripheral;
- found_latch.CountDown();
- },
- });
- ble_b.StartAdvertising(service_id, advertisement_bytes,
- fast_advertisement_service_uuid);
- ble_b.StartAcceptingConnections(
- service_id,
- AcceptedConnectionCallback{
- .accepted_cb = [&accepted_latch](BleSocket socket,
- const std::string& service_id) {
- NEARBY_LOG(INFO, "Connection accepted: socket=%p, service_id=%s",
- &socket, service_id.c_str());
- accepted_latch.CountDown();
- }});
- EXPECT_TRUE(found_latch.Await(kWaitDuration).result());
-
- BleSocket socket_a;
- EXPECT_FALSE(socket_a.IsValid());
- {
- SingleThreadExecutor client_executor;
- client_executor.Execute(
- [&ble_a, &socket_a, discovered_peripheral, &service_id, &flag]() {
- socket_a = ble_a.Connect(*discovered_peripheral, service_id, &flag);
- });
- }
- EXPECT_TRUE(accepted_latch.Await(kWaitDuration).result());
- EXPECT_TRUE(socket_a.IsValid());
- ble_b.StopAdvertising(service_id);
- ble_a.StopScanning(service_id);
- env_.Stop();
-}
-
-TEST_P(BleMediumTest, CanCancelConnect) {
- FeatureFlags feature_flags = GetParam();
- env_.SetFeatureFlags(feature_flags);
- env_.Start();
- BluetoothAdapter adapter_a_;
- BluetoothAdapter adapter_b_;
- BleMedium ble_a{adapter_a_};
- BleMedium ble_b{adapter_b_};
- std::string service_id(kServiceID);
- ByteArray advertisement_bytes{std::string(kAdvertisementString)};
- std::string fast_advertisement_service_uuid(kFastAdvertisementServiceUuid);
- CountDownLatch found_latch(1);
- CountDownLatch accepted_latch(1);
- CancellationFlag flag(true);
-
- BlePeripheral* discovered_peripheral = nullptr;
- ble_a.StartScanning(
- service_id, fast_advertisement_service_uuid,
- DiscoveredPeripheralCallback{
- .peripheral_discovered_cb =
- [&found_latch, &discovered_peripheral](
- BlePeripheral& peripheral, const std::string& service_id,
- const ByteArray& advertisement_bytes,
- bool fast_advertisement) {
- NEARBY_LOG(
- INFO,
- "Peripheral discovered: %s, %p, fast advertisement: %d",
- peripheral.GetName().c_str(), &peripheral,
- fast_advertisement);
- discovered_peripheral = &peripheral;
- found_latch.CountDown();
- },
- });
- ble_b.StartAdvertising(service_id, advertisement_bytes,
- fast_advertisement_service_uuid);
- ble_b.StartAcceptingConnections(
- service_id,
- AcceptedConnectionCallback{
- .accepted_cb = [&accepted_latch](BleSocket socket,
- const std::string& service_id) {
- NEARBY_LOG(INFO, "Connection accepted: socket=%p, service_id=%s",
- &socket, service_id.c_str());
- accepted_latch.CountDown();
- }});
- EXPECT_TRUE(found_latch.Await(kWaitDuration).result());
-
- BleSocket socket_a;
- EXPECT_FALSE(socket_a.IsValid());
- {
- SingleThreadExecutor client_executor;
- client_executor.Execute(
- [&ble_a, &socket_a, discovered_peripheral, &service_id, &flag]() {
- socket_a = ble_a.Connect(*discovered_peripheral, service_id, &flag);
- });
- }
- // If FeatureFlag is disabled, Cancelled is false as no-op.
- if (!feature_flags.enable_cancellation_flag) {
- EXPECT_TRUE(accepted_latch.Await(kWaitDuration).result());
- EXPECT_TRUE(socket_a.IsValid());
- } else {
- EXPECT_FALSE(accepted_latch.Await(kWaitDuration).result());
- EXPECT_FALSE(socket_a.IsValid());
- }
- ble_b.StopAdvertising(service_id);
- ble_a.StopScanning(service_id);
- env_.Stop();
-}
-
-INSTANTIATE_TEST_SUITE_P(ParametrisedBleMediumTest, BleMediumTest,
- ::testing::ValuesIn(kTestCases));
-
-TEST_F(BleMediumTest, ConstructorDestructorWorks) {
- env_.Start();
- BluetoothAdapter adapter_a_;
- BluetoothAdapter adapter_b_;
- BleMedium ble_a{adapter_a_};
- BleMedium ble_b{adapter_b_};
-
- // Make sure we can create functional mediums.
- ASSERT_TRUE(ble_a.IsValid());
- ASSERT_TRUE(ble_b.IsValid());
-
- // Make sure we can create 2 distinct mediums.
- EXPECT_NE(&ble_a.GetImpl(), &ble_b.GetImpl());
- env_.Stop();
-}
-
-TEST_F(BleMediumTest, CanStartAdvertising) {
- env_.Start();
- BluetoothAdapter adapter_a_;
- BluetoothAdapter adapter_b_;
- BleMedium ble_a{adapter_a_};
- BleMedium ble_b{adapter_b_};
- std::string service_id(kServiceID);
- ByteArray advertisement_bytes{std::string(kAdvertisementString)};
- std::string fast_advertisement_service_uuid(kFastAdvertisementServiceUuid);
- CountDownLatch found_latch(1);
-
- ble_a.StartAdvertising(service_id, advertisement_bytes,
- fast_advertisement_service_uuid);
-
- EXPECT_TRUE(ble_b.StartScanning(
- service_id, fast_advertisement_service_uuid,
- DiscoveredPeripheralCallback{
- .peripheral_discovered_cb =
- [&found_latch](
- BlePeripheral& peripheral, const std::string& service_id,
- const ByteArray& advertisement_bytes,
- bool fast_advertisement) { found_latch.CountDown(); },
- }));
- EXPECT_TRUE(found_latch.Await(kWaitDuration).result());
- EXPECT_TRUE(ble_a.StopAdvertising(service_id));
- EXPECT_TRUE(ble_b.StopScanning(service_id));
- env_.Stop();
-}
-
-TEST_F(BleMediumTest, CanStartScanning) {
- env_.Start();
- BluetoothAdapter adapter_a_;
- BluetoothAdapter adapter_b_;
- BleMedium ble_a{adapter_a_};
- BleMedium ble_b{adapter_b_};
- std::string service_id(kServiceID);
- ByteArray advertisement_bytes{std::string(kAdvertisementString)};
- std::string fast_advertisement_service_uuid(kFastAdvertisementServiceUuid);
- CountDownLatch found_latch(1);
- CountDownLatch lost_latch(1);
-
- ble_a.StartScanning(
- service_id, fast_advertisement_service_uuid,
- DiscoveredPeripheralCallback{
- .peripheral_discovered_cb =
- [&found_latch](
- BlePeripheral& peripheral, const std::string& service_id,
- const ByteArray& advertisement_bytes,
- bool fast_advertisement) { found_latch.CountDown(); },
- .peripheral_lost_cb =
- [&lost_latch](BlePeripheral& peripheral,
- const std::string& service_id) {
- lost_latch.CountDown();
- },
- });
- EXPECT_TRUE(ble_b.StartAdvertising(service_id, advertisement_bytes,
- fast_advertisement_service_uuid));
- EXPECT_TRUE(found_latch.Await(kWaitDuration).result());
- EXPECT_TRUE(ble_b.StopAdvertising(service_id));
- EXPECT_TRUE(lost_latch.Await(kWaitDuration).result());
- EXPECT_TRUE(ble_a.StopScanning(service_id));
- env_.Stop();
-}
-
-TEST_F(BleMediumTest, CanStopDiscovery) {
- env_.Start();
- BluetoothAdapter adapter_a_;
- BluetoothAdapter adapter_b_;
- BleMedium ble_a{adapter_a_};
- BleMedium ble_b{adapter_b_};
- std::string service_id(kServiceID);
- ByteArray advertisement_bytes{std::string(kAdvertisementString)};
- std::string fast_advertisement_service_uuid(kFastAdvertisementServiceUuid);
- CountDownLatch found_latch(1);
- CountDownLatch lost_latch(1);
-
- ble_a.StartScanning(
- service_id, fast_advertisement_service_uuid,
- DiscoveredPeripheralCallback{
- .peripheral_discovered_cb =
- [&found_latch](
- BlePeripheral& peripheral, const std::string& service_id,
- const ByteArray& advertisement_bytes,
- bool fast_advertisement) { found_latch.CountDown(); },
- .peripheral_lost_cb =
- [&lost_latch](BlePeripheral& peripheral,
- const std::string& service_id) {
- lost_latch.CountDown();
- },
- });
- EXPECT_TRUE(ble_b.StartAdvertising(service_id, advertisement_bytes,
- fast_advertisement_service_uuid));
- EXPECT_TRUE(found_latch.Await(kWaitDuration).result());
- EXPECT_TRUE(ble_a.StopScanning(service_id));
- EXPECT_TRUE(ble_b.StopAdvertising(service_id));
- EXPECT_FALSE(lost_latch.Await(kWaitDuration).result());
- env_.Stop();
-}
-
-} // namespace
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/bluetooth_adapter.h b/chromium/third_party/nearby/src/cpp/platform/public/bluetooth_adapter.h
deleted file mode 100644
index 78179a2e5e7..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/bluetooth_adapter.h
+++ /dev/null
@@ -1,126 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_BLUETOOTH_ADAPTER_H_
-#define PLATFORM_PUBLIC_BLUETOOTH_ADAPTER_H_
-
-#include <string>
-
-#include "absl/strings/string_view.h"
-#include "platform/api/bluetooth_adapter.h"
-#include "platform/api/bluetooth_classic.h"
-#include "platform/api/platform.h"
-
-namespace location {
-namespace nearby {
-
-// Opaque wrapper over a BLE peripheral. Must contain enough data about a
-// particular BLE peripheral to connect to its GATT server.
-class BlePeripheral final {
- public:
- BlePeripheral() = default;
- BlePeripheral(const BlePeripheral&) = default;
- BlePeripheral& operator=(const BlePeripheral&) = default;
- explicit BlePeripheral(api::BlePeripheral* peripheral) : impl_(peripheral) {}
- ~BlePeripheral() = default;
-
- std::string GetName() const { return impl_->GetName(); }
-
- ByteArray GetAdvertisementBytes(const std::string& service_id) const {
- return impl_->GetAdvertisementBytes(service_id);
- }
-
- api::BlePeripheral& GetImpl() { return *impl_; }
- bool IsValid() const { return impl_ != nullptr; }
-
- private:
- api::BlePeripheral* impl_;
-};
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html.
-class BluetoothDevice final {
- public:
- BluetoothDevice() = default;
- BluetoothDevice(const BluetoothDevice&) = default;
- BluetoothDevice& operator=(const BluetoothDevice&) = default;
- explicit BluetoothDevice(api::BluetoothDevice* device) : impl_(device) {}
- ~BluetoothDevice() = default;
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#getName()
- std::string GetName() const { return impl_->GetName(); }
- std::string GetMacAddress() const { return impl_->GetMacAddress(); }
-
- api::BluetoothDevice& GetImpl() { return *impl_; }
- bool IsValid() const { return impl_ != nullptr; }
-
- private:
- api::BluetoothDevice* impl_;
-};
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html
-class BluetoothAdapter final {
- public:
- using Status = api::BluetoothAdapter::Status;
- using ScanMode = api::BluetoothAdapter::ScanMode;
-
- BluetoothAdapter()
- : impl_(api::ImplementationPlatform::CreateBluetoothAdapter()) {}
- ~BluetoothAdapter() = default;
- BluetoothAdapter(BluetoothAdapter&&) = default;
- BluetoothAdapter& operator=(BluetoothAdapter&&) = default;
-
- // Synchronously sets the status of the BluetoothAdapter to 'status', and
- // returns true if the operation was a success.
- bool SetStatus(Status status) { return impl_->SetStatus(status); }
- Status GetStatus() const {
- return IsEnabled() ? Status::kEnabled : Status::kDisabled;
- }
-
- // Returns true if the BluetoothAdapter's current status is
- // Status::Value::kEnabled.
- bool IsEnabled() const { return impl_->IsEnabled(); }
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getScanMode()
- //
- // Returns ScanMode::kUnknown on error.
- ScanMode GetScanMode() const { return impl_->GetScanMode(); }
-
- // Synchronously sets the scan mode of the adapter, and returns true if the
- // operation was a success.
- bool SetScanMode(ScanMode scan_mode) { return impl_->SetScanMode(scan_mode); }
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getName()
- // Returns an empty string on error
- std::string GetName() const { return impl_->GetName(); }
- std::string GetMacAddress() const { return impl_->GetMacAddress(); }
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#setName(java.lang.String)
- bool SetName(absl::string_view name) { return impl_->SetName(name); }
-
- bool IsValid() const { return impl_ != nullptr; }
-
- // Returns reference to platform implementation.
- // This is used to communicate with platform code, and for debugging purposes.
- // Returned reference will remain valid for while BluetoothAdapter object is
- // itself valid. It matches Core() object lifetime.
- api::BluetoothAdapter& GetImpl() { return *impl_; }
-
- private:
- std::unique_ptr<api::BluetoothAdapter> impl_;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_BLUETOOTH_ADAPTER_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/bluetooth_adapter_test.cc b/chromium/third_party/nearby/src/cpp/platform/public/bluetooth_adapter_test.cc
deleted file mode 100644
index 149064139b8..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/bluetooth_adapter_test.cc
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/public/bluetooth_adapter.h"
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "platform/base/bluetooth_utils.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace {
-
-TEST(BluetoothAdapterTest, ConstructorDestructorWorks) {
- BluetoothAdapter adapter;
- EXPECT_TRUE(adapter.IsValid());
-}
-
-TEST(BluetoothAdapterTest, CanSetName) {
- constexpr char kAdapterName[] = "MyBtAdapter";
- BluetoothAdapter adapter;
- EXPECT_EQ(adapter.GetStatus(), BluetoothAdapter::Status::kDisabled);
- EXPECT_TRUE(adapter.SetName(kAdapterName));
- EXPECT_EQ(adapter.GetName(), std::string(kAdapterName));
-}
-
-TEST(BluetoothAdapterTest, CanSetStatus) {
- BluetoothAdapter adapter;
- EXPECT_EQ(adapter.GetStatus(), BluetoothAdapter::Status::kDisabled);
- EXPECT_TRUE(adapter.SetStatus(BluetoothAdapter::Status::kEnabled));
- EXPECT_EQ(adapter.GetStatus(), BluetoothAdapter::Status::kEnabled);
-}
-
-TEST(BluetoothAdapterTest, CanSetMode) {
- BluetoothAdapter adapter;
- EXPECT_TRUE(adapter.SetScanMode(BluetoothAdapter::ScanMode::kConnectable));
- EXPECT_EQ(adapter.GetScanMode(), BluetoothAdapter::ScanMode::kConnectable);
- EXPECT_TRUE(adapter.SetScanMode(
- BluetoothAdapter::ScanMode::kConnectableDiscoverable));
- EXPECT_EQ(adapter.GetScanMode(),
- BluetoothAdapter::ScanMode::kConnectableDiscoverable);
- EXPECT_TRUE(adapter.SetScanMode(BluetoothAdapter::ScanMode::kNone));
- EXPECT_EQ(adapter.GetScanMode(), BluetoothAdapter::ScanMode::kNone);
-}
-
-TEST(BluetoothAdapterTest, CanGetMacAddress) {
- BluetoothAdapter adapter;
- std::string bt_mac =
- BluetoothUtils::ToString(ByteArray(adapter.GetMacAddress()));
- NEARBY_LOG(INFO, "BT MAC: '%s'", bt_mac.c_str());
- EXPECT_NE(bt_mac, "");
-}
-
-} // namespace
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/bluetooth_classic.cc b/chromium/third_party/nearby/src/cpp/platform/public/bluetooth_classic.cc
deleted file mode 100644
index 16cd9207768..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/bluetooth_classic.cc
+++ /dev/null
@@ -1,99 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/public/bluetooth_classic.h"
-
-#include "platform/public/logging.h"
-#include "platform/public/mutex_lock.h"
-
-namespace location {
-namespace nearby {
-
-BluetoothClassicMedium::~BluetoothClassicMedium() { StopDiscovery(); }
-
-BluetoothSocket BluetoothClassicMedium::ConnectToService(
- BluetoothDevice& remote_device, const std::string& service_uuid,
- CancellationFlag* cancellation_flag) {
- NEARBY_LOG(INFO,
- "BluetoothClassicMedium::ConnectToService: device=%p [impl=%p]",
- &remote_device, &remote_device.GetImpl());
- return BluetoothSocket(impl_->ConnectToService(
- remote_device.GetImpl(), service_uuid, cancellation_flag));
-}
-
-bool BluetoothClassicMedium::StartDiscovery(DiscoveryCallback callback) {
- MutexLock lock(&mutex_);
- if (discovery_enabled_) {
- NEARBY_LOG(INFO, "BT Discovery already enabled; impl=%p", &GetImpl());
- return false;
- }
- bool success = impl_->StartDiscovery({
- .device_discovered_cb =
- [this](api::BluetoothDevice& device) {
- MutexLock lock(&mutex_);
- auto pair = devices_.emplace(
- &device, absl::make_unique<DeviceDiscoveryInfo>());
- auto& context = *pair.first->second;
- if (!pair.second) {
- NEARBY_LOG(INFO, "Adding (again) device=%p, impl=%p",
- &context.device, &device);
- return;
- }
- context.device = BluetoothDevice(&device);
- NEARBY_LOG(INFO, "Adding device=%p, impl=%p", &context.device,
- &device);
- if (!discovery_enabled_) return;
- discovery_callback_.device_discovered_cb(context.device);
- },
- .device_name_changed_cb =
- [this](api::BluetoothDevice& device) {
- MutexLock lock(&mutex_);
- auto& context = *devices_[&device];
- NEARBY_LOG(INFO, "Renaming device=%p, impl=%p", &context.device,
- &device);
- if (!discovery_enabled_) return;
- discovery_callback_.device_name_changed_cb(context.device);
- },
- .device_lost_cb =
- [this](api::BluetoothDevice& device) {
- MutexLock lock(&mutex_);
- auto item = devices_.extract(&device);
- auto& context = *item.mapped();
- NEARBY_LOG(INFO, "Removing device=%p, impl=%p", &context.device,
- &device);
- if (!discovery_enabled_) return;
- discovery_callback_.device_lost_cb(context.device);
- },
- });
- if (success) {
- discovery_callback_ = std::move(callback);
- devices_.clear();
- discovery_enabled_ = true;
- NEARBY_LOG(INFO, "BT Discovery enabled; impl=%p", &GetImpl());
- }
- return success;
-}
-
-bool BluetoothClassicMedium::StopDiscovery() {
- MutexLock lock(&mutex_);
- if (!discovery_enabled_) return true;
- discovery_enabled_ = false;
- discovery_callback_ = {};
- devices_.clear();
- NEARBY_LOG(INFO, "BT Discovery disabled: impl=%p", &GetImpl());
- return impl_->StopDiscovery();
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/bluetooth_classic.h b/chromium/third_party/nearby/src/cpp/platform/public/bluetooth_classic.h
deleted file mode 100644
index 3728377125f..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/bluetooth_classic.h
+++ /dev/null
@@ -1,235 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_BLUETOOTH_CLASSIC_H_
-#define PLATFORM_PUBLIC_BLUETOOTH_CLASSIC_H_
-
-#include <memory>
-#include <string>
-
-#include "absl/container/flat_hash_map.h"
-#include "platform/api/bluetooth_classic.h"
-#include "platform/api/platform.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/cancellation_flag.h"
-#include "platform/base/exception.h"
-#include "platform/base/input_stream.h"
-#include "platform/base/listeners.h"
-#include "platform/base/output_stream.h"
-#include "platform/public/bluetooth_adapter.h"
-#include "platform/public/logging.h"
-#include "platform/public/mutex.h"
-
-namespace location {
-namespace nearby {
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html.
-class BluetoothSocket final {
- public:
- BluetoothSocket() = default;
- BluetoothSocket(const BluetoothSocket&) = default;
- BluetoothSocket& operator=(const BluetoothSocket&) = default;
- explicit BluetoothSocket(std::unique_ptr<api::BluetoothSocket> socket)
- : impl_(socket.release()) {}
- ~BluetoothSocket() = default;
-
- // Returns the InputStream of this connected BluetoothSocket.
- InputStream& GetInputStream() { return impl_->GetInputStream(); }
-
- // Returns the OutputStream of this connected BluetoothSocket.
- OutputStream& GetOutputStream() { return impl_->GetOutputStream(); }
-
- // Closes both input and output streams, marks Socket as closed.
- // After this call object should be treated as not connected.
- // Returns Exception::kIo on error, Exception::kSuccess otherwise.
- Exception Close() { return impl_->Close(); }
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#getRemoteDevice()
- BluetoothDevice GetRemoteDevice() {
- return BluetoothDevice(impl_->GetRemoteDevice());
- }
-
- // Returns true if a socket is usable. If this method returns false,
- // it is not safe to call any other method.
- // NOTE(socket validity):
- // Socket created by a default public constructor is not valid, because
- // it is missing platform implementation.
- // The only way to obtain a valid socket is through connection, such as
- // an object returned by either BluetoothClassicMedium::ConnectTotService or
- // BluetoothServerSocket::Accept().
- // These methods may also return an invalid socket if connection failed for
- // any reason.
- bool IsValid() const { return impl_ != nullptr; }
-
- // Returns reference to platform implementation.
- // This is used to communicate with platform code, and for debugging purposes.
- // Returned reference will remain valid for while BluetoothSocket object is
- // itself valid. Typically BluetoothSocket lifetime matches duration of the
- // connection, and is controlled by end user, since they hold the instance.
- api::BluetoothSocket& GetImpl() { return *impl_; }
-
- private:
- std::shared_ptr<api::BluetoothSocket> impl_;
-};
-
-// https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html.
-class BluetoothServerSocket final {
- public:
- BluetoothServerSocket() = default;
- BluetoothServerSocket(const BluetoothServerSocket&) = default;
- BluetoothServerSocket& operator=(const BluetoothServerSocket&) = default;
- ~BluetoothServerSocket() = default;
- explicit BluetoothServerSocket(
- std::unique_ptr<api::BluetoothServerSocket> socket)
- : impl_(std::move(socket)) {}
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html#accept()
- //
- // Blocks until either:
- // - at least one incoming connection request is available, or
- // - ServerSocket is closed.
- // On success, returns connected socket, ready to exchange data.
- // Returns nullptr on error.
- // Once error is reported, it is permanent, and ServerSocket has to be closed.
- BluetoothSocket Accept() {
- auto socket = impl_->Accept();
- if (!socket) {
- NEARBY_LOGS(INFO) << "Accept() failed on server socket: " << this;
- }
- return BluetoothSocket(std::move(socket));
- }
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html#close()
- //
- // Returns Exception::kIo on error, Exception::kSuccess otherwise.
- Exception Close() {
- NEARBY_LOGS(INFO) << "Closing server socket: " << this;
- return impl_->Close();
- }
-
- bool IsValid() const { return impl_ != nullptr; }
- api::BluetoothServerSocket& GetImpl() { return *impl_; }
-
- private:
- std::shared_ptr<api::BluetoothServerSocket> impl_;
-};
-
-// Container of operations that can be performed over the Bluetooth Classic
-// medium.
-class BluetoothClassicMedium final {
- public:
- using Platform = api::ImplementationPlatform;
- struct DiscoveryCallback {
- // BluetoothDevice is a proxy object created as a result of BT discovery.
- // Its lifetime spans between calls to device_discovered_cb and
- // device_lost_cb.
- // It is safe to use BluetoothDevice in device_discovered_cb() callback
- // and at any time afterwards, until device_lost_cb() is called.
- // It is not safe to use BluetoothDevice after returning from
- // device_lost_cb() callback.
- std::function<void(BluetoothDevice& device)> device_discovered_cb =
- DefaultCallback<BluetoothDevice&>();
- std::function<void(BluetoothDevice& device)> device_name_changed_cb =
- DefaultCallback<BluetoothDevice&>();
- std::function<void(BluetoothDevice& device)> device_lost_cb =
- DefaultCallback<BluetoothDevice&>();
- };
- struct DeviceDiscoveryInfo {
- BluetoothDevice device;
- };
-
- explicit BluetoothClassicMedium(BluetoothAdapter& adapter)
- : impl_(Platform::CreateBluetoothClassicMedium(adapter.GetImpl())),
- adapter_(adapter) {}
-
- ~BluetoothClassicMedium();
-
- // NOTE(DiscoveryCallback):
- // BluetoothDevice is a proxy object created as a result of BT discovery.
- // Its lifetime spans between calls to device_discovered_cb and
- // device_lost_cb.
- // It is safe to use BluetoothDevice in device_discovered_cb() callback
- // and at any time afterwards, until device_lost_cb() is called.
- // It is not safe to use BluetoothDevice after returning from
- // device_lost_cb() callback.
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#startDiscovery()
- //
- // Returns true once the process of discovery has been initiated.
- bool StartDiscovery(DiscoveryCallback callback);
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#cancelDiscovery()
- //
- // Returns true once discovery is well and truly stopped; after this returns,
- // there must be no more invocations of the DiscoveryCallback passed in to
- // StartDiscovery().
- bool StopDiscovery();
-
- // A combination of
- // https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#createInsecureRfcommSocketToServiceRecord
- // followed by
- // https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#connect().
- //
- // service_uuid is the canonical textual representation
- // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format) of a
- // type 3 name-based
- // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based))
- // UUID.
- //
- // Returns a new BluetoothSocket. On Success, BluetoothSocket::IsValid()
- // returns true.
- BluetoothSocket ConnectToService(BluetoothDevice& remote_device,
- const std::string& service_uuid,
- CancellationFlag* cancellation_flag);
-
- // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#listenUsingInsecureRfcommWithServiceRecord
- //
- // service_uuid is the canonical textual representation
- // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format) of a
- // type 3 name-based
- // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based))
- // UUID.
- //
- // Returns a new BluetoothServerSocket.
- // On Success, BluetoothServerSocket::IsValid() returns true.
- BluetoothServerSocket ListenForService(const std::string& service_name,
- const std::string& service_uuid) {
- return BluetoothServerSocket(
- impl_->ListenForService(service_name, service_uuid));
- }
-
- bool IsValid() const { return impl_ != nullptr; }
-
- api::BluetoothClassicMedium& GetImpl() { return *impl_; }
- BluetoothAdapter& GetAdapter() { return adapter_; }
- std::string GetMacAddress() const { return adapter_.GetMacAddress(); }
- BluetoothDevice GetRemoteDevice(const std::string& mac_address) {
- return BluetoothDevice(impl_->GetRemoteDevice(mac_address));
- }
-
- private:
- Mutex mutex_;
- std::unique_ptr<api::BluetoothClassicMedium> impl_;
- BluetoothAdapter& adapter_;
- absl::flat_hash_map<api::BluetoothDevice*,
- std::unique_ptr<DeviceDiscoveryInfo>>
- devices_ ABSL_GUARDED_BY(mutex_);
- DiscoveryCallback discovery_callback_ ABSL_GUARDED_BY(mutex_);
- bool discovery_enabled_ ABSL_GUARDED_BY(mutex_) = false;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_BLUETOOTH_CLASSIC_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/bluetooth_classic_test.cc b/chromium/third_party/nearby/src/cpp/platform/public/bluetooth_classic_test.cc
deleted file mode 100644
index ea219ca5e1a..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/bluetooth_classic_test.cc
+++ /dev/null
@@ -1,293 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/public/bluetooth_classic.h"
-
-#include <memory>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/time/time.h"
-#include "platform/base/medium_environment.h"
-#include "platform/public/bluetooth_adapter.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/logging.h"
-#include "platform/public/single_thread_executor.h"
-
-namespace location {
-namespace nearby {
-namespace {
-
-using FeatureFlags = FeatureFlags::Flags;
-
-constexpr FeatureFlags kTestCases[] = {
- FeatureFlags{
- .enable_cancellation_flag = true,
- },
- FeatureFlags{
- .enable_cancellation_flag = false,
- },
-};
-
-class BluetoothClassicMediumTest
- : public ::testing::TestWithParam<FeatureFlags> {
- protected:
- using DiscoveryCallback = BluetoothClassicMedium::DiscoveryCallback;
- BluetoothClassicMediumTest() {
- env_.Start();
- env_.Reset();
- adapter_a_ = std::make_unique<BluetoothAdapter>();
- adapter_b_ = std::make_unique<BluetoothAdapter>();
- bt_a_ = std::make_unique<BluetoothClassicMedium>(*adapter_a_);
- bt_b_ = std::make_unique<BluetoothClassicMedium>(*adapter_b_);
- adapter_a_->SetName("Device-A");
- adapter_b_->SetName("Device-B");
- adapter_a_->SetStatus(BluetoothAdapter::Status::kEnabled);
- adapter_b_->SetStatus(BluetoothAdapter::Status::kEnabled);
- env_.Sync();
- }
- ~BluetoothClassicMediumTest() override {
- env_.Sync(false);
- adapter_a_->SetStatus(BluetoothAdapter::Status::kDisabled);
- adapter_b_->SetStatus(BluetoothAdapter::Status::kDisabled);
- bt_a_.reset();
- bt_b_.reset();
- env_.Sync(false);
- adapter_a_.reset();
- adapter_b_.reset();
- env_.Reset();
- env_.Stop();
- }
-
- MediumEnvironment& env_{MediumEnvironment::Instance()};
-
- std::unique_ptr<BluetoothAdapter> adapter_a_;
- std::unique_ptr<BluetoothAdapter> adapter_b_;
- std::unique_ptr<BluetoothClassicMedium> bt_a_;
- std::unique_ptr<BluetoothClassicMedium> bt_b_;
-};
-
-TEST_P(BluetoothClassicMediumTest, CanConnectToService) {
- FeatureFlags feature_flags = GetParam();
- env_.SetFeatureFlags(feature_flags);
-
- adapter_a_->SetScanMode(BluetoothAdapter::ScanMode::kConnectable);
- CountDownLatch found_latch(1);
- BluetoothDevice* discovered_device = nullptr;
- bt_a_->StartDiscovery(DiscoveryCallback{
- .device_discovered_cb =
- [this, &found_latch, &discovered_device](BluetoothDevice& device) {
- NEARBY_LOG(INFO, "Device discovered: %s", device.GetName().c_str());
- EXPECT_EQ(device.GetName(), adapter_b_->GetName());
- discovered_device = &device;
- found_latch.CountDown();
- },
- });
- adapter_b_->SetScanMode(BluetoothAdapter::ScanMode::kConnectableDiscoverable);
- EXPECT_EQ(adapter_b_->GetScanMode(),
- BluetoothAdapter::ScanMode::kConnectableDiscoverable);
- EXPECT_TRUE(found_latch.Await(absl::Milliseconds(1000)).result());
- std::string service_name{"service"};
- std::string service_uuid("service-uuid");
- BluetoothServerSocket server_socket =
- bt_b_->ListenForService(service_name, service_uuid);
- EXPECT_TRUE(server_socket.IsValid());
- BluetoothSocket socket_a;
- BluetoothSocket socket_b;
- EXPECT_FALSE(socket_a.IsValid());
- EXPECT_FALSE(socket_b.IsValid());
- {
- CancellationFlag flag;
- SingleThreadExecutor server_executor;
- SingleThreadExecutor client_executor;
- client_executor.Execute([this, &socket_a, discovered_device, &service_uuid,
- &server_socket, &flag]() {
- socket_a =
- bt_a_->ConnectToService(*discovered_device, service_uuid, &flag);
- if (!socket_a.IsValid()) server_socket.Close();
- });
- server_executor.Execute([&socket_b, &server_socket]() {
- socket_b = server_socket.Accept();
- if (!socket_b.IsValid()) server_socket.Close();
- });
- }
- EXPECT_TRUE(socket_a.IsValid());
- EXPECT_TRUE(socket_b.IsValid());
- server_socket.Close();
-}
-
-TEST_P(BluetoothClassicMediumTest, CanCancelConnect) {
- FeatureFlags feature_flags = GetParam();
- env_.SetFeatureFlags(feature_flags);
-
- adapter_a_->SetScanMode(BluetoothAdapter::ScanMode::kConnectable);
- CountDownLatch found_latch(1);
- BluetoothDevice* discovered_device = nullptr;
- bt_a_->StartDiscovery(DiscoveryCallback{
- .device_discovered_cb =
- [this, &found_latch, &discovered_device](BluetoothDevice& device) {
- NEARBY_LOG(INFO, "Device discovered: %s", device.GetName().c_str());
- EXPECT_EQ(device.GetName(), adapter_b_->GetName());
- discovered_device = &device;
- found_latch.CountDown();
- },
- });
- adapter_b_->SetScanMode(BluetoothAdapter::ScanMode::kConnectableDiscoverable);
- EXPECT_EQ(adapter_b_->GetScanMode(),
- BluetoothAdapter::ScanMode::kConnectableDiscoverable);
- EXPECT_TRUE(found_latch.Await(absl::Milliseconds(1000)).result());
- std::string service_name{"service"};
- std::string service_uuid("service-uuid");
- BluetoothServerSocket server_socket =
- bt_b_->ListenForService(service_name, service_uuid);
- EXPECT_TRUE(server_socket.IsValid());
- BluetoothSocket socket_a;
- BluetoothSocket socket_b;
- EXPECT_FALSE(socket_a.IsValid());
- EXPECT_FALSE(socket_b.IsValid());
- {
- CancellationFlag flag(true);
- SingleThreadExecutor server_executor;
- SingleThreadExecutor client_executor;
- client_executor.Execute([this, &socket_a, discovered_device, &service_uuid,
- &server_socket, &flag]() {
- socket_a =
- bt_a_->ConnectToService(*discovered_device, service_uuid, &flag);
- if (!socket_a.IsValid()) server_socket.Close();
- });
- server_executor.Execute([&socket_b, &server_socket]() {
- socket_b = server_socket.Accept();
- if (!socket_b.IsValid()) server_socket.Close();
- });
- }
- // If FeatureFlag is disabled, Cancelled is false as no-op.
- if (!feature_flags.enable_cancellation_flag) {
- EXPECT_TRUE(socket_a.IsValid());
- EXPECT_TRUE(socket_b.IsValid());
- } else {
- EXPECT_FALSE(socket_a.IsValid());
- EXPECT_FALSE(socket_b.IsValid());
- }
- server_socket.Close();
-}
-
-INSTANTIATE_TEST_SUITE_P(ParametrisedBluetoothClassicMediumTest,
- BluetoothClassicMediumTest,
- ::testing::ValuesIn(kTestCases));
-
-TEST_F(BluetoothClassicMediumTest, ConstructorDestructorWorks) {
- // Make sure we can create functional adapters.
- ASSERT_TRUE(adapter_a_->IsValid());
- ASSERT_TRUE(adapter_b_->IsValid());
-
- // Make sure we can create 2 distinct adapters.
- // NOTE: multiple adapters are supported on a test platform, but not
- // necessarily on every available HW platform.
- // Often, HW platform supports only one BT adapter.
- EXPECT_NE(&adapter_a_->GetImpl(), &adapter_b_->GetImpl());
-
- // Make sure we can create functional mediums.
- ASSERT_TRUE(bt_a_->IsValid());
- ASSERT_TRUE(bt_b_->IsValid());
-
- // Make sure we can create 2 distinct mediums.
- EXPECT_NE(&bt_a_->GetImpl(), &bt_b_->GetImpl());
-}
-
-TEST_F(BluetoothClassicMediumTest, CanStartDiscovery) {
- adapter_a_->SetScanMode(BluetoothAdapter::ScanMode::kConnectable);
- CountDownLatch found_latch(1);
- CountDownLatch lost_latch(1);
- bt_a_->StartDiscovery(DiscoveryCallback{
- .device_discovered_cb =
- [this, &found_latch](BluetoothDevice& device) {
- NEARBY_LOG(INFO, "Device discovered: %s", device.GetName().c_str());
- EXPECT_EQ(device.GetName(), adapter_b_->GetName());
- found_latch.CountDown();
- },
- .device_lost_cb =
- [this, &lost_latch](BluetoothDevice& device) {
- NEARBY_LOG(INFO, "Device lost: %s", device.GetName().c_str());
- EXPECT_EQ(device.GetName(), adapter_b_->GetName());
- lost_latch.CountDown();
- },
- });
- adapter_b_->SetScanMode(BluetoothAdapter::ScanMode::kConnectableDiscoverable);
- EXPECT_EQ(adapter_b_->GetScanMode(),
- BluetoothAdapter::ScanMode::kConnectableDiscoverable);
- EXPECT_TRUE(found_latch.Await(absl::Milliseconds(1000)).result());
- adapter_b_->SetStatus(BluetoothAdapter::Status::kDisabled);
- EXPECT_FALSE(adapter_b_->IsEnabled());
- EXPECT_TRUE(lost_latch.Await(absl::Milliseconds(1000)).result());
-}
-
-TEST_F(BluetoothClassicMediumTest, CanStopDiscovery) {
- adapter_a_->SetScanMode(BluetoothAdapter::ScanMode::kConnectable);
- CountDownLatch found_latch(1);
- CountDownLatch lost_latch(1);
- bt_a_->StartDiscovery(DiscoveryCallback{
- .device_discovered_cb =
- [this, &found_latch](BluetoothDevice& device) {
- NEARBY_LOG(INFO, "Device discovered: %s", device.GetName().c_str());
- EXPECT_EQ(device.GetName(), adapter_b_->GetName());
- found_latch.CountDown();
- },
- .device_lost_cb =
- [this, &lost_latch](BluetoothDevice& device) {
- NEARBY_LOG(INFO, "Device lost: %s", device.GetName().c_str());
- EXPECT_EQ(device.GetName(), adapter_b_->GetName());
- lost_latch.CountDown();
- },
- });
- adapter_b_->SetScanMode(BluetoothAdapter::ScanMode::kConnectableDiscoverable);
- EXPECT_EQ(adapter_b_->GetScanMode(),
- BluetoothAdapter::ScanMode::kConnectableDiscoverable);
- EXPECT_TRUE(found_latch.Await(absl::Milliseconds(1000)).result());
- bt_a_->StopDiscovery();
- adapter_b_->SetStatus(BluetoothAdapter::Status::kDisabled);
- EXPECT_FALSE(adapter_b_->IsEnabled());
- EXPECT_FALSE(lost_latch.Await(absl::Milliseconds(1000)).result());
-}
-
-TEST_F(BluetoothClassicMediumTest, CanListenForService) {
- adapter_a_->SetScanMode(BluetoothAdapter::ScanMode::kConnectable);
- CountDownLatch found_latch(1);
- bt_a_->StartDiscovery(DiscoveryCallback{
- .device_discovered_cb =
- [this, &found_latch](BluetoothDevice& device) {
- NEARBY_LOG(INFO, "Device discovered: %s", device.GetName().c_str());
- EXPECT_EQ(device.GetName(), adapter_b_->GetName());
- found_latch.CountDown();
- },
- });
- adapter_b_->SetScanMode(BluetoothAdapter::ScanMode::kConnectableDiscoverable);
- EXPECT_EQ(adapter_b_->GetScanMode(),
- BluetoothAdapter::ScanMode::kConnectableDiscoverable);
- EXPECT_TRUE(found_latch.Await(absl::Milliseconds(1000)).result());
- std::string service_name{"service"};
- std::string service_uuid("service-uuid");
- BluetoothServerSocket server_socket =
- bt_b_->ListenForService(service_name, service_uuid);
- EXPECT_TRUE(server_socket.IsValid());
- server_socket.Close();
-}
-
-TEST_F(BluetoothClassicMediumTest, FailIfDiscovering) {
- EXPECT_TRUE(bt_a_->StartDiscovery({}));
- EXPECT_FALSE(bt_a_->StartDiscovery({}));
-}
-
-} // namespace
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/cancelable.h b/chromium/third_party/nearby/src/cpp/platform/public/cancelable.h
deleted file mode 100644
index 89b957b1517..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/cancelable.h
+++ /dev/null
@@ -1,60 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_CANCELABLE_H_
-#define PLATFORM_PUBLIC_CANCELABLE_H_
-
-#include <memory>
-#include <utility>
-
-#include "platform/api/cancelable.h"
-#include "platform/public/cancellable_task.h"
-
-namespace location {
-namespace nearby {
-
-// An interface to provide a cancellation mechanism for objects that represent
-// long-running operations.
-class Cancelable final {
- public:
- Cancelable() = default;
- Cancelable(const Cancelable&) = default;
- Cancelable& operator=(const Cancelable& other) = default;
-
- ~Cancelable() = default;
-
- // This constructor is used internally only,
- // by other classes in "//platform/public/".
- explicit Cancelable(std::shared_ptr<CancellableTask> task,
- std::shared_ptr<api::Cancelable> impl)
- : task_{task}, impl_(std::move(impl)) {}
-
- bool Cancel() {
- if (!impl_) return false;
- bool result = impl_->Cancel();
- task_->CancelAndWaitIfStarted();
- return result;
- }
-
- bool IsValid() { return impl_ != nullptr; }
-
- private:
- std::shared_ptr<CancellableTask> task_;
- std::shared_ptr<api::Cancelable> impl_;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_CANCELABLE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/cancelable_alarm.h b/chromium/third_party/nearby/src/cpp/platform/public/cancelable_alarm.h
deleted file mode 100644
index 73e3cf30033..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/cancelable_alarm.h
+++ /dev/null
@@ -1,71 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_CANCELABLE_ALARM_H_
-#define PLATFORM_PUBLIC_CANCELABLE_ALARM_H_
-
-#include <cstdint>
-#include <functional>
-#include <memory>
-#include <string>
-
-#include "platform/public/cancelable.h"
-#include "platform/public/mutex.h"
-#include "platform/public/mutex_lock.h"
-#include "platform/public/scheduled_executor.h"
-
-namespace location {
-namespace nearby {
-
-/**
- * A cancelable alarm with a name. This is a simple wrapper around the logic
- * for posting a Runnable on a ScheduledExecutor and (possibly) later
- * canceling it.
- */
-class CancelableAlarm {
- public:
- CancelableAlarm() = default;
- CancelableAlarm(absl::string_view name, std::function<void()>&& runnable,
- absl::Duration delay, ScheduledExecutor* scheduled_executor)
- : name_(name),
- cancelable_(scheduled_executor->Schedule(std::move(runnable), delay)) {}
- ~CancelableAlarm() = default;
- CancelableAlarm(CancelableAlarm&& other) { *this = std::move(other); }
- CancelableAlarm& operator=(CancelableAlarm&& other) {
- MutexLock lock(&mutex_);
- {
- MutexLock other_lock(&other.mutex_);
- name_ = std::move(other.name_);
- cancelable_ = std::move(other.cancelable_);
- }
- return *this;
- }
-
- bool Cancel() {
- MutexLock lock(&mutex_);
- return cancelable_.Cancel();
- }
-
- bool IsValid() { return cancelable_.IsValid(); }
-
- private:
- Mutex mutex_;
- std::string name_;
- Cancelable cancelable_;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_CANCELABLE_ALARM_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/cancelable_alarm_test.cc b/chromium/third_party/nearby/src/cpp/platform/public/cancelable_alarm_test.cc
deleted file mode 100644
index 4aebe310bf8..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/cancelable_alarm_test.cc
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/public/cancelable_alarm.h"
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/time/time.h"
-#include "platform/public/atomic_boolean.h"
-#include "platform/public/scheduled_executor.h"
-
-namespace location {
-namespace nearby {
-namespace {
-
-TEST(CancelableAlarmTest, CanCreateDefault) { CancelableAlarm alarm; }
-
-TEST(CancelableAlarmTest, CancelDefaultFails) {
- CancelableAlarm alarm;
- EXPECT_FALSE(alarm.Cancel());
-}
-
-TEST(CancelableAlarmTest, CanCreateAndFireAlarm) {
- ScheduledExecutor alarm_executor;
- AtomicBoolean done{false};
- CancelableAlarm alarm(
- "test_alarm", [&done]() { done.Set(true); }, absl::Milliseconds(100),
- &alarm_executor);
- SystemClock::Sleep(absl::Milliseconds(1000));
- EXPECT_TRUE(done.Get());
-}
-
-TEST(CancelableAlarmTest, CanCreateAndCancelAlarm) {
- ScheduledExecutor alarm_executor;
- AtomicBoolean done{false};
- CancelableAlarm alarm(
- "test_alarm", [&done]() { done.Set(true); }, absl::Milliseconds(100),
- &alarm_executor);
- EXPECT_TRUE(alarm.Cancel());
- SystemClock::Sleep(absl::Milliseconds(1000));
- EXPECT_FALSE(done.Get());
-}
-
-TEST(CancelableAlarmTest, CancelExpiredAlarmFails) {
- ScheduledExecutor alarm_executor;
- AtomicBoolean done{false};
- CancelableAlarm alarm(
- "test_alarm", [&done]() { done.Set(true); }, absl::Milliseconds(100),
- &alarm_executor);
- SystemClock::Sleep(absl::Milliseconds(1000));
- EXPECT_TRUE(done.Get());
- EXPECT_FALSE(alarm.Cancel());
-}
-
-} // namespace
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/cancellable_task.h b/chromium/third_party/nearby/src/cpp/platform/public/cancellable_task.h
deleted file mode 100644
index dac4cee6338..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/cancellable_task.h
+++ /dev/null
@@ -1,70 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_CANCELLABLE_TASK_H_
-#define PLATFORM_PUBLIC_CANCELLABLE_TASK_H_
-
-#include <utility>
-
-#include "platform/base/feature_flags.h"
-#include "platform/base/runnable.h"
-#include "platform/public/atomic_boolean.h"
-#include "platform/public/future.h"
-
-namespace location {
-namespace nearby {
-
-/**
- * Runnable wrapper that allows one to wait for the task
- * to complete if it is already running.
- */
-class CancellableTask {
- public:
- explicit CancellableTask(Runnable&& runnable)
- : runnable_{std::move(runnable)} {}
-
- /**
- * Try to cancel the task and wait until completion if the task is already
- * running.
- */
- void CancelAndWaitIfStarted() {
- if (started_or_cancelled_.Set(true)) {
- if (FeatureFlags::GetInstance()
- .GetFlags()
- .cancel_waits_for_running_tasks) {
- // task could still be running, wait until finish
- finished_.Get();
- }
- } else {
- // mark as finished to support multiple calls to this method
- finished_.Set(true);
- }
- }
-
- void operator()() {
- if (started_or_cancelled_.Set(true)) return;
- runnable_();
- finished_.Set(true);
- }
-
- private:
- AtomicBoolean started_or_cancelled_;
- Future<bool> finished_;
- Runnable runnable_;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_CANCELLABLE_TASK_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/condition_variable.h b/chromium/third_party/nearby/src/cpp/platform/public/condition_variable.h
deleted file mode 100644
index e6c0408ff6f..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/condition_variable.h
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_CONDITION_VARIABLE_H_
-#define PLATFORM_PUBLIC_CONDITION_VARIABLE_H_
-
-#include "platform/api/condition_variable.h"
-#include "platform/api/platform.h"
-#include "platform/base/exception.h"
-#include "platform/public/mutex.h"
-
-namespace location {
-namespace nearby {
-
-// The ConditionVariable class is a synchronization primitive that can be used
-// to block a thread, or multiple threads at the same time, until another thread
-// both modifies a shared variable (the condition), and notifies the
-// ConditionVariable.
-class ConditionVariable final {
- public:
- using Platform = api::ImplementationPlatform;
- explicit ConditionVariable(Mutex* mutex)
- : impl_(Platform::CreateConditionVariable(mutex->impl_.get())) {}
- ConditionVariable(ConditionVariable&&) = default;
- ConditionVariable& operator=(ConditionVariable&&) = default;
-
- void Notify() { impl_->Notify(); }
- Exception Wait() { return impl_->Wait(); }
- Exception Wait(absl::Duration timeout) { return impl_->Wait(timeout); }
-
- private:
- std::unique_ptr<api::ConditionVariable> impl_;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_CONDITION_VARIABLE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/condition_variable_test.cc b/chromium/third_party/nearby/src/cpp/platform/public/condition_variable_test.cc
deleted file mode 100644
index 1c0f5c16083..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/condition_variable_test.cc
+++ /dev/null
@@ -1,82 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/public/condition_variable.h"
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/time/time.h"
-#include "platform/public/logging.h"
-#include "platform/public/mutex.h"
-#include "platform/public/single_thread_executor.h"
-#include "platform/public/system_clock.h"
-
-namespace location {
-namespace nearby {
-namespace {
-
-TEST(ConditionVariableTest, CanCreate) {
- Mutex mutex;
- ConditionVariable cond{&mutex};
-}
-
-TEST(ConditionVariableTest, CanWakeupWaiter) {
- Mutex mutex;
- ConditionVariable cond{&mutex};
- bool done = false;
- bool waiting = false;
- NEARBY_LOG(INFO, "At start; done=%d", done);
- {
- SingleThreadExecutor executor;
- executor.Execute([&cond, &mutex, &done, &waiting]() {
- MutexLock lock(&mutex);
- NEARBY_LOG(INFO, "Before cond.Wait(); done=%d", done);
- waiting = true;
- cond.Wait();
- waiting = false;
- done = true;
- NEARBY_LOG(INFO, "After cond.Wait(); done=%d", done);
- });
- while (true) {
- {
- MutexLock lock(&mutex);
- if (waiting) break;
- }
- SystemClock::Sleep(absl::Milliseconds(100));
- }
- {
- MutexLock lock(&mutex);
- cond.Notify();
- EXPECT_FALSE(done);
- }
- }
- NEARBY_LOG(INFO, "After executor shutdown: done=%d", done);
- EXPECT_TRUE(done);
-}
-
-TEST(ConditionVariableTest, WaitTerminatesOnTimeoutWithoutNotify) {
- Mutex mutex;
- ConditionVariable cond{&mutex};
- MutexLock lock(&mutex);
-
- const absl::Duration kWaitTime = absl::Milliseconds(100);
- absl::Time start = SystemClock::ElapsedRealtime();
- cond.Wait(kWaitTime);
- absl::Duration duration = SystemClock::ElapsedRealtime() - start;
- EXPECT_GE(duration, kWaitTime);
-}
-
-} // namespace
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/count_down_latch.h b/chromium/third_party/nearby/src/cpp/platform/public/count_down_latch.h
deleted file mode 100644
index a86fd13e9d8..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/count_down_latch.h
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_COUNT_DOWN_LATCH_H_
-#define PLATFORM_PUBLIC_COUNT_DOWN_LATCH_H_
-
-#include <cstdint>
-
-#include "absl/time/time.h"
-#include "platform/api/count_down_latch.h"
-#include "platform/api/platform.h"
-#include "platform/base/exception.h"
-
-namespace location {
-namespace nearby {
-
-// A synchronization aid that allows one or more threads to wait until a set of
-// operations being performed in other threads completes.
-//
-// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html
-class CountDownLatch final {
- public:
- using Platform = api::ImplementationPlatform;
- explicit CountDownLatch(int count)
- : impl_(Platform::CreateCountDownLatch(count)) {}
- CountDownLatch(const CountDownLatch&) = default;
- CountDownLatch& operator=(const CountDownLatch&) = default;
- ~CountDownLatch() = default;
-
- Exception Await() { return impl_->Await(); }
- ExceptionOr<bool> Await(absl::Duration timeout) {
- return impl_->Await(timeout);
- }
- void CountDown() { impl_->CountDown(); }
-
- private:
- std::shared_ptr<api::CountDownLatch> impl_;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_COUNT_DOWN_LATCH_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/count_down_latch_test.cc b/chromium/third_party/nearby/src/cpp/platform/public/count_down_latch_test.cc
deleted file mode 100644
index c516dc0bedb..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/count_down_latch_test.cc
+++ /dev/null
@@ -1,70 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/public/count_down_latch.h"
-
-#include "gtest/gtest.h"
-#include "platform/public/single_thread_executor.h"
-
-namespace location {
-namespace nearby {
-namespace {
-
-TEST(CountDownLatch, ConstructorDestructorWorks) { CountDownLatch latch(1); }
-
-TEST(CountDownLatch, LatchAwaitCanWait) {
- CountDownLatch latch(1);
- SingleThreadExecutor executor;
- std::atomic_bool done = false;
- executor.Execute([&done, &latch]() {
- done = true;
- latch.CountDown();
- });
- latch.Await();
- EXPECT_TRUE(done);
-}
-
-TEST(CountDownLatch, LatchExtraCountDownIgnored) {
- CountDownLatch latch(1);
- SingleThreadExecutor executor;
- std::atomic_bool done = false;
- executor.Execute([&done, &latch]() {
- done = true;
- latch.CountDown();
- latch.CountDown();
- latch.CountDown();
- });
- latch.Await();
- EXPECT_TRUE(done);
-}
-
-TEST(CountDownLatch, LatchAwaitWithTimeoutCanExpire) {
- CountDownLatch latch(1);
- SingleThreadExecutor executor;
- auto response = latch.Await(absl::Milliseconds(100));
- EXPECT_TRUE(response.ok());
- EXPECT_FALSE(response.result());
-}
-
-TEST(CountDownLatch, InitialCountZero_AwaitDoesNotBlock) {
- CountDownLatch latch(0);
-
- auto response = latch.Await();
-
- EXPECT_TRUE(response.Ok());
-}
-
-} // namespace
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/crypto.h b/chromium/third_party/nearby/src/cpp/platform/public/crypto.h
deleted file mode 100644
index a41d44ef6d9..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/crypto.h
+++ /dev/null
@@ -1,20 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_CRYPTO_H_
-#define PLATFORM_PUBLIC_CRYPTO_H_
-
-#include "platform/api/crypto.h"
-
-#endif // PLATFORM_PUBLIC_CRYPTO_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/crypto_test.cc b/chromium/third_party/nearby/src/cpp/platform/public/crypto_test.cc
deleted file mode 100644
index 72a4fb039d9..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/crypto_test.cc
+++ /dev/null
@@ -1,48 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/public/crypto.h"
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "platform/base/byte_array.h"
-
-namespace location {
-namespace nearby {
-
-TEST(CryptoTest, Md5GeneratesHash) {
- const ByteArray expected_md5(
- "\xb4\x5c\xff\xe0\x84\xdd\x3d\x20\xd9\x28\xbe\xe8\x5e\x7b\x0f\x21");
- ByteArray md5_hash = Crypto::Md5("string");
- EXPECT_EQ(md5_hash, expected_md5);
-}
-
-TEST(CryptoTest, Md5ReturnsEmptyOnError) {
- EXPECT_EQ(Crypto::Md5(""), ByteArray{});
-}
-
-TEST(CryptoTest, Sha256GeneratesHash) {
- const ByteArray expected_sha256(
- "\x47\x32\x87\xf8\x29\x8d\xba\x71\x63\xa8\x97\x90\x89\x58\xf7\xc0"
- "\xea\xe7\x33\xe2\x5d\x2e\x02\x79\x92\xea\x2e\xdc\x9b\xed\x2f\xa8");
- ByteArray sha256_hash = Crypto::Sha256("string");
- EXPECT_EQ(sha256_hash, expected_sha256);
-}
-
-TEST(CryptoTest, Sha256ReturnsEmptyOnError) {
- EXPECT_EQ(Crypto::Sha256(""), ByteArray{});
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/file.cc b/chromium/third_party/nearby/src/cpp/platform/public/file.cc
deleted file mode 100644
index 4ea9bd991a6..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/file.cc
+++ /dev/null
@@ -1,92 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/public/file.h"
-
-namespace location {
-namespace nearby {
-
-InputFile::InputFile(PayloadId payload_id, std::int64_t size)
- : impl_(Platform::CreateInputFile(payload_id, size)), id_(payload_id) {}
-InputFile::~InputFile() = default;
-InputFile::InputFile(InputFile&&) noexcept = default;
-InputFile& InputFile::operator=(InputFile&&) noexcept = default;
-
-// Reads up to size bytes and returns as a ByteArray object wrapped by
-// ExceptionOr.
-// Returns Exception::kIo on error, or end of file.
-ExceptionOr<ByteArray> InputFile::Read(std::int64_t size) {
- return impl_->Read(size);
-}
-
-// Returns a string that uniqely identifies this file.
-std::string InputFile::GetFilePath() const { return impl_->GetFilePath(); }
-
-// Returns total size of this file in bytes.
-std::int64_t InputFile::GetTotalSize() const { return impl_->GetTotalSize(); }
-
-ExceptionOr<size_t> InputFile::Skip(size_t offset) {
- return impl_->Skip(offset);
-}
-
-// Disallows further reads from the file and frees system resources,
-// associated with it.
-Exception InputFile::Close() { return impl_->Close(); }
-
-// Returns a handle to the underlying input stream.
-//
-// Returned handle will remain valid even if InputFile is moved, for as long
-// as original InputFile lifetime continues.
-// Side effects of any non-const operation invoked for InputFile (such as
-// Read, or Close will be observable through InputStream& handle, and vice
-// versa.
-InputStream& InputFile::GetInputStream() { return *impl_; }
-
-// Returns payload id of this file. The closest "file" equivalent is inode.
-PayloadId InputFile::GetPayloadId() const { return id_; }
-
-OutputFile::OutputFile(PayloadId payload_id)
- : impl_(Platform::CreateOutputFile(payload_id)), id_(payload_id) {}
-OutputFile::~OutputFile() = default;
-OutputFile::OutputFile(OutputFile&&) noexcept = default;
-OutputFile& OutputFile::operator=(OutputFile&&) noexcept = default;
-
-// Writes all data from ByteArray object to the underlying stream.
-// Returns Exception::kIo on error, Exception::kSuccess otherwise.
-Exception OutputFile::Write(const ByteArray& data) {
- return impl_->Write(data);
-}
-
-// Ensures that all data written by previous calls to Write() is passed
-// down to the applicable transport layer.
-Exception OutputFile::Flush() { return impl_->Flush(); }
-
-// Disallows further writes to the file and frees system resources,
-// associated with it.
-Exception OutputFile::Close() { return impl_->Close(); }
-
-// Returns a handle to the underlying output stream.
-//
-// Returned handle will remain valid even if OutputFile is moved, for as long
-// as original OutputFile lifetime continues.
-// Side effects of any non-const operation invoked for OutputFile (such as
-// Write, or Close will be observable through OutputStream& handle, and vice
-// versa.
-OutputStream& OutputFile::GetOutputStream() { return *impl_; }
-
-// Returns payload id of this file. The closest "file" equivalent is inode.
-PayloadId OutputFile::GetPayloadId() const { return id_; }
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/file.h b/chromium/third_party/nearby/src/cpp/platform/public/file.h
deleted file mode 100644
index 80e1ce589e1..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/file.h
+++ /dev/null
@@ -1,116 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_FILE_H_
-#define PLATFORM_PUBLIC_FILE_H_
-
-#include <cstdint>
-#include <memory>
-#include <string>
-
-#include "platform/api/input_file.h"
-#include "platform/api/output_file.h"
-#include "platform/api/platform.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/exception.h"
-#include "platform/base/input_stream.h"
-#include "platform/base/output_stream.h"
-#include "platform/public/core_config.h"
-
-namespace location {
-namespace nearby {
-
-class DLL_API InputFile final {
- public:
- using Platform = api::ImplementationPlatform;
- InputFile(PayloadId payload_id, std::int64_t size);
- ~InputFile();
- InputFile(InputFile&&) noexcept;
- InputFile& operator=(InputFile&&) noexcept;
-
- // Reads up to size bytes and returns as a ByteArray object wrapped by
- // ExceptionOr.
- // Returns Exception::kIo on error, or end of file.
- ExceptionOr<ByteArray> Read(std::int64_t size);
-
- // Returns a string that uniqely identifies this file.
- std::string GetFilePath() const;
-
- // Returns total size of this file in bytes.
- std::int64_t GetTotalSize() const;
-
- ExceptionOr<size_t> Skip(size_t offset);
-
- // Disallows further reads from the file and frees system resources,
- // associated with it.
- Exception Close();
-
- // Returns a handle to the underlying input stream.
- //
- // Returned handle will remain valid even if InputFile is moved, for as long
- // as original InputFile lifetime continues.
- // Side effects of any non-const operation invoked for InputFile (such as
- // Read, or Close will be observable through InputStream& handle, and vice
- // versa.
- InputStream& GetInputStream();
-
- // Returns payload id of this file. The closest "file" equivalent is inode.
- PayloadId GetPayloadId() const;
-
- private:
- std::unique_ptr<api::InputFile> impl_;
- PayloadId id_;
-};
-
-class DLL_API OutputFile final {
- public:
- using Platform = api::ImplementationPlatform;
- explicit OutputFile(PayloadId payload_id);
- ~OutputFile();
- OutputFile(OutputFile&&) noexcept;
- OutputFile& operator=(OutputFile&&) noexcept;
-
- // Writes all data from ByteArray object to the underlying stream.
- // Returns Exception::kIo on error, Exception::kSuccess otherwise.
- Exception Write(const ByteArray& data);
-
- // Ensures that all data written by previous calls to Write() is passed
- // down to the applicable transport layer.
- Exception Flush();
-
- // Disallows further writes to the file and frees system resources,
- // associated with it.
- Exception Close();
-
- // Returns a handle to the underlying output stream.
- //
- // Returned handle will remain valid even if OutputFile is moved, for as long
- // as original OutputFile lifetime continues.
- // Side effects of any non-const operation invoked for OutputFile (such as
- // Write, or Close will be observable through OutputStream& handle, and vice
- // versa.
- OutputStream& GetOutputStream();
-
- // Returns payload id of this file. The closest "file" equivalent is inode.
- PayloadId GetPayloadId() const;
-
- private:
- std::unique_ptr<api::OutputFile> impl_;
- PayloadId id_;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_FILE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/future.h b/chromium/third_party/nearby/src/cpp/platform/public/future.h
deleted file mode 100644
index 78c950a6337..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/future.h
+++ /dev/null
@@ -1,56 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_FUTURE_H_
-#define PLATFORM_PUBLIC_FUTURE_H_
-
-#include "platform/public/settable_future.h"
-
-namespace location {
-namespace nearby {
-
-template <typename T>
-class Future final {
- public:
- virtual bool Set(T value) { return impl_->Set(std::move(value)); }
- virtual bool SetException(Exception exception) {
- return impl_->SetException(exception);
- }
- virtual ExceptionOr<T> Get() { return impl_->Get(); }
- virtual ExceptionOr<T> Get(absl::Duration timeout) {
- return impl_->Get(timeout);
- }
- void AddListener(Runnable runnable, api::Executor* executor) {
- impl_->AddListener(std::move(runnable), executor);
- }
- bool IsSet() const { return impl_->IsSet(); }
-
- private:
- // Instance of future implementation is wrapped in shared_ptr<> to make
- // it possible to pass Future by value and share the implementation.
- // This allows for the following constructions:
- // 1)
- // Future<bool> future;
- // RunOnXyzThread([future]() { future.Set(DoTheJobAndReport()); });
- // if (future.Get().Ok()) { /*...*/ }
- // 2)
- // Future<bool> future = DoSomeAsyncWork(); // Returns future, but keeps copy.
- // if (future.Get().Ok()) { /*...*/ }
- std::shared_ptr<SettableFuture<T>> impl_{new SettableFuture<T>()};
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_FUTURE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/future_test.cc b/chromium/third_party/nearby/src/cpp/platform/public/future_test.cc
deleted file mode 100644
index c996a3938f0..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/future_test.cc
+++ /dev/null
@@ -1,116 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/public/future.h"
-
-#include "gtest/gtest.h"
-#include "absl/time/clock.h"
-#include "absl/time/time.h"
-#include "platform/public/single_thread_executor.h"
-
-namespace location {
-namespace nearby {
-
-namespace {
-
-enum TestEnum {
- kValue1 = 1,
- kValue2 = 2,
-};
-
-enum class ScopedTestEnum {
- kValue1 = 1,
- kValue2 = 2,
-};
-
-struct BigSizedStruct {
- int data[100]{};
-};
-
-bool operator==(const BigSizedStruct& a, const BigSizedStruct& b) {
- return memcmp(a.data, b.data, sizeof(BigSizedStruct::data)) == 0;
-}
-
-bool operator!=(const BigSizedStruct& a, const BigSizedStruct& b) {
- return !(a == b);
-}
-
-} // namespace
-
-TEST(FutureTest, SupportIntegralTypes) {
- Future<int> future;
- future.Set(5);
- EXPECT_EQ(future.Get().exception(), Exception::kSuccess);
- EXPECT_EQ(future.Get().result(), 5);
-}
-
-TEST(FutureTest, SetExceptionIsPropagated) {
- Future<int> future;
- future.SetException({Exception::kIo});
- EXPECT_EQ(future.Get().exception(), Exception::kIo);
-}
-
-TEST(FutureTest, SupportEnum) {
- Future<TestEnum> future;
- future.Set(TestEnum::kValue1);
- EXPECT_EQ(future.Get().exception(), Exception::kSuccess);
- EXPECT_EQ(future.Get().result(), TestEnum::kValue1);
-}
-
-TEST(FutureTest, SupportScopedEnum) {
- Future<ScopedTestEnum> future;
- future.Set(ScopedTestEnum::kValue1);
- EXPECT_EQ(future.Get().exception(), Exception::kSuccess);
- EXPECT_EQ(future.Get().result(), ScopedTestEnum::kValue1);
-}
-
-TEST(FutureTest, SetTakesCopyOfValue) {
- // Default constructor is zero-initalizing all data in BigSizedStruct.
- BigSizedStruct v1;
- Future<BigSizedStruct> future;
- v1.data[0] = 5; // Changing value before calling Set() will affect stored
- v1.data[7] = 3; // value.
- future.Set(v1);
- v1.data[1] = 6; // Changing value after calling Set() will not affect stored
- v1.data[5] = 4; // value.
- EXPECT_EQ(future.Get().exception(), Exception::kSuccess);
- BigSizedStruct v2 = future.Get().result();
- EXPECT_NE(v1, v2);
- v1.data[1] = 0;
- v1.data[5] = 0;
- EXPECT_EQ(v2, v1);
-}
-
-TEST(FutureTest, SetsExceptionOnTimeout) {
- Future<int> future;
- EXPECT_EQ(future.Get(absl::Milliseconds(100)).exception(),
- Exception::kTimeout);
-}
-
-TEST(FutureTest, GetBlocksWhenNotReady) {
- Future<int> future;
- SingleThreadExecutor executor;
- absl::Time start = absl::Now();
- executor.Execute([&future]() {
- absl::SleepFor(absl::Milliseconds(500));
- future.Set(10);
- });
- auto response = future.Get();
- absl::Duration blocked_duration = absl::Now() - start;
- EXPECT_EQ(response.result(), 10);
- EXPECT_GE(blocked_duration, absl::Milliseconds(500));
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/logging.h b/chromium/third_party/nearby/src/cpp/platform/public/logging.h
deleted file mode 100644
index 7d68c1ef5fe..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/logging.h
+++ /dev/null
@@ -1,20 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_LOGGING_H_
-#define PLATFORM_PUBLIC_LOGGING_H_
-
-#include "platform/base/logging.h"
-
-#endif // PLATFORM_PUBLIC_LOGGING_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/logging_test.cc b/chromium/third_party/nearby/src/cpp/platform/public/logging_test.cc
deleted file mode 100644
index 73628af3029..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/logging_test.cc
+++ /dev/null
@@ -1,52 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/public/logging.h"
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-
-namespace {
-
-TEST(LoggingTest, CanLog) {
- NEARBY_LOG_SET_SEVERITY(INFO);
- int num = 42;
- NEARBY_LOG(INFO, "The answer to everything: %d", num++);
- EXPECT_EQ(num, 43);
-}
-
-TEST(LoggingTest, CanLog_LoggingDisabled) {
- NEARBY_LOG_SET_SEVERITY(ERROR);
- int num = 42;
- NEARBY_LOG(INFO, "The answer to everything: %d", num++);
- // num++ should not be evaluated
- EXPECT_EQ(num, 42);
-}
-
-TEST(LoggingTest, CanStream) {
- NEARBY_LOG_SET_SEVERITY(INFO);
- int num = 42;
- NEARBY_LOGS(INFO) << "The answer to everything: " << num++;
- EXPECT_EQ(num, 43);
-}
-
-TEST(LoggingTest, CanStream_LoggingDisabled) {
- NEARBY_LOG_SET_SEVERITY(ERROR);
- int num = 42;
- NEARBY_LOGS(INFO) << "The answer to everything: " << num++;
- // num++ should not be evaluated
- EXPECT_EQ(num, 42);
-}
-
-} // namespace
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/monitored_runnable.cc b/chromium/third_party/nearby/src/cpp/platform/public/monitored_runnable.cc
deleted file mode 100644
index 7478f70e8f6..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/monitored_runnable.cc
+++ /dev/null
@@ -1,59 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/public/monitored_runnable.h"
-
-#include "platform/public/logging.h"
-#include "platform/public/pending_job_registry.h"
-
-namespace location {
-namespace nearby {
-
-namespace {
-absl::Duration kMinReportedStartDelay = absl::Seconds(5);
-absl::Duration kMinReportedTaskDuration = absl::Seconds(10);
-} // namespace
-
-MonitoredRunnable::MonitoredRunnable(Runnable&& runnable)
- : runnable_{runnable} {}
-
-MonitoredRunnable::MonitoredRunnable(const std::string& name,
- Runnable&& runnable)
- : name_{name}, runnable_{runnable} {
- PendingJobRegistry::GetInstance().AddPendingJob(name_, post_time_);
-}
-
-MonitoredRunnable::~MonitoredRunnable() = default;
-
-void MonitoredRunnable::operator()() const {
- auto start_time = SystemClock::ElapsedRealtime();
- auto start_delay = start_time - post_time_;
- if (start_delay >= kMinReportedStartDelay) {
- NEARBY_LOGS(INFO) << "Task: \"" << name_ << "\" started after "
- << absl::ToInt64Seconds(start_delay) << " seconds";
- }
- PendingJobRegistry::GetInstance().RemovePendingJob(name_, post_time_);
- PendingJobRegistry::GetInstance().AddRunningJob(name_, post_time_);
- runnable_();
- auto task_duration = SystemClock::ElapsedRealtime() - start_time;
- if (task_duration >= kMinReportedTaskDuration) {
- NEARBY_LOGS(INFO) << "Task: \"" << name_ << "\" finished after "
- << absl::ToInt64Seconds(task_duration) << " seconds";
- }
- PendingJobRegistry::GetInstance().RemoveRunningJob(name_, post_time_);
- PendingJobRegistry::GetInstance().ListJobs();
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/monitored_runnable.h b/chromium/third_party/nearby/src/cpp/platform/public/monitored_runnable.h
deleted file mode 100644
index adc765f88bf..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/monitored_runnable.h
+++ /dev/null
@@ -1,48 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_MONITORED_RUNNABLE_H_
-#define PLATFORM_PUBLIC_MONITORED_RUNNABLE_H_
-
-#include <string>
-
-#include "absl/time/time.h"
-#include "platform/base/runnable.h"
-#include "platform/public/system_clock.h"
-
-namespace location {
-namespace nearby {
-
-// A runnable with extra logging
-// We log if the task has been waiting long on the executor or if it was running
-// for a long time. The latter isn't always an issue - some tasks are expected
-// to run for longer periods of time (minutes).
-class MonitoredRunnable {
- public:
- explicit MonitoredRunnable(Runnable&& runnable);
- MonitoredRunnable(const std::string& name, Runnable&& runnable);
- ~MonitoredRunnable();
-
- void operator()() const;
-
- private:
- const std::string name_;
- Runnable runnable_;
- absl::Time post_time_ = SystemClock::ElapsedRealtime();
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_MONITORED_RUNNABLE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/multi_thread_executor.h b/chromium/third_party/nearby/src/cpp/platform/public/multi_thread_executor.h
deleted file mode 100644
index 46aa837f1f5..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/multi_thread_executor.h
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_MULTI_THREAD_EXECUTOR_H_
-#define PLATFORM_PUBLIC_MULTI_THREAD_EXECUTOR_H_
-
-#include "absl/base/thread_annotations.h"
-#include "platform/api/platform.h"
-#include "platform/public/submittable_executor.h"
-
-namespace location {
-namespace nearby {
-
-// An Executor that reuses a fixed number of threads operating off a shared
-// unbounded queue.
-//
-// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool-int-
-class ABSL_LOCKABLE MultiThreadExecutor final : public SubmittableExecutor {
- public:
- using Platform = api::ImplementationPlatform;
- explicit MultiThreadExecutor(int max_parallelism)
- : SubmittableExecutor(
- Platform::CreateMultiThreadExecutor(max_parallelism)) {}
- MultiThreadExecutor(MultiThreadExecutor&&) = default;
- MultiThreadExecutor& operator=(MultiThreadExecutor&&) = default;
- ~MultiThreadExecutor() override = default;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_MULTI_THREAD_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/multi_thread_executor_test.cc b/chromium/third_party/nearby/src/cpp/platform/public/multi_thread_executor_test.cc
deleted file mode 100644
index fe1be8ff226..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/multi_thread_executor_test.cc
+++ /dev/null
@@ -1,138 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/public/multi_thread_executor.h"
-
-#include <atomic>
-#include <functional>
-
-#include "gtest/gtest.h"
-#include "absl/synchronization/mutex.h"
-#include "absl/time/clock.h"
-#include "absl/time/time.h"
-#include "platform/base/exception.h"
-
-namespace location {
-namespace nearby {
-
-namespace {
-const int kMaxThreads = 5;
-}
-
-TEST(MultiThreadExecutorTest, ConsructorDestructorWorks) {
- MultiThreadExecutor executor(kMaxThreads);
-}
-
-TEST(MultiThreadExecutorTest, CanExecute) {
- absl::CondVar cond;
- std::atomic_bool done = false;
- MultiThreadExecutor executor(kMaxThreads);
- executor.Execute([&done, &cond]() {
- done = true;
- cond.SignalAll();
- });
- absl::Mutex mutex;
- {
- absl::MutexLock lock(&mutex);
- if (!done) {
- cond.WaitWithTimeout(&mutex, absl::Seconds(1));
- }
- }
- EXPECT_TRUE(done);
-}
-
-TEST(MultiThreadExecutorTest, JobsExecuteInParallel) {
- absl::Mutex mutex;
- absl::CondVar thread_cond;
- absl::CondVar test_cond;
- MultiThreadExecutor executor(kMaxThreads);
- int count = 0;
-
- for (int i = 0; i < kMaxThreads; ++i) {
- executor.Execute([&count, &mutex, &test_cond, &thread_cond]() {
- absl::MutexLock lock(&mutex);
- count++;
- test_cond.Signal();
- thread_cond.Wait(&mutex);
- count--;
- test_cond.Signal();
- });
- }
-
- {
- absl::Duration duration = absl::Milliseconds(kMaxThreads * 100);
- absl::MutexLock lock(&mutex);
- while (count < kMaxThreads) {
- absl::Time start = absl::Now();
- if (test_cond.WaitWithTimeout(&mutex, duration)) break;
- duration -= absl::Now() - start;
- }
- }
-
- EXPECT_EQ(count, kMaxThreads);
- thread_cond.SignalAll();
-
- {
- absl::Duration duration = absl::Milliseconds(kMaxThreads * 100);
- absl::MutexLock lock(&mutex);
- while (count > 0) {
- absl::Time start = absl::Now();
- if (test_cond.WaitWithTimeout(&mutex, duration)) break;
- duration -= absl::Now() - start;
- }
- }
- EXPECT_EQ(count, 0);
-}
-
-TEST(MultiThreadExecutorTest, CanSubmit) {
- MultiThreadExecutor executor(kMaxThreads);
- Future<bool> future;
- bool submitted =
- executor.Submit<bool>([]() { return ExceptionOr<bool>{true}; }, &future);
- EXPECT_TRUE(submitted);
- EXPECT_TRUE(future.Get().result());
-}
-
-struct ThreadCheckTestClass {
- MultiThreadExecutor executor{kMaxThreads};
- int value ABSL_GUARDED_BY(executor) = 0;
-
- void incValue() ABSL_EXCLUSIVE_LOCKS_REQUIRED(executor) { value++; }
- int getValue() ABSL_EXCLUSIVE_LOCKS_REQUIRED(executor) { return value; }
-};
-
-TEST(MultiThreadExecutorTest, ThreadCheck_ExecuteRunnable) {
- ThreadCheckTestClass test_class;
-
- test_class.executor.Execute(
- [&test_class]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(test_class.executor) {
- test_class.incValue();
- });
-}
-
-TEST(MultiThreadExecutorTest, ThreadCheck_SubmitCallable) {
- ThreadCheckTestClass test_class;
- Future<int> future;
-
- bool submitted = test_class.executor.Submit<int>(
- [&test_class]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(test_class.executor) {
- return ExceptionOr<int>{test_class.getValue()};
- },
- &future);
-
- EXPECT_TRUE(submitted);
- EXPECT_EQ(future.Get().result(), 0);
-}
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/mutex.h b/chromium/third_party/nearby/src/cpp/platform/public/mutex.h
deleted file mode 100644
index ac19b5f7c9c..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/mutex.h
+++ /dev/null
@@ -1,78 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_MUTEX_H_
-#define PLATFORM_PUBLIC_MUTEX_H_
-
-#include <memory>
-
-#include "absl/base/thread_annotations.h"
-#include "platform/api/mutex.h"
-#include "platform/api/platform.h"
-
-namespace location {
-namespace nearby {
-
-// This is a classic mutex can be acquired at most once.
-// Atttempt to acuire mutex from the same thread that is holding it will likely
-// cause a deadlock.
-class ABSL_LOCKABLE Mutex final {
- public:
- using Platform = api::ImplementationPlatform;
- using Mode = api::Mutex::Mode;
-
- explicit Mutex(bool check = true)
- : impl_(Platform::CreateMutex(check ? Mode::kRegular
- : Mode::kRegularNoCheck)) {}
- Mutex(Mutex&&) = default;
- Mutex& operator=(Mutex&&) = default;
- ~Mutex() = default;
-
- void Lock() ABSL_EXCLUSIVE_LOCK_FUNCTION() { impl_->Lock(); }
- void Unlock() ABSL_UNLOCK_FUNCTION() { impl_->Unlock(); }
-
- private:
- friend class ConditionVariable;
- friend class MutexLock;
- std::unique_ptr<api::Mutex> impl_;
-};
-
-// This mutex is compatible with Java definition:
-// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/Lock.html
-// This mutex may be acuired multiple times by a thread that is already holding
-// it without blocking.
-// It needs to be released equal number of times before any other thread could
-// successfully acquire it.
-class ABSL_LOCKABLE RecursiveMutex final {
- public:
- using Platform = api::ImplementationPlatform;
- using Mode = api::Mutex::Mode;
-
- RecursiveMutex() : impl_(Platform::CreateMutex(Mode::kRecursive)) {}
- RecursiveMutex(RecursiveMutex&&) = default;
- RecursiveMutex& operator=(RecursiveMutex&&) = default;
- ~RecursiveMutex() = default;
-
- void Lock() ABSL_EXCLUSIVE_LOCK_FUNCTION() { impl_->Lock(); }
- void Unlock() ABSL_UNLOCK_FUNCTION() { impl_->Unlock(); }
-
- private:
- friend class MutexLock;
- std::unique_ptr<api::Mutex> impl_;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_MUTEX_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/mutex_lock.h b/chromium/third_party/nearby/src/cpp/platform/public/mutex_lock.h
deleted file mode 100644
index 4bf48bdcdf5..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/mutex_lock.h
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_MUTEX_LOCK_H_
-#define PLATFORM_PUBLIC_MUTEX_LOCK_H_
-
-#include "absl/base/thread_annotations.h"
-#include "platform/api/mutex.h"
-#include "platform/public/mutex.h"
-
-namespace location {
-namespace nearby {
-
-// An RAII mechanism to acquire a Lock over a block of code.
-class ABSL_SCOPED_LOCKABLE MutexLock final {
- public:
- explicit MutexLock(Mutex* mutex) ABSL_EXCLUSIVE_LOCK_FUNCTION(mutex)
- : mutex_(mutex->impl_.get()) {
- mutex_->Lock();
- }
- explicit MutexLock(RecursiveMutex* mutex) ABSL_EXCLUSIVE_LOCK_FUNCTION(mutex)
- : mutex_(mutex->impl_.get()) {
- mutex_->Lock();
- }
- ~MutexLock() ABSL_UNLOCK_FUNCTION() { mutex_->Unlock(); }
-
- private:
- api::Mutex* mutex_;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_MUTEX_LOCK_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/mutex_test.cc b/chromium/third_party/nearby/src/cpp/platform/public/mutex_test.cc
deleted file mode 100644
index ac1bb790f30..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/mutex_test.cc
+++ /dev/null
@@ -1,117 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/public/mutex.h"
-
-#include "gtest/gtest.h"
-#include "absl/synchronization/mutex.h"
-#include "absl/time/clock.h"
-#include "absl/time/time.h"
-#include "platform/public/condition_variable.h"
-#include "platform/public/single_thread_executor.h"
-
-namespace location {
-namespace nearby {
-namespace {
-
-class MutexTest : public testing::Test {
- public:
- void VerifyStepReached(int expected) {
- absl::MutexLock lock(&step_mutex_);
- absl::Time deadline = absl::Now() + kTimeToWait;
- while (step_ != expected) {
- if (step_cond_.WaitWithDeadline(&step_mutex_, deadline)) break;
- }
- EXPECT_EQ(step_, expected);
- // Make sure we are not progressing further.
- absl::SleepFor(kTimeToWait);
- EXPECT_EQ(step_, expected);
- }
-
- protected:
- SingleThreadExecutor executor_;
- const absl::Duration kTimeToWait = absl::Milliseconds(500);
- std::atomic_int step_ = 0;
- absl::Mutex step_mutex_;
- absl::CondVar step_cond_;
-};
-
-TEST_F(MutexTest, ConstructorDestructorWorks) {
- Mutex test_mutex;
- SUCCEED();
-}
-
-TEST_F(MutexTest, BasicLockingWorks) {
- Mutex test_mutex;
- test_mutex.Lock();
- executor_.Execute([this, &test_mutex]() {
- step_ = 1;
- step_cond_.Signal();
- test_mutex.Lock();
- test_mutex.Unlock();
- step_ = 2;
- step_cond_.Signal();
- });
- VerifyStepReached(1);
- test_mutex.Unlock();
- VerifyStepReached(2);
-}
-
-#ifdef THREAD_SANITIZER
-TEST_F(MutexTest, DISABLED_DoubleLockIsDeadlock)
-ABSL_NO_THREAD_SAFETY_ANALYSIS {
-#else
-TEST_F(MutexTest, DoubleLockIsDeadlock) ABSL_NO_THREAD_SAFETY_ANALYSIS {
-#endif
- Mutex test_mutex{/*check=*/false}; // Disable run-time deadlock detection.
- test_mutex.Lock();
- executor_.Execute([this, &test_mutex]() ABSL_NO_THREAD_SAFETY_ANALYSIS {
- step_ = 1;
- step_cond_.Signal(); // We entered executor.
- test_mutex.Lock();
- step_ = 2;
- step_cond_.Signal(); // We acquired the test lock.
- test_mutex.Lock(); // Deadlock. (Main thread should save us).
- step_ = 3;
- step_cond_.Signal(); // We are done.
- });
- VerifyStepReached(1);
- test_mutex.Unlock(); // Let executor proceed to step 2.
- VerifyStepReached(2);
- test_mutex.Unlock(); // Bring executor out of deadlock.
- VerifyStepReached(3);
- test_mutex.Unlock(); // Unlock before shutdown.
-}
-
-TEST_F(MutexTest, DoubleLockIsNotDeadlock) {
- RecursiveMutex test_mutex;
- test_mutex.Lock();
- executor_.Execute([this, &test_mutex]() ABSL_NO_THREAD_SAFETY_ANALYSIS {
- step_ = 1;
- step_cond_.Signal(); // We entered executor.
- test_mutex.Lock();
- test_mutex.Lock();
- test_mutex.Unlock();
- test_mutex.Unlock();
- step_ = 2;
- step_cond_.Signal(); // We are done.
- });
- VerifyStepReached(1);
- test_mutex.Unlock(); // Let executor continue.
- VerifyStepReached(2);
-}
-
-} // namespace
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/pending_job_registry.cc b/chromium/third_party/nearby/src/cpp/platform/public/pending_job_registry.cc
deleted file mode 100644
index 577c7b52afc..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/pending_job_registry.cc
+++ /dev/null
@@ -1,91 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/public/pending_job_registry.h"
-
-#include "platform/public/logging.h"
-#include "platform/public/mutex_lock.h"
-#include "platform/public/system_clock.h"
-
-namespace location {
-namespace nearby {
-
-namespace {
-absl::Duration kMinReportInterval = absl::Seconds(60);
-absl::Duration kReportPendingJobsOlderThan = absl::Seconds(40);
-absl::Duration kReportRunningJobsOlderThan = absl::Seconds(60);
-} // namespace
-
-PendingJobRegistry& PendingJobRegistry::GetInstance() {
- static PendingJobRegistry* instance = new PendingJobRegistry();
- return *instance;
-}
-
-PendingJobRegistry::PendingJobRegistry() = default;
-
-PendingJobRegistry::~PendingJobRegistry() = default;
-
-void PendingJobRegistry::AddPendingJob(const std::string& name,
- absl::Time post_time) {
- MutexLock lock(&mutex_);
- pending_jobs_.emplace(CreateKey(name, post_time), post_time);
-}
-
-void PendingJobRegistry::RemovePendingJob(const std::string& name,
- absl::Time post_time) {
- MutexLock lock(&mutex_);
- pending_jobs_.erase(CreateKey(name, post_time));
-}
-
-void PendingJobRegistry::AddRunningJob(const std::string& name,
- absl::Time post_time) {
- MutexLock lock(&mutex_);
- running_jobs_.emplace(CreateKey(name, post_time),
- SystemClock::ElapsedRealtime());
-}
-
-void PendingJobRegistry::RemoveRunningJob(const std::string& name,
- absl::Time post_time) {
- MutexLock lock(&mutex_);
- running_jobs_.erase(CreateKey(name, post_time));
-}
-
-void PendingJobRegistry::ListJobs() {
- auto current_time = SystemClock::ElapsedRealtime();
- MutexLock lock(&mutex_);
- if (current_time - list_jobs_time_ < kMinReportInterval) return;
- for (auto& job : pending_jobs_) {
- auto age = current_time - job.second;
- if (age >= kReportPendingJobsOlderThan) {
- NEARBY_LOGS(INFO) << "Task \"" << job.first << "\" is waiting for "
- << absl::ToInt64Seconds(age) << " s";
- }
- }
- for (auto& job : running_jobs_) {
- auto age = current_time - job.second;
- if (age >= kReportRunningJobsOlderThan) {
- NEARBY_LOGS(INFO) << "Task \"" << job.first << "\" is running for "
- << absl::ToInt64Seconds(age) << " s";
- }
- }
- list_jobs_time_ = current_time;
-}
-
-std::string PendingJobRegistry::CreateKey(const std::string& name,
- absl::Time post_time) {
- return name + "." + std::to_string(absl::ToUnixNanos(post_time));
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/pending_job_registry.h b/chromium/third_party/nearby/src/cpp/platform/public/pending_job_registry.h
deleted file mode 100644
index 4a7d5b650f5..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/pending_job_registry.h
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_PENDING_JOB_REGISTRY_H_
-#define PLATFORM_PUBLIC_PENDING_JOB_REGISTRY_H_
-
-#include "absl/base/thread_annotations.h"
-#include "absl/time/time.h"
-#include "platform/public/mutex.h"
-
-namespace location {
-namespace nearby {
-
-// A global registry of running tasks. The goal is to help us monitor
-// tasks that are either waiting too long for their turn or they never finish
-class PendingJobRegistry {
- public:
- static PendingJobRegistry& GetInstance();
-
- ~PendingJobRegistry();
-
- void AddPendingJob(const std::string& name, absl::Time post_time);
- void RemovePendingJob(const std::string& name, absl::Time post_time);
- void AddRunningJob(const std::string& name, absl::Time post_time);
- void RemoveRunningJob(const std::string& name, absl::Time post_time);
- void ListJobs();
-
- private:
- PendingJobRegistry();
-
- std::string CreateKey(const std::string& name, absl::Time post_time);
-
- Mutex mutex_;
- absl::flat_hash_map<const std::string, absl::Time> pending_jobs_
- ABSL_GUARDED_BY(mutex_);
- absl::flat_hash_map<const std::string, absl::Time> running_jobs_
- ABSL_GUARDED_BY(mutex_);
- absl::Time list_jobs_time_ ABSL_GUARDED_BY(mutex_) = absl::UnixEpoch();
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_PENDING_JOB_REGISTRY_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/pipe.cc b/chromium/third_party/nearby/src/cpp/platform/public/pipe.cc
deleted file mode 100644
index 39000e4f8e7..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/pipe.cc
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/public/pipe.h"
-
-#include "platform/api/condition_variable.h"
-#include "platform/api/mutex.h"
-#include "platform/api/platform.h"
-
-namespace location {
-namespace nearby {
-
-namespace {
-using Platform = api::ImplementationPlatform;
-}
-
-Pipe::Pipe() {
- auto mutex = Platform::CreateMutex(api::Mutex::Mode::kRegular);
- auto cond = Platform::CreateConditionVariable(mutex.get());
- Setup(std::move(mutex), std::move(cond));
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/pipe.h b/chromium/third_party/nearby/src/cpp/platform/public/pipe.h
deleted file mode 100644
index be5ac879752..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/pipe.h
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_PIPE_H_
-#define PLATFORM_PUBLIC_PIPE_H_
-
-#include "platform/base/base_pipe.h"
-
-namespace location {
-namespace nearby {
-
-// See for details:
-// http://google3/platform/base/base_pipe.h
-class Pipe final : public BasePipe {
- public:
- Pipe();
- ~Pipe() override = default;
- Pipe(Pipe&&) = delete;
- Pipe& operator=(Pipe&&) = delete;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_PIPE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/pipe_test.cc b/chromium/third_party/nearby/src/cpp/platform/public/pipe_test.cc
deleted file mode 100644
index 402140ee510..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/pipe_test.cc
+++ /dev/null
@@ -1,346 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/public/pipe.h"
-
-#include <pthread.h>
-
-#include <atomic>
-#include <cstring>
-#include <string>
-
-#include "gtest/gtest.h"
-#include "platform/base/prng.h"
-#include "platform/base/runnable.h"
-
-namespace location {
-namespace nearby {
-
-TEST(PipeTest, ConstructorDestructorWorks) {
- Pipe pipe;
- SUCCEED();
-}
-
-TEST(PipeTest, SimpleWriteRead) {
- Pipe pipe;
- InputStream& input_stream{pipe.GetInputStream()};
- OutputStream& output_stream{pipe.GetOutputStream()};
-
- std::string data("ABCD");
- EXPECT_TRUE(output_stream.Write(ByteArray(data)).Ok());
-
- ExceptionOr<ByteArray> read_data = input_stream.Read(Pipe::kChunkSize);
- EXPECT_TRUE(read_data.ok());
- EXPECT_EQ(data, std::string(read_data.result()));
-}
-
-TEST(PipeTest, WriteEndClosedBeforeRead) {
- Pipe pipe;
- InputStream& input_stream{pipe.GetInputStream()};
- OutputStream& output_stream{pipe.GetOutputStream()};
-
- std::string data("ABCD");
- EXPECT_TRUE(output_stream.Write(ByteArray(data)).Ok());
-
- // Close the write end before the read end has even begun reading.
- EXPECT_TRUE(output_stream.Close().Ok());
-
- // We should still be able to read what was written.
- ExceptionOr<ByteArray> read_data = input_stream.Read(Pipe::kChunkSize);
- EXPECT_TRUE(read_data.ok());
- EXPECT_EQ(data, std::string(read_data.result()));
-
- // And after that, we should get our indication that all the data that could
- // ever be read, has already been read.
- read_data = input_stream.Read(Pipe::kChunkSize);
- EXPECT_TRUE(read_data.ok());
- EXPECT_TRUE(read_data.result().Empty());
-}
-
-TEST(PipeTest, ReadEndClosedBeforeWrite) {
- Pipe pipe;
- InputStream& input_stream{pipe.GetInputStream()};
- OutputStream& output_stream{pipe.GetOutputStream()};
-
- // Close the read end before the write end has even begun writing.
- EXPECT_TRUE(input_stream.Close().Ok());
-
- std::string data("ABCD");
- EXPECT_TRUE(output_stream.Write(ByteArray(data)).Raised(Exception::kIo));
-}
-
-TEST(PipeTest, SizedReadMoreThanFirstChunkSize) {
- Pipe pipe;
- InputStream& input_stream{pipe.GetInputStream()};
- OutputStream& output_stream{pipe.GetOutputStream()};
-
- std::string data("ABCD");
- EXPECT_TRUE(output_stream.Write(ByteArray(data)).Ok());
-
- // Even though we ask for double of what's there in the first chunk, we should
- // get back only what's there in that first chunk, and that's alright.
- ExceptionOr<ByteArray> read_data = input_stream.Read(data.size() * 2);
- EXPECT_TRUE(read_data.ok());
- EXPECT_EQ(data, std::string(read_data.result()));
-}
-
-TEST(PipeTest, SizedReadLessThanFirstChunkSize) {
- Pipe pipe;
- InputStream& input_stream{pipe.GetInputStream()};
- OutputStream& output_stream{pipe.GetOutputStream()};
-
- std::string data_first_part("ABCD");
- std::string data_second_part("EFGHIJ");
- std::string data = data_first_part + data_second_part;
- EXPECT_TRUE(output_stream.Write(ByteArray(data)).Ok());
-
- // When we ask for less than what's there in the first chunk, we should get
- // back exactly what we asked for, with the remainder still being available
- // for the next read.
- std::int64_t desired_size = data_first_part.size();
- ExceptionOr<ByteArray> first_read_data = input_stream.Read(desired_size);
- EXPECT_TRUE(first_read_data.ok());
- EXPECT_EQ(data_first_part, std::string(first_read_data.result()));
-
- // Now read the remainder, and get everything that ought to have been left.
- ExceptionOr<ByteArray> second_read_data = input_stream.Read(Pipe::kChunkSize);
- EXPECT_TRUE(second_read_data.ok());
- EXPECT_EQ(data_second_part, std::string(second_read_data.result()));
-}
-
-TEST(PipeTest, ReadAfterInputStreamClosed) {
- Pipe pipe;
- InputStream& input_stream{pipe.GetInputStream()};
-
- input_stream.Close();
-
- ExceptionOr<ByteArray> read_data = input_stream.Read(Pipe::kChunkSize);
- EXPECT_TRUE(!read_data.ok());
- EXPECT_TRUE(read_data.GetException().Raised(Exception::kIo));
-}
-
-TEST(PipeTest, WriteAfterOutputStreamClosed) {
- Pipe pipe;
- OutputStream& output_stream{pipe.GetOutputStream()};
-
- output_stream.Close();
-
- std::string data("ABCD");
- EXPECT_TRUE(output_stream.Write(ByteArray(data)).Raised(Exception::kIo));
-}
-
-TEST(PipeTest, RepeatedClose) {
- Pipe pipe;
- InputStream& input_stream{pipe.GetInputStream()};
- OutputStream& output_stream{pipe.GetOutputStream()};
-
- EXPECT_TRUE(output_stream.Close().Ok());
- EXPECT_TRUE(output_stream.Close().Ok());
- EXPECT_TRUE(output_stream.Close().Ok());
-
- EXPECT_TRUE(input_stream.Close().Ok());
- EXPECT_TRUE(input_stream.Close().Ok());
- EXPECT_TRUE(input_stream.Close().Ok());
-}
-
-class Thread {
- public:
- Thread() : thread_(), attr_(), runnable_() {
- pthread_attr_init(&attr_);
- pthread_attr_setdetachstate(&attr_, PTHREAD_CREATE_JOINABLE);
- }
- ~Thread() { pthread_attr_destroy(&attr_); }
-
- void Start(Runnable runnable) {
- runnable_ = runnable;
-
- pthread_create(&thread_, &attr_, Thread::Body, this);
- }
-
- void Join() { pthread_join(thread_, nullptr); }
-
- private:
- static void* Body(void* args) {
- reinterpret_cast<Thread*>(args)->runnable_();
- return nullptr;
- }
-
- pthread_t thread_;
- pthread_attr_t attr_;
- Runnable runnable_;
-};
-
-TEST(PipeTest, ReadBlockedUntilWrite) {
- using CrossThreadBool = std::atomic_bool;
-
- class ReaderRunnable {
- public:
- ReaderRunnable(InputStream* input_stream,
- absl::string_view expected_read_data,
- CrossThreadBool* ok_for_read_to_unblock)
- : input_stream_(input_stream),
- expected_read_data_(expected_read_data),
- ok_for_read_to_unblock_(ok_for_read_to_unblock) {}
- ~ReaderRunnable() = default;
-
- // Signature "void()" satisfies Runnable.
- void operator()() {
- ExceptionOr<ByteArray> read_data = input_stream_->Read(Pipe::kChunkSize);
-
- // Make sure read() doesn't return before it's appropriate.
- if (!*ok_for_read_to_unblock_) {
- FAIL() << "read() unblocked before it was supposed to.";
- }
-
- // And then run our normal set of checks to make sure the read() was
- // successful.
- EXPECT_TRUE(read_data.ok());
- EXPECT_EQ(expected_read_data_, std::string(read_data.result()));
- }
-
- private:
- InputStream* input_stream_;
- const std::string expected_read_data_;
- CrossThreadBool* ok_for_read_to_unblock_;
- };
-
- Pipe pipe;
- OutputStream& output_stream{pipe.GetOutputStream()};
-
- // State shared between this thread (the writer) and reader_thread.
- CrossThreadBool ok_for_read_to_unblock = false;
- std::string data("ABCD");
-
- // Kick off reader_thread.
- Thread reader_thread;
- reader_thread.Start(
- ReaderRunnable(&pipe.GetInputStream(), data, &ok_for_read_to_unblock));
-
- // Introduce a delay before we actually write anything.
- absl::SleepFor(absl::Seconds(5));
- // Mark that we're done with the delay, and that the write is about to occur
- // (this is slightly earlier than it ought to be, but there's no way to
- // atomically set this from within the implementation of write(), and doing it
- // after is too late for the purposes of this test).
- ok_for_read_to_unblock = true;
-
- // Perform the actual write.
- EXPECT_TRUE(output_stream.Write(ByteArray(data)).Ok());
-
- // And wait for reader_thread to finish.
- reader_thread.Join();
-}
-
-TEST(PipeTest, ConcurrentWriteAndRead) {
- class BaseRunnable {
- protected:
- explicit BaseRunnable(const std::vector<std::string>& chunks)
- : chunks_(chunks), prng_() {}
- virtual ~BaseRunnable() = default;
-
- void RandomSleep() {
- // Generate a random sleep between 100 and 1000 milliseconds.
- absl::SleepFor(absl::Milliseconds(BoundedUint32(100, 1000)));
- }
-
- const std::vector<std::string>& chunks_;
-
- private:
- // Both ends of the bounds are inclusive.
- std::uint32_t BoundedUint32(std::uint32_t lower_bound,
- std::uint32_t upper_bound) {
- return (prng_.NextUint32() % (upper_bound - lower_bound + 1)) +
- lower_bound;
- }
-
- Prng prng_;
- };
-
- class WriterRunnable : public BaseRunnable {
- public:
- WriterRunnable(OutputStream* output_stream,
- const std::vector<std::string>& chunks)
- : BaseRunnable(chunks), output_stream_(output_stream) {}
- ~WriterRunnable() override = default;
-
- void operator()() {
- for (auto& chunk : chunks_) {
- RandomSleep(); // Random pauses before each write.
- EXPECT_TRUE(output_stream_->Write(ByteArray(chunk)).Ok());
- }
-
- RandomSleep(); // A random pause before closing the writer end.
- EXPECT_TRUE(output_stream_->Close().Ok());
- }
-
- private:
- OutputStream* output_stream_;
- };
-
- class ReaderRunnable : public BaseRunnable {
- public:
- ReaderRunnable(InputStream* input_stream,
- const std::vector<std::string>& chunks)
- : BaseRunnable(chunks), input_stream_(input_stream) {}
- ~ReaderRunnable() override = default;
-
- void operator()() {
- // First, calculate what we expect to receive, in total.
- std::string expected_data;
- for (auto& chunk : chunks_) {
- expected_data += chunk;
- }
-
- // Then, start actually receiving.
- std::string actual_data;
- while (true) {
- RandomSleep(); // Random pauses before each read.
- ExceptionOr<ByteArray> read_data =
- input_stream_->Read(Pipe::kChunkSize);
- if (read_data.ok()) {
- ByteArray result = read_data.result();
- if (result.Empty()) {
- break; // Normal exit from the read loop.
- }
- actual_data += std::string(result);
- } else {
- break; // Erroneous exit from the read loop.
- }
- }
-
- // And once we're done, check that we got everything we expected.
- EXPECT_EQ(expected_data, actual_data);
- }
-
- private:
- InputStream* input_stream_;
- };
-
- Pipe pipe;
-
- std::vector<std::string> chunks;
- chunks.push_back("ABCD");
- chunks.push_back("EFGH");
- chunks.push_back("IJKL");
-
- Thread writer_thread;
- Thread reader_thread;
- writer_thread.Start(WriterRunnable(&pipe.GetOutputStream(), chunks));
- reader_thread.Start(ReaderRunnable(&pipe.GetInputStream(), chunks));
- writer_thread.Join();
- reader_thread.Join();
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/scheduled_executor.h b/chromium/third_party/nearby/src/cpp/platform/public/scheduled_executor.h
deleted file mode 100644
index 921da2a58da..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/scheduled_executor.h
+++ /dev/null
@@ -1,109 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_SCHEDULED_EXECUTOR_H_
-#define PLATFORM_PUBLIC_SCHEDULED_EXECUTOR_H_
-
-#include <cstdint>
-#include <functional>
-#include <memory>
-
-#include "absl/base/thread_annotations.h"
-#include "absl/time/time.h"
-#include "platform/api/platform.h"
-#include "platform/api/scheduled_executor.h"
-#include "platform/base/runnable.h"
-#include "platform/public/cancelable.h"
-#include "platform/public/cancellable_task.h"
-#include "platform/public/lockable.h"
-#include "platform/public/monitored_runnable.h"
-#include "platform/public/mutex.h"
-#include "platform/public/mutex_lock.h"
-#include "platform/public/thread_check_callable.h"
-#include "platform/public/thread_check_runnable.h"
-
-namespace location {
-namespace nearby {
-
-// An Executor that can schedule commands to run after a given delay, or to
-// execute periodically.
-//
-// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html
-class ABSL_LOCKABLE ScheduledExecutor final : public Lockable {
- public:
- using Platform = api::ImplementationPlatform;
-
- ScheduledExecutor() : impl_(Platform::CreateScheduledExecutor()) {}
- ScheduledExecutor(ScheduledExecutor&& other) { *this = std::move(other); }
- ~ScheduledExecutor() {
- MutexLock lock(&mutex_);
- DoShutdown();
- }
-
- ScheduledExecutor& operator=(ScheduledExecutor&& other)
- ABSL_LOCKS_EXCLUDED(mutex_) {
- MutexLock lock(&mutex_);
- {
- MutexLock other_lock(&other.mutex_);
- impl_ = std::move(other.impl_);
- }
- return *this;
- }
- void Execute(const std::string& name, Runnable&& runnable)
- ABSL_LOCKS_EXCLUDED(mutex_) {
- MutexLock lock(&mutex_);
- if (impl_)
- impl_->Execute(MonitoredRunnable(
- name, ThreadCheckRunnable(this, std::move(runnable))));
- }
-
- void Execute(Runnable&& runnable) ABSL_LOCKS_EXCLUDED(mutex_) {
- MutexLock lock(&mutex_);
- if (impl_) impl_->Execute(ThreadCheckRunnable(this, std::move(runnable)));
- }
-
- void Shutdown() ABSL_LOCKS_EXCLUDED(mutex_) {
- MutexLock lock(&mutex_);
- DoShutdown();
- }
-
- Cancelable Schedule(Runnable&& runnable, absl::Duration duration)
- ABSL_LOCKS_EXCLUDED(mutex_) {
- MutexLock lock(&mutex_);
- if (impl_) {
- auto task = std::make_shared<CancellableTask>(
- ThreadCheckRunnable(this, std::move(runnable)));
- return Cancelable(task,
- impl_->Schedule([task]() { (*task)(); }, duration));
- } else {
- return Cancelable();
- }
- }
-
- private:
- void DoShutdown() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_) {
- if (impl_) {
- impl_->Shutdown();
- impl_.reset();
- }
- }
-
- mutable Mutex mutex_;
- std::unique_ptr<api::ScheduledExecutor> ABSL_GUARDED_BY(mutex_) impl_;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_SCHEDULED_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/scheduled_executor_test.cc b/chromium/third_party/nearby/src/cpp/platform/public/scheduled_executor_test.cc
deleted file mode 100644
index ecfadd03ae4..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/scheduled_executor_test.cc
+++ /dev/null
@@ -1,206 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/public/scheduled_executor.h"
-
-#include <atomic>
-#include <functional>
-
-#include "gtest/gtest.h"
-#include "absl/synchronization/mutex.h"
-#include "absl/time/clock.h"
-#include "absl/time/time.h"
-#include "platform/base/exception.h"
-#include "platform/public/count_down_latch.h"
-
-namespace location {
-namespace nearby {
-
-// kShortDelay must be significant enough to guarantee that OS under heavy load
-// should be able to execute the non-blocking test paths within this time.
-absl::Duration kShortDelay = absl::Milliseconds(100);
-
-// kLongDelay must be long enough to make sure that under OS under heavy load
-// will let kShortDelay fire and jobs scheduled before the kLongDelay fires.
-absl::Duration kLongDelay = 10 * kShortDelay;
-
-TEST(ScheduledExecutorTest, ConsructorDestructorWorks) {
- ScheduledExecutor executor;
-}
-
-TEST(ScheduledExecutorTest, CanExecute) {
- absl::Mutex mutex;
- absl::CondVar cond;
- std::atomic_bool done = false;
- ScheduledExecutor executor;
- executor.Execute([&done, &cond]() {
- done = true;
- cond.SignalAll();
- });
- {
- absl::MutexLock lock(&mutex);
- if (!done) {
- cond.WaitWithTimeout(&mutex, kLongDelay);
- }
- }
- EXPECT_TRUE(done);
-}
-
-TEST(ScheduledExecutorTest, CanSchedule) {
- ScheduledExecutor executor;
- std::atomic_int value = 0;
- absl::Mutex mutex;
- absl::CondVar cond;
- // schedule job due in kLongDelay.
- executor.Schedule(
- [&value, &cond]() {
- EXPECT_EQ(value, 1);
- value = 5;
- cond.Signal();
- },
- kLongDelay);
- // schedule job due in kShortDelay; must fire before the first one.
- executor.Schedule(
- [&value]() {
- EXPECT_EQ(value, 0);
- value = 1;
- },
- kShortDelay);
- {
- // wait for the final job to unblock us; wait longer than kLongDelay.
- absl::MutexLock lock(&mutex);
- cond.WaitWithTimeout(&mutex, 2 * kLongDelay);
- }
- EXPECT_EQ(value, 5);
-}
-
-TEST(ScheduledExecutorTest, CanCancel) {
- ScheduledExecutor executor;
- std::atomic_int value = 0;
- Cancelable cancelable =
- executor.Schedule([&value]() { value += 1; }, kShortDelay);
- EXPECT_EQ(value, 0);
- EXPECT_TRUE(cancelable.Cancel());
- absl::SleepFor(kLongDelay);
- EXPECT_EQ(value, 0);
-}
-
-TEST(ScheduledExecutorTest, CanCancelTwice) {
- ScheduledExecutor executor;
- std::atomic_int value = 0;
- Cancelable cancelable =
- executor.Schedule([&value]() { value += 1; }, kShortDelay);
- EXPECT_EQ(value, 0);
-
- cancelable.Cancel();
- cancelable.Cancel();
-
- absl::SleepFor(kLongDelay);
- EXPECT_EQ(value, 0);
-}
-
-TEST(ScheduledExecutorTest, FailToCancel) {
- absl::Mutex mutex;
- absl::CondVar cond;
- ScheduledExecutor executor;
- std::atomic_int value = 0;
- // Schedule job in kShortDelay, which will we will attempt to cancel later.
- Cancelable cancelable =
- executor.Schedule([&value]() { value += 1; }, kShortDelay);
- // schedule another job to test results of the first one, in kLongDelay.
- executor.Schedule(
- [&cancelable, &cond]() {
- EXPECT_FALSE(cancelable.Cancel());
- // Wake up main thread.
- cond.Signal();
- },
- kLongDelay);
- {
- absl::MutexLock lock(&mutex);
- cond.Wait(&mutex);
- }
- EXPECT_EQ(value, 1);
-}
-
-TEST(ScheduledExecutorTest,
- CancelWhileRunning_TaskCompletesBeforeCancelReturns) {
- CountDownLatch start_latch(1);
- ScheduledExecutor executor;
- std::atomic_int value = 0;
- // A task that takes a little bit of time to complete
- Cancelable cancelable = executor.Schedule(
- [&start_latch, &value]() {
- start_latch.CountDown();
- absl::SleepFor(kLongDelay);
- value += 1;
- },
- absl::ZeroDuration());
-
- start_latch.Await();
- cancelable.Cancel();
-
- EXPECT_EQ(value, 1);
-}
-
-TEST(ScheduledExecutorTest,
- CancelTwiceWhileRunning_TaskCompletesBeforeCancelReturns) {
- CountDownLatch start_latch(1);
- ScheduledExecutor executor;
- std::atomic_int value = 0;
- // A task that takes a little bit of time to complete
- Cancelable cancelable = executor.Schedule(
- [&start_latch, &value]() {
- start_latch.CountDown();
- absl::SleepFor(kLongDelay);
- value += 1;
- },
- absl::ZeroDuration());
-
- start_latch.Await();
-
- cancelable.Cancel();
- cancelable.Cancel();
-
- EXPECT_EQ(value, 1);
-}
-
-struct ThreadCheckTestClass {
- ScheduledExecutor executor;
- int value ABSL_GUARDED_BY(executor) = 0;
-
- void incValue() ABSL_EXCLUSIVE_LOCKS_REQUIRED(executor) { value++; }
- int getValue() ABSL_EXCLUSIVE_LOCKS_REQUIRED(executor) { return value; }
-};
-
-TEST(ScheduledExecutorTest, ThreadCheck_Execute) {
- ThreadCheckTestClass test_class;
-
- test_class.executor.Execute(
- [&test_class]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(test_class.executor) {
- test_class.incValue();
- });
-}
-
-TEST(ScheduledExecutorTest, ThreadCheck_Schedule) {
- ThreadCheckTestClass test_class;
-
- test_class.executor.Schedule(
- [&test_class]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(test_class.executor) {
- test_class.incValue();
- },
- absl::ZeroDuration());
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/settable_future.h b/chromium/third_party/nearby/src/cpp/platform/public/settable_future.h
deleted file mode 100644
index 512d0e72796..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/settable_future.h
+++ /dev/null
@@ -1,128 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_SETTABLE_FUTURE_H_
-#define PLATFORM_PUBLIC_SETTABLE_FUTURE_H_
-
-#include <utility>
-
-#include "platform/public/condition_variable.h"
-#include "platform/public/mutex.h"
-#include "platform/public/mutex_lock.h"
-#include "platform/public/system_clock.h"
-
-namespace location {
-namespace nearby {
-
-template <typename T>
-class SettableFuture : public api::SettableFuture<T> {
- public:
- SettableFuture() = default;
- ~SettableFuture() override = default;
-
- bool Set(T value) override {
- MutexLock lock(&mutex_);
- if (!done_) {
- value_ = std::move(value);
- done_ = true;
- exception_ = {Exception::kSuccess};
- completed_.Notify();
- InvokeAllLocked();
- return true;
- }
- return false;
- }
-
- void AddListener(Runnable runnable, api::Executor* executor) override {
- MutexLock lock(&mutex_);
- if (done_) {
- executor->Execute(std::move(runnable));
- } else {
- listeners_.emplace_back(std::make_pair(executor, std::move(runnable)));
- }
- }
-
- bool IsSet() const {
- MutexLock lock(&mutex_);
- return done_;
- }
-
- bool SetException(Exception exception) override {
- MutexLock lock(&mutex_);
- return SetExceptionLocked(exception);
- }
-
- ExceptionOr<T> Get() override {
- MutexLock lock(&mutex_);
- while (!done_) {
- completed_.Wait();
- }
- return exception_.value != Exception::kSuccess
- ? ExceptionOr<T>{exception_.value}
- : ExceptionOr<T>{value_};
- }
-
- ExceptionOr<T> Get(absl::Duration timeout) override {
- MutexLock lock(&mutex_);
- while (!done_) {
- absl::Time start_time = SystemClock::ElapsedRealtime();
- if (completed_.Wait(timeout).Raised(Exception::kInterrupted)) {
- SetExceptionLocked({Exception::kInterrupted});
- break;
- }
- absl::Duration spent = SystemClock::ElapsedRealtime() - start_time;
- if (spent < timeout) {
- timeout -= spent;
- } else if (!done_) {
- SetExceptionLocked({Exception::kTimeout});
- break;
- }
- }
- return exception_.value != Exception::kSuccess
- ? ExceptionOr<T>{exception_.value}
- : ExceptionOr<T>{value_};
- }
-
- private:
- bool SetExceptionLocked(Exception exception) {
- if (!done_) {
- exception_ = exception.value != Exception::kSuccess
- ? exception
- : Exception{Exception::kFailed};
- done_ = true;
- completed_.Notify();
- InvokeAllLocked();
- }
- return true;
- }
-
- void InvokeAllLocked() {
- for (auto& item : listeners_) {
- item.first->Execute(std::move(item.second));
- }
- listeners_.clear();
- }
-
- mutable Mutex mutex_;
- ConditionVariable completed_{&mutex_};
- std::vector<std::pair<api::Executor*, std::function<void()>>> listeners_;
- bool done_{false};
- T value_;
- Exception exception_{Exception::kFailed};
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_SETTABLE_FUTURE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/single_thread_executor.h b/chromium/third_party/nearby/src/cpp/platform/public/single_thread_executor.h
deleted file mode 100644
index 9be5a34ab9c..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/single_thread_executor.h
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_SINGLE_THREAD_EXECUTOR_H_
-#define PLATFORM_PUBLIC_SINGLE_THREAD_EXECUTOR_H_
-
-#include "absl/base/thread_annotations.h"
-#include "platform/public/submittable_executor.h"
-
-namespace location {
-namespace nearby {
-
-// An Executor that uses a single worker thread operating off an unbounded
-// queue.
-//
-// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newSingleThreadExecutor--
-class ABSL_LOCKABLE SingleThreadExecutor final : public SubmittableExecutor {
- public:
- using Platform = api::ImplementationPlatform;
- SingleThreadExecutor()
- : SubmittableExecutor(Platform::CreateSingleThreadExecutor()) {}
- ~SingleThreadExecutor() override = default;
- SingleThreadExecutor(SingleThreadExecutor&&) = default;
- SingleThreadExecutor& operator=(SingleThreadExecutor&&) = default;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_SINGLE_THREAD_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/single_thread_executor_test.cc b/chromium/third_party/nearby/src/cpp/platform/public/single_thread_executor_test.cc
deleted file mode 100644
index f610578fb82..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/single_thread_executor_test.cc
+++ /dev/null
@@ -1,139 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/public/single_thread_executor.h"
-
-#include <atomic>
-#include <functional>
-#include <string>
-
-#include "gtest/gtest.h"
-#include "absl/synchronization/mutex.h"
-#include "absl/time/clock.h"
-#include "platform/base/exception.h"
-
-namespace location {
-namespace nearby {
-
-TEST(SingleThreadExecutorTest, ConsructorDestructorWorks) {
- SingleThreadExecutor executor;
-}
-
-TEST(SingleThreadExecutorTest, CanExecute) {
- absl::CondVar cond;
- std::atomic_bool done = false;
- SingleThreadExecutor executor;
- executor.Execute([&done, &cond]() {
- done = true;
- cond.SignalAll();
- });
- absl::Mutex mutex;
- {
- absl::MutexLock lock(&mutex);
- if (!done) {
- cond.WaitWithTimeout(&mutex, absl::Seconds(1));
- }
- }
- EXPECT_TRUE(done);
-}
-
-TEST(SingleThreadExecutorTest, CanExecuteNamedTask) {
- absl::CondVar cond;
- std::atomic_bool done = false;
- SingleThreadExecutor executor;
- executor.Execute("my task", [&done, &cond]() {
- done = true;
- cond.SignalAll();
- });
- absl::Mutex mutex;
- {
- absl::MutexLock lock(&mutex);
- if (!done) {
- cond.WaitWithTimeout(&mutex, absl::Seconds(1));
- }
- }
- EXPECT_TRUE(done);
-}
-
-TEST(SingleThreadExecutorTest, JobsExecuteInOrder) {
- std::vector<int> results;
- SingleThreadExecutor executor;
-
- for (int i = 0; i < 10; ++i) {
- executor.Execute([i, &results]() { results.push_back(i); });
- }
-
- absl::CondVar cond;
- std::atomic_bool done = false;
- executor.Execute([&done, &cond]() {
- done = true;
- cond.SignalAll();
- });
- absl::Mutex mutex;
- {
- absl::MutexLock lock(&mutex);
- if (!done) {
- cond.WaitWithTimeout(&mutex, absl::Seconds(1));
- }
- }
- EXPECT_TRUE(done);
- EXPECT_EQ(results, (std::vector<int>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}));
-}
-
-TEST(SingleThreadExecutorTest, CanSubmit) {
- SingleThreadExecutor executor;
- Future<bool> future;
- bool submitted =
- executor.Submit<bool>([]() { return ExceptionOr<bool>{true}; }, &future);
- EXPECT_TRUE(submitted);
- EXPECT_TRUE(future.Get().result());
-}
-
-struct ThreadCheckTestClass {
- SingleThreadExecutor executor;
- int value ABSL_GUARDED_BY(executor) = 0;
-
- void incValue() ABSL_EXCLUSIVE_LOCKS_REQUIRED(executor) { value++; }
- int getValue() ABSL_EXCLUSIVE_LOCKS_REQUIRED(executor) { return value; }
-};
-
-TEST(SingleThreadExecutorTest, ThreadCheck_ExecuteRunnable) {
- ThreadCheckTestClass test_class;
-
- test_class.executor.Execute(
- [&test_class]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(test_class.executor) {
- test_class.incValue();
- });
-}
-
-TEST(SingleThreadExecutorTest, ThreadCheck_SubmitCallable) {
- ThreadCheckTestClass test_class;
- test_class.executor.Execute(
- [&test_class]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(test_class.executor) {
- test_class.incValue();
- });
- Future<int> future;
-
- bool submitted = test_class.executor.Submit<int>(
- [&test_class]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(test_class.executor) {
- return ExceptionOr<int>{test_class.getValue()};
- },
- &future);
-
- EXPECT_TRUE(submitted);
- EXPECT_EQ(future.Get().result(), 1);
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/submittable_executor.h b/chromium/third_party/nearby/src/cpp/platform/public/submittable_executor.h
deleted file mode 100644
index 105f8931745..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/submittable_executor.h
+++ /dev/null
@@ -1,130 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_SUBMITTABLE_EXECUTOR_H_
-#define PLATFORM_PUBLIC_SUBMITTABLE_EXECUTOR_H_
-
-#include <cstddef>
-#include <functional>
-#include <memory>
-#include <utility>
-
-#include "absl/base/thread_annotations.h"
-#include "platform/api/executor.h"
-#include "platform/api/submittable_executor.h"
-#include "platform/base/callable.h"
-#include "platform/base/runnable.h"
-#include "platform/public/future.h"
-#include "platform/public/lockable.h"
-#include "platform/public/monitored_runnable.h"
-#include "platform/public/mutex.h"
-#include "platform/public/mutex_lock.h"
-#include "platform/public/thread_check_callable.h"
-#include "platform/public/thread_check_runnable.h"
-
-namespace location {
-namespace nearby {
-
-inline int GetCurrentTid() { return api::GetCurrentTid(); }
-
-// Main interface to be used by platform as a base class for
-// - MultiThreadExecutor
-// - SingleThreadExecutor
-class ABSL_LOCKABLE SubmittableExecutor : public api::SubmittableExecutor,
- public Lockable {
- public:
- ~SubmittableExecutor() override {
- MutexLock lock(&mutex_);
- DoShutdown();
- }
- SubmittableExecutor(SubmittableExecutor&& other) { *this = std::move(other); }
- SubmittableExecutor& operator=(SubmittableExecutor&& other)
- ABSL_LOCKS_EXCLUDED(mutex_) {
- MutexLock lock(&mutex_);
- {
- MutexLock other_lock(&other.mutex_);
- impl_ = std::move(other.impl_);
- }
- return *this;
- }
- void Execute(const std::string& name, Runnable&& runnable)
- ABSL_LOCKS_EXCLUDED(mutex_) {
- MutexLock lock(&mutex_);
- if (impl_)
- impl_->Execute(MonitoredRunnable(
- name, ThreadCheckRunnable(this, std::move(runnable))));
- }
-
- void Execute(Runnable&& runnable) ABSL_LOCKS_EXCLUDED(mutex_) override {
- MutexLock lock(&mutex_);
- if (impl_)
- impl_->Execute(
- MonitoredRunnable(ThreadCheckRunnable(this, std::move(runnable))));
- }
-
- void Shutdown() ABSL_LOCKS_EXCLUDED(mutex_) override {
- MutexLock lock(&mutex_);
- DoShutdown();
- }
-
- // Submits a callable for execution.
- // When execution completes, return value is assigned to the passed future.
- // Future must outlive the whole execution chain.
- template <typename T>
- bool Submit(Callable<T>&& callable, Future<T>* future)
- ABSL_LOCKS_EXCLUDED(mutex_) {
- MutexLock lock(&mutex_);
- bool submitted =
- DoSubmit([callable = ThreadCheckCallable<T>(this, std::move(callable)),
- future]() {
- ExceptionOr<T> result = callable();
- if (result.ok()) {
- future->Set(result.result());
- } else {
- future->SetException({result.exception()});
- }
- });
- if (!submitted) {
- // complete immediately with kExecution exception value.
- future->SetException({Exception::kExecution});
- }
- return submitted;
- }
-
- protected:
- explicit SubmittableExecutor(std::unique_ptr<api::SubmittableExecutor> impl)
- : impl_(std::move(impl)) {}
-
- private:
- void DoShutdown() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_) {
- if (impl_) {
- impl_->Shutdown();
- impl_.reset();
- }
- }
- // Submit a callable (with no delay).
- // Returns true, if callable was submitted, false otherwise.
- // Callable is not submitted if shutdown is in progress.
- bool DoSubmit(Runnable&& wrapped_callable)
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_) override {
- return impl_ ? impl_->DoSubmit(std::move(wrapped_callable)) : false;
- }
- mutable Mutex mutex_;
- std::unique_ptr<api::SubmittableExecutor> ABSL_GUARDED_BY(mutex_) impl_;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_SUBMITTABLE_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/system_clock.h b/chromium/third_party/nearby/src/cpp/platform/public/system_clock.h
deleted file mode 100644
index df21c63ce16..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/system_clock.h
+++ /dev/null
@@ -1,20 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_SYSTEM_CLOCK_H_
-#define PLATFORM_PUBLIC_SYSTEM_CLOCK_H_
-
-#include "platform/api/system_clock.h"
-
-#endif // PLATFORM_PUBLIC_SYSTEM_CLOCK_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/thread_check_callable.h b/chromium/third_party/nearby/src/cpp/platform/public/thread_check_callable.h
deleted file mode 100644
index bf43ee84ac4..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/thread_check_callable.h
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_THREAD_CHECK_CALLABLE_H_
-#define PLATFORM_PUBLIC_THREAD_CHECK_CALLABLE_H_
-
-#include "absl/base/thread_annotations.h"
-#include "platform/base/callable.h"
-#include "platform/public/lockable.h"
-
-namespace location {
-namespace nearby {
-
-// A callable that acquires a lockable resource while running.
-// This class helps with thread safety analysis.
-template <typename T>
-class ThreadCheckCallable {
- public:
- ThreadCheckCallable(const Lockable *lockable, Callable<T> &&callable)
- : lockable_{lockable}, callable_{callable} {}
-
- ExceptionOr<T> operator()() const {
- ThreadLockHolder thread_lock(lockable_);
- return callable_();
- }
-
- private:
- Lockable const *lockable_;
- Callable<T> callable_;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_THREAD_CHECK_CALLABLE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/thread_check_nocompile.cc b/chromium/third_party/nearby/src/cpp/platform/public/thread_check_nocompile.cc
deleted file mode 100644
index bf215ba7bc8..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/thread_check_nocompile.cc
+++ /dev/null
@@ -1,83 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "absl/time/time.h"
-#include "platform/public/scheduled_executor.h"
-#include "platform/public/single_thread_executor.h"
-
-// Snippets of invalid code that should trigger an error during thread
-// safety analysis at compile time.
-// See https://g3doc.corp.google.com/googletest/g3doc/cpp_nc_test.md
-namespace location {
-namespace nearby {
-
-#ifdef TEST_EXECUTE_MISSING_METHOD_ANNOTATION
-struct ThreadCheckTestClass {
- SingleThreadExecutor executor;
- int value ABSL_GUARDED_BY(executor) = 0;
-
- void incValue() { value++; }
-};
-
-void TestExecute_MissingMethodAnnotation() {
- ThreadCheckTestClass test_class;
-
- test_class.executor.Execute(
- [&test_class]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(test_class.executor) {
- test_class.incValue();
- });
-}
-#endif // TEST_EXECUTE_MISSING_METHOD_ANNOTATION
-
-#ifdef TEST_SUBMIT_MISSING_METHOD_ANNOTATION
-struct ThreadCheckTestClass {
- SingleThreadExecutor executor;
- int value ABSL_GUARDED_BY(executor) = 0;
-
- int getValue() { return value; }
-};
-
-void TestSubmit_MissingMethodAnnotation() {
- ThreadCheckTestClass test_class;
- Future<int> future;
-
- test_class.executor.Submit<int>(
- [&test_class]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(test_class.executor) {
- return ExceptionOr<int>{test_class.getValue()};
- },
- &future);
-}
-#endif // TEST_SUBMIT_MISSING_METHOD_ANNOTATION
-
-#ifdef TEST_SCHEDULE_MISSING_METHOD_ANNOTATION
-struct ThreadCheckTestClass {
- ScheduledExecutor executor;
- int value ABSL_GUARDED_BY(executor) = 0;
-
- void incValue() { value++; }
-};
-
-void TestSchedule_MissingMethodAnnotation() {
- ThreadCheckTestClass test_class;
-
- test_class.executor.Schedule(
- [&test_class]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(test_class.executor) {
- test_class.incValue();
- },
- absl::ZeroDuration());
-}
-#endif // TEST_SCHEDULE_MISSING_METHOD_ANNOTATION
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/thread_check_nocompile_test.py b/chromium/third_party/nearby/src/cpp/platform/public/thread_check_nocompile_test.py
deleted file mode 100644
index 565779606c0..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/thread_check_nocompile_test.py
+++ /dev/null
@@ -1,26 +0,0 @@
-"""Negative tests for thread safety analysis in executors implementation."""
-
-from google3.testing.pybase import fake_target_util
-from google3.testing.pybase import googletest
-
-
-class ThreadCheckNocompileTest(googletest.TestCase):
- """Negative tests for thread safety analysis in executors implementation."""
-
- def testCompilerErrors(self):
- """Runs a list of tests to verify that erroneous code leads to expected compiler messages."""
- test_specs = [
- ('EXECUTE_MISSING_METHOD_ANNOTATION', [r'-Wthread-safety-analysis']),
- ('SUBMIT_MISSING_METHOD_ANNOTATION', [r'-Wthread-safety-analysis']),
- ('SCHEDULE_MISSING_METHOD_ANNOTATION', [r'-Wthread-safety-analysis']),
- # Tests that compiling a valid C++ succeeds.
- ('SANITY', None) # None means that the compilation should succeed.
- ]
- fake_target_util.AssertCcCompilerErrors(
- self,
- 'google3/platform/public/thread_check_nocompile',
- 'thread_check_nocompile.o', test_specs)
-
-
-if __name__ == '__main__':
- googletest.main()
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/thread_check_runnable.h b/chromium/third_party/nearby/src/cpp/platform/public/thread_check_runnable.h
deleted file mode 100644
index 3cce9ce1afb..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/thread_check_runnable.h
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_THREAD_CHECK_RUNNABLE_H_
-#define PLATFORM_PUBLIC_THREAD_CHECK_RUNNABLE_H_
-
-#include <utility>
-
-#include "absl/base/thread_annotations.h"
-#include "platform/base/runnable.h"
-#include "platform/public/lockable.h"
-
-namespace location {
-namespace nearby {
-
-// A runnable that acquires a lockable resource while running.
-// This class helps with thread safety analysis.
-class ThreadCheckRunnable {
- public:
- ThreadCheckRunnable(const Lockable *lockable, Runnable &&runnable)
- : lockable_{lockable}, runnable_{runnable} {}
-
- void operator()() const {
- ThreadLockHolder thread_lock(lockable_);
- runnable_();
- }
-
- private:
- Lockable const *lockable_;
- Runnable runnable_;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_THREAD_CHECK_RUNNABLE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/webrtc.h b/chromium/third_party/nearby/src/cpp/platform/public/webrtc.h
deleted file mode 100644
index 56b497ed93f..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/webrtc.h
+++ /dev/null
@@ -1,99 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_WEBRTC_H_
-#define PLATFORM_PUBLIC_WEBRTC_H_
-
-#include <memory>
-
-#include "platform/api/platform.h"
-#include "platform/api/webrtc.h"
-#include "webrtc/api/peer_connection_interface.h"
-
-namespace location {
-namespace nearby {
-
-class WebRtcSignalingMessenger final {
- public:
- using OnSignalingMessageCallback =
- api::WebRtcSignalingMessenger::OnSignalingMessageCallback;
- using OnSignalingCompleteCallback =
- api::WebRtcSignalingMessenger::OnSignalingCompleteCallback;
-
- explicit WebRtcSignalingMessenger(
- std::unique_ptr<api::WebRtcSignalingMessenger> messenger)
- : impl_(std::move(messenger)) {}
- ~WebRtcSignalingMessenger() = default;
- WebRtcSignalingMessenger(WebRtcSignalingMessenger&&) = default;
- WebRtcSignalingMessenger operator=(WebRtcSignalingMessenger&&) = delete;
-
- bool SendMessage(absl::string_view peer_id, const ByteArray& message) {
- return impl_->SendMessage(peer_id, message);
- }
-
- bool StartReceivingMessages(
- OnSignalingMessageCallback on_message_callback,
- OnSignalingCompleteCallback on_complete_callback) {
- return impl_->StartReceivingMessages(on_message_callback,
- on_complete_callback);
- }
-
- void StopReceivingMessages() { impl_->StopReceivingMessages(); }
-
- bool IsValid() const { return impl_ != nullptr; }
-
- private:
- std::unique_ptr<api::WebRtcSignalingMessenger> impl_;
-};
-
-class WebRtcMedium final {
- public:
- using PeerConnectionCallback = api::WebRtcMedium::PeerConnectionCallback;
-
- WebRtcMedium() : impl_(api::ImplementationPlatform::CreateWebRtcMedium()) {}
- ~WebRtcMedium() = default;
- WebRtcMedium(WebRtcMedium&&) = delete;
- WebRtcMedium& operator=(WebRtcMedium&&) = delete;
-
- // Gets the default two-letter country code associated with current locale.
- // For example, en_US locale resolves to "US".
- const std::string GetDefaultCountryCode() {
- return impl_->GetDefaultCountryCode();
- }
-
- // Creates and returns a new webrtc::PeerConnectionInterface object via
- // |callback|.
- void CreatePeerConnection(webrtc::PeerConnectionObserver* observer,
- PeerConnectionCallback callback) {
- impl_->CreatePeerConnection(observer, std::move(callback));
- }
-
- // Returns a signaling messenger for sending WebRTC signaling messages.
- std::unique_ptr<WebRtcSignalingMessenger> GetSignalingMessenger(
- absl::string_view self_id,
- const connections::LocationHint& location_hint) {
- return std::make_unique<WebRtcSignalingMessenger>(
- impl_->GetSignalingMessenger(self_id, location_hint));
- }
-
- bool IsValid() const { return impl_ != nullptr; }
-
- private:
- std::unique_ptr<api::WebRtcMedium> impl_;
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_WEBRTC_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/wifi_lan.cc b/chromium/third_party/nearby/src/cpp/platform/public/wifi_lan.cc
deleted file mode 100644
index fd2d0336d4b..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/wifi_lan.cc
+++ /dev/null
@@ -1,146 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/public/wifi_lan.h"
-
-#include "platform/public/mutex_lock.h"
-
-namespace location {
-namespace nearby {
-
-bool WifiLanMedium::StartAdvertising(const NsdServiceInfo& nsd_service_info) {
- return impl_->StartAdvertising(nsd_service_info);
-}
-
-bool WifiLanMedium::StopAdvertising(const NsdServiceInfo& nsd_service_info) {
- return impl_->StopAdvertising(nsd_service_info);
-}
-
-bool WifiLanMedium::StartDiscovery(const std::string& service_id,
- const std::string& service_type,
- DiscoveredServiceCallback callback) {
- {
- MutexLock lock(&mutex_);
- if (discovery_callbacks_.contains(service_type)) {
- NEARBY_LOGS(INFO) << "WifiLan Discovery already start with service_type="
- << service_type << "; impl=" << &GetImpl();
- return false;
- }
- }
- api::WifiLanMedium::DiscoveredServiceCallback api_callback = {
- .service_discovered_cb =
- [this](NsdServiceInfo service_info) {
- MutexLock lock(&mutex_);
- std::string service_type = service_info.GetServiceType();
- auto pair = discovery_services_.insert(service_type);
- if (!pair.second) {
- NEARBY_LOGS(INFO)
- << "Discovering (again) service_info=" << &service_info
- << ", service_type=" << service_type
- << ", service_name=" << service_info.GetServiceName();
- return;
- }
- NEARBY_LOGS(INFO)
- << "Adding service_info=" << &service_info
- << ", service_type=" << service_type
- << ", service_name=" << service_info.GetServiceName();
- // Callback service found.
- const auto& it = discovery_callbacks_.find(service_type);
- if (it != discovery_callbacks_.end()) {
- std::string service_id = it->second->service_id;
- DiscoveredServiceCallback medium_callback =
- it->second->medium_callback;
- medium_callback.service_discovered_cb(service_info, service_id);
- } else {
- NEARBY_LOGS(ERROR)
- << "There is no callback found for service_type="
- << service_type;
- }
- },
- .service_lost_cb =
- [this](NsdServiceInfo service_info) {
- MutexLock lock(&mutex_);
- std::string service_type = service_info.GetServiceType();
- auto item = discovery_services_.extract(service_type);
- if (item.empty()) return;
- NEARBY_LOGS(INFO)
- << "Removing service_info=" << &service_info
- << ", service_type=" << service_type
- << ", service_info_name=" << service_info.GetServiceName();
- // Callback service lost.
- const auto& it = discovery_callbacks_.find(service_type);
- if (it != discovery_callbacks_.end()) {
- std::string service_id = it->second->service_id;
- DiscoveredServiceCallback medium_callback =
- it->second->medium_callback;
- medium_callback.service_lost_cb(service_info, service_id);
- }
- },
- };
- {
- // Insert callback to the map first no matter it succeeds or not.
- MutexLock lock(&mutex_);
- auto pair = discovery_callbacks_.insert(
- {service_type, absl::make_unique<DiscoveryCallbackInfo>()});
- auto& context = *pair.first->second;
- context.medium_callback = std::move(callback);
- context.service_id = service_id;
- }
-
- bool success = impl_->StartDiscovery(service_type, std::move(api_callback));
- if (!success) {
- // If failed, then revert back the insertion.
- MutexLock lock(&mutex_);
- discovery_callbacks_.erase(service_type);
- }
- NEARBY_LOGS(INFO) << "WifiLan Discovery started for service_type="
- << service_type << ", impl=" << &GetImpl()
- << ", success=" << success;
- return success;
-}
-
-bool WifiLanMedium::StopDiscovery(const std::string& service_type) {
- MutexLock lock(&mutex_);
- if (!discovery_callbacks_.contains(service_type)) {
- return false;
- }
- discovery_callbacks_.erase(service_type);
- if (discovery_services_.contains(service_type)) {
- discovery_services_.erase(service_type);
- }
- NEARBY_LOGS(INFO) << "WifiLan Discovery disabled for service_type="
- << service_type << ", impl=" << &GetImpl();
- return impl_->StopDiscovery(service_type);
-}
-
-WifiLanSocket WifiLanMedium::ConnectToService(
- const NsdServiceInfo& remote_service_info,
- CancellationFlag* cancellation_flag) {
- NEARBY_LOGS(INFO) << "WifiLanMedium::ConnectToService: remote_service_name="
- << remote_service_info.GetServiceName();
- return WifiLanSocket(
- impl_->ConnectToService(remote_service_info, cancellation_flag));
-}
-
-WifiLanSocket WifiLanMedium::ConnectToService(
- const std::string& ip_address, int port,
- CancellationFlag* cancellation_flag) {
- NEARBY_LOGS(INFO) << "WifiLanMedium::ConnectToService: ip address="
- << ip_address << ", port=" << port;
- return WifiLanSocket(
- impl_->ConnectToService(ip_address, port, cancellation_flag));
-}
-
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/wifi_lan.h b/chromium/third_party/nearby/src/cpp/platform/public/wifi_lan.h
deleted file mode 100644
index 9bf5092613b..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/wifi_lan.h
+++ /dev/null
@@ -1,205 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef PLATFORM_PUBLIC_WIFI_LAN_H_
-#define PLATFORM_PUBLIC_WIFI_LAN_H_
-
-#include "absl/container/flat_hash_map.h"
-#include "platform/api/platform.h"
-#include "platform/api/wifi_lan.h"
-#include "platform/base/byte_array.h"
-#include "platform/base/cancellation_flag.h"
-#include "platform/base/input_stream.h"
-#include "platform/base/nsd_service_info.h"
-#include "platform/base/output_stream.h"
-#include "platform/public/logging.h"
-#include "platform/public/mutex.h"
-
-namespace location {
-namespace nearby {
-
-class WifiLanSocket final {
- public:
- WifiLanSocket() = default;
- WifiLanSocket(const WifiLanSocket&) = default;
- WifiLanSocket& operator=(const WifiLanSocket&) = default;
- ~WifiLanSocket() = default;
- explicit WifiLanSocket(std::unique_ptr<api::WifiLanSocket> socket)
- : impl_(std::move(socket)) {}
-
- // Returns the InputStream of the WifiLanSocket.
- // On error, returned stream will report Exception::kIo on any operation.
- //
- // The returned object is not owned by the caller, and can be invalidated once
- // the WifiLanSocket object is destroyed.
- InputStream& GetInputStream() { return impl_->GetInputStream(); }
-
- // Returns the OutputStream of the WifiLanSocket.
- // On error, returned stream will report Exception::kIo on any operation.
- //
- // The returned object is not owned by the caller, and can be invalidated once
- // the WifiLanSocket object is destroyed.
- OutputStream& GetOutputStream() { return impl_->GetOutputStream(); }
-
- // Returns Exception::kIo on error, Exception::kSuccess otherwise.
- Exception Close() { return impl_->Close(); }
-
- // Returns true if a socket is usable. If this method returns false,
- // it is not safe to call any other method.
- // NOTE(socket validity):
- // Socket created by a default public constructor is not valid, because
- // it is missing platform implementation.
- // The only way to obtain a valid socket is through connection, such as
- // an object returned by WifiLanMedium::Connect
- // These methods may also return an invalid socket if connection failed for
- // any reason.
- bool IsValid() const { return impl_ != nullptr; }
-
- // Returns reference to platform implementation.
- // This is used to communicate with platform code, and for debugging purposes.
- // Returned reference will remain valid for while WifiLanSocket object is
- // itself valid. Typically WifiLanSocket lifetime matches duration of the
- // connection, and is controlled by end user, since they hold the instance.
- api::WifiLanSocket& GetImpl() { return *impl_; }
-
- private:
- std::shared_ptr<api::WifiLanSocket> impl_;
-};
-
-class WifiLanServerSocket final {
- public:
- WifiLanServerSocket() = default;
- WifiLanServerSocket(const WifiLanServerSocket&) = default;
- WifiLanServerSocket& operator=(const WifiLanServerSocket&) = default;
- ~WifiLanServerSocket() = default;
- explicit WifiLanServerSocket(std::unique_ptr<api::WifiLanServerSocket> socket)
- : impl_(std::move(socket)) {}
-
- // Returns ip address.
- std::string GetIPAddress() { return impl_->GetIPAddress(); }
-
- // Returns port.
- int GetPort() { return impl_->GetPort(); }
-
- // Blocks until either:
- // - at least one incoming connection request is available, or
- // - ServerSocket is closed.
- // On success, returns connected socket, ready to exchange data.
- // Returns nullptr on error.
- // Once error is reported, it is permanent, and ServerSocket has to be closed.
- WifiLanSocket Accept() {
- std::unique_ptr<api::WifiLanSocket> socket = impl_->Accept();
- if (!socket) {
- NEARBY_LOGS(INFO)
- << "WifiLanServerSocket Accept() failed on server socket: " << this;
- }
- return WifiLanSocket(std::move(socket));
- }
-
- // Returns Exception::kIo on error, Exception::kSuccess otherwise.
- Exception Close() {
- NEARBY_LOGS(INFO) << "WifiLanServerSocket Closing:: " << this;
- return impl_->Close();
- }
-
- bool IsValid() const { return impl_ != nullptr; }
- api::WifiLanServerSocket& GetImpl() { return *impl_; }
-
- private:
- std::shared_ptr<api::WifiLanServerSocket> impl_;
-};
-
-// Container of operations that can be performed over the WifiLan medium.
-class WifiLanMedium {
- public:
- using Platform = api::ImplementationPlatform;
-
- struct DiscoveredServiceCallback {
- std::function<void(NsdServiceInfo service_info,
- const std::string& service_type)>
- service_discovered_cb =
- DefaultCallback<NsdServiceInfo, const std::string&>();
- std::function<void(NsdServiceInfo service_info,
- const std::string& service_type)>
- service_lost_cb = DefaultCallback<NsdServiceInfo, const std::string&>();
- };
-
- struct DiscoveryCallbackInfo {
- std::string service_id;
- DiscoveredServiceCallback medium_callback;
- };
-
- WifiLanMedium() : impl_(Platform::CreateWifiLanMedium()) {}
- ~WifiLanMedium() = default;
-
- // Starts WifiLan advertising.
- //
- // nsd_service_info - NsdServiceInfo data that's advertised through mDNS
- // service.
- // On success if the service is now advertising.
- // On error if the service cannot start to advertise or the nsd_type in
- // NsdServiceInfo has been passed previously which StopAdvertising is not
- // been called.
- bool StartAdvertising(const NsdServiceInfo& nsd_service_info);
-
- // Stops WifiLan advertising.
- //
- // nsd_service_info - NsdServiceInfo data that's advertised through mDNS
- // service.
- // On success if the service stops advertising.
- // On error if the service cannot stop advertising or the nsd_type in
- // NsdServiceInfo cannot be found.
- bool StopAdvertising(const NsdServiceInfo& nsd_service_info);
-
- // Returns true once the WifiLan discovery has been initiated.
- bool StartDiscovery(const std::string& service_id,
- const std::string& service_type,
- DiscoveredServiceCallback callback);
-
- // Returns true once service_type is associated to existing callback. If the
- // callback is the last found then WifiLan discovery will be stopped.
- bool StopDiscovery(const std::string& service_type);
-
- // Returns a new WifiLanSocket.
- // On Success, WifiLanSocket::IsValid() returns true.
- WifiLanSocket ConnectToService(const NsdServiceInfo& remote_service_info,
- CancellationFlag* cancellation_flag);
-
- // Returns a new WifiLanSocket by ip address and port.
- // On Success, WifiLanSocket::IsValid()returns true.
- WifiLanSocket ConnectToService(const std::string& ip_address, int port,
- CancellationFlag* cancellation_flag);
-
- // Returns a new WifiLanServerSocket.
- // On Success, WifiLanServerSocket::IsValid() returns true.
- WifiLanServerSocket ListenForService(int port = 0) {
- return WifiLanServerSocket(impl_->ListenForService(port));
- }
-
- bool IsValid() const { return impl_ != nullptr; }
-
- api::WifiLanMedium& GetImpl() { return *impl_; }
-
- private:
- Mutex mutex_;
- std::unique_ptr<api::WifiLanMedium> impl_;
- absl::flat_hash_map<std::string, std::unique_ptr<DiscoveryCallbackInfo>>
- discovery_callbacks_ ABSL_GUARDED_BY(mutex_);
- absl::flat_hash_set<std::string> discovery_services_ ABSL_GUARDED_BY(mutex_);
-};
-
-} // namespace nearby
-} // namespace location
-
-#endif // PLATFORM_PUBLIC_WIFI_LAN_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/wifi_lan_test.cc b/chromium/third_party/nearby/src/cpp/platform/public/wifi_lan_test.cc
deleted file mode 100644
index 93eb0a54184..00000000000
--- a/chromium/third_party/nearby/src/cpp/platform/public/wifi_lan_test.cc
+++ /dev/null
@@ -1,390 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "platform/public/wifi_lan.h"
-
-#include <memory>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/strings/string_view.h"
-#include "platform/base/medium_environment.h"
-#include "platform/public/count_down_latch.h"
-#include "platform/public/logging.h"
-
-namespace location {
-namespace nearby {
-namespace {
-
-using FeatureFlags = FeatureFlags::Flags;
-
-constexpr FeatureFlags kTestCases[] = {
- FeatureFlags{
- .enable_cancellation_flag = true,
- },
- FeatureFlags{
- .enable_cancellation_flag = false,
- },
-};
-
-constexpr absl::Duration kWaitDuration = absl::Milliseconds(1000);
-constexpr absl::string_view kServiceId{"service_id"};
-constexpr absl::string_view kServiceType{"_service.tcp_"};
-constexpr absl::string_view kServiceInfoName{"Simulated service info name"};
-constexpr absl::string_view kEndpointName{"Simulated endpoint name"};
-constexpr absl::string_view kEndpointInfoKey{"n"};
-
-class WifiLanMediumTest : public ::testing::TestWithParam<FeatureFlags> {
- protected:
- using DiscoveredServiceCallback = WifiLanMedium::DiscoveredServiceCallback;
-
- WifiLanMediumTest() { env_.Stop(); }
-
- MediumEnvironment& env_{MediumEnvironment::Instance()};
-};
-
-TEST_P(WifiLanMediumTest, CanConnectToService) {
- FeatureFlags feature_flags = GetParam();
- env_.SetFeatureFlags(feature_flags);
- env_.Start();
- WifiLanMedium wifi_lan_a;
- WifiLanMedium wifi_lan_b;
- std::string service_id(kServiceId);
- std::string service_type(kServiceType);
- std::string service_info_name(kServiceInfoName);
- std::string endpoint_info_name(kEndpointName);
- CountDownLatch discovered_latch(1);
- CountDownLatch lost_latch(1);
-
- WifiLanServerSocket server_socket = wifi_lan_b.ListenForService();
- EXPECT_TRUE(server_socket.IsValid());
-
- NsdServiceInfo nsd_service_info;
- nsd_service_info.SetServiceName(service_info_name);
- nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
- endpoint_info_name);
- nsd_service_info.SetServiceType(service_type);
- nsd_service_info.SetIPAddress(server_socket.GetIPAddress());
- nsd_service_info.SetPort(server_socket.GetPort());
- wifi_lan_b.StartAdvertising(nsd_service_info);
-
- NsdServiceInfo discovered_service_info;
- wifi_lan_a.StartDiscovery(
- service_id, service_type,
- DiscoveredServiceCallback{
- .service_discovered_cb =
- [&discovered_latch, &discovered_service_info](
- NsdServiceInfo service_info,
- const std::string& service_type) {
- discovered_service_info = service_info;
- discovered_latch.CountDown();
- },
- .service_lost_cb =
- [&lost_latch](NsdServiceInfo service_info,
- const std::string& service_type) {
- lost_latch.CountDown();
- },
- });
- EXPECT_TRUE(discovered_latch.Await(absl::Milliseconds(1000)).result());
- WifiLanSocket socket_a;
- WifiLanSocket socket_b;
- EXPECT_FALSE(socket_a.IsValid());
- EXPECT_FALSE(socket_b.IsValid());
- {
- CancellationFlag flag;
- SingleThreadExecutor server_executor;
- SingleThreadExecutor client_executor;
- client_executor.Execute([&wifi_lan_a, &socket_a,
- discovered_service_info = discovered_service_info,
- service_type, &server_socket, &flag]() {
- socket_a = wifi_lan_a.ConnectToService(discovered_service_info, &flag);
- if (!socket_a.IsValid()) {
- server_socket.Close();
- }
- });
- server_executor.Execute([&socket_b, &server_socket]() {
- socket_b = server_socket.Accept();
- if (!socket_b.IsValid()) {
- server_socket.Close();
- }
- });
- }
- EXPECT_TRUE(socket_a.IsValid());
- EXPECT_TRUE(socket_b.IsValid());
- server_socket.Close();
- env_.Stop();
-}
-
-TEST_P(WifiLanMediumTest, CanCancelConnect) {
- FeatureFlags feature_flags = GetParam();
- env_.SetFeatureFlags(feature_flags);
- env_.Start();
- WifiLanMedium wifi_lan_a;
- WifiLanMedium wifi_lan_b;
- std::string service_id(kServiceId);
- std::string service_type(kServiceType);
- std::string service_info_name(kServiceInfoName);
- std::string endpoint_info_name(kEndpointName);
- CountDownLatch discovered_latch(1);
- CountDownLatch lost_latch(1);
-
- WifiLanServerSocket server_socket = wifi_lan_b.ListenForService();
- EXPECT_TRUE(server_socket.IsValid());
-
- NsdServiceInfo nsd_service_info;
- nsd_service_info.SetServiceName(service_info_name);
- nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
- endpoint_info_name);
- nsd_service_info.SetServiceType(service_type);
- nsd_service_info.SetIPAddress(server_socket.GetIPAddress());
- nsd_service_info.SetPort(server_socket.GetPort());
- wifi_lan_b.StartAdvertising(nsd_service_info);
-
- NsdServiceInfo discovered_service_info;
- wifi_lan_a.StartDiscovery(
- service_id, service_type,
- DiscoveredServiceCallback{
- .service_discovered_cb =
- [&discovered_latch, &discovered_service_info](
- NsdServiceInfo service_info,
- const std::string& service_type) {
- discovered_service_info = service_info;
- discovered_latch.CountDown();
- },
- .service_lost_cb =
- [&lost_latch](NsdServiceInfo service_info,
- const std::string& service_type) {
- lost_latch.CountDown();
- },
- });
- EXPECT_TRUE(discovered_latch.Await(absl::Milliseconds(1000)).result());
- WifiLanSocket socket_a;
- WifiLanSocket socket_b;
- EXPECT_FALSE(socket_a.IsValid());
- EXPECT_FALSE(socket_b.IsValid());
- {
- CancellationFlag flag(true);
- SingleThreadExecutor server_executor;
- SingleThreadExecutor client_executor;
- client_executor.Execute([&wifi_lan_a, &socket_a,
- discovered_service_info = discovered_service_info,
- service_type, &server_socket, &flag]() {
- socket_a = wifi_lan_a.ConnectToService(discovered_service_info, &flag);
- if (!socket_a.IsValid()) {
- server_socket.Close();
- }
- });
- server_executor.Execute([&socket_b, &server_socket]() {
- socket_b = server_socket.Accept();
- if (!socket_b.IsValid()) {
- server_socket.Close();
- }
- });
- }
- // If FeatureFlag is disabled, Cancelled is false as no-op.
- if (!feature_flags.enable_cancellation_flag) {
- EXPECT_TRUE(socket_a.IsValid());
- EXPECT_TRUE(socket_b.IsValid());
- } else {
- EXPECT_FALSE(socket_a.IsValid());
- EXPECT_FALSE(socket_b.IsValid());
- }
- server_socket.Close();
- env_.Stop();
-}
-
-INSTANTIATE_TEST_SUITE_P(ParametrisedWifiLanMediumTest, WifiLanMediumTest,
- ::testing::ValuesIn(kTestCases));
-
-TEST_F(WifiLanMediumTest, ConstructorDestructorWorks) {
- env_.Start();
- WifiLanMedium wifi_lan_a;
- WifiLanMedium wifi_lan_b;
-
- // Make sure we can create functional mediums.
- ASSERT_TRUE(wifi_lan_a.IsValid());
- ASSERT_TRUE(wifi_lan_b.IsValid());
-
- // Make sure we can create 2 distinct mediums.
- EXPECT_NE(&wifi_lan_a.GetImpl(), &wifi_lan_b.GetImpl());
- env_.Stop();
-}
-
-TEST_F(WifiLanMediumTest, CanStartAdvertising) {
- env_.Start();
- WifiLanMedium wifi_lan_a;
- std::string service_type(kServiceType);
- std::string service_info_name(kServiceInfoName);
- std::string endpoint_info_name(kEndpointName);
-
- WifiLanServerSocket server_socket = wifi_lan_a.ListenForService();
- EXPECT_TRUE(server_socket.IsValid());
-
- NsdServiceInfo nsd_service_info;
- nsd_service_info.SetServiceName(service_info_name);
- nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
- endpoint_info_name);
- nsd_service_info.SetServiceType(service_type);
- EXPECT_TRUE(wifi_lan_a.StartAdvertising(nsd_service_info));
- EXPECT_TRUE(wifi_lan_a.StopAdvertising(nsd_service_info));
- env_.Stop();
-}
-
-TEST_F(WifiLanMediumTest, CanStartMultipleAdvertising) {
- env_.Start();
- WifiLanMedium wifi_lan_a;
- std::string service_type_1(kServiceType);
- std::string service_type_2("_service_1.tcp_");
- std::string service_info_name_1(kServiceInfoName);
- std::string service_info_name_2(kServiceInfoName);
- std::string endpoint_info_name(kEndpointName);
-
- WifiLanServerSocket server_socket = wifi_lan_a.ListenForService();
- EXPECT_TRUE(server_socket.IsValid());
-
- NsdServiceInfo nsd_service_info_1;
- nsd_service_info_1.SetServiceName(service_info_name_1);
- nsd_service_info_1.SetTxtRecord(std::string(kEndpointInfoKey),
- endpoint_info_name);
- nsd_service_info_1.SetServiceType(service_type_1);
-
- NsdServiceInfo nsd_service_info_2;
- nsd_service_info_2.SetServiceName(service_info_name_2);
- nsd_service_info_2.SetTxtRecord(std::string(kEndpointInfoKey),
- endpoint_info_name);
- nsd_service_info_2.SetServiceType(service_type_2);
-
- EXPECT_TRUE(wifi_lan_a.StartAdvertising(nsd_service_info_1));
- EXPECT_TRUE(wifi_lan_a.StartAdvertising(nsd_service_info_2));
- EXPECT_TRUE(wifi_lan_a.StopAdvertising(nsd_service_info_1));
- EXPECT_TRUE(wifi_lan_a.StopAdvertising(nsd_service_info_2));
- env_.Stop();
-}
-
-TEST_F(WifiLanMediumTest, CanStartDiscovery) {
- env_.Start();
- WifiLanMedium wifi_lan_a;
- std::string service_id(kServiceId);
- std::string service_type(kServiceType);
-
- EXPECT_TRUE(wifi_lan_a.StartDiscovery(service_id, service_type,
- DiscoveredServiceCallback{}));
- EXPECT_TRUE(wifi_lan_a.StopDiscovery(service_type));
- env_.Stop();
-}
-
-TEST_F(WifiLanMediumTest, CanStartMultipleDiscovery) {
- env_.Start();
- WifiLanMedium wifi_lan_a;
- std::string service_id_1(kServiceId);
- std::string service_id_2("service_id_2");
- std::string service_type_1(kServiceType);
- std::string service_type_2("_service_1.tcp_");
-
- EXPECT_TRUE(wifi_lan_a.StartDiscovery(service_id_1, service_type_1,
- DiscoveredServiceCallback{}));
- EXPECT_TRUE(wifi_lan_a.StartDiscovery(service_id_2, service_type_2,
- DiscoveredServiceCallback{}));
- EXPECT_TRUE(wifi_lan_a.StopDiscovery(service_type_1));
- EXPECT_TRUE(wifi_lan_a.StopDiscovery(service_type_2));
- env_.Stop();
-}
-
-TEST_F(WifiLanMediumTest, CanAdvertiseThatOtherMediumDiscover) {
- env_.Start();
- WifiLanMedium wifi_lan_a;
- WifiLanMedium wifi_lan_b;
- std::string service_id(kServiceId);
- std::string service_type(kServiceType);
- std::string service_info_name(kServiceInfoName);
- std::string endpoint_info_name(kEndpointName);
- CountDownLatch discovered_latch(1);
- CountDownLatch lost_latch(1);
-
- wifi_lan_b.StartDiscovery(
- service_id, service_type,
- DiscoveredServiceCallback{
- .service_discovered_cb =
- [&discovered_latch](NsdServiceInfo service_info,
- const std::string& service_type) {
- discovered_latch.CountDown();
- },
- .service_lost_cb =
- [&lost_latch](NsdServiceInfo service_info,
- const std::string& service_id) {
- lost_latch.CountDown();
- },
- });
-
- WifiLanServerSocket server_socket = wifi_lan_a.ListenForService();
- EXPECT_TRUE(server_socket.IsValid());
-
- NsdServiceInfo nsd_service_info;
- nsd_service_info.SetServiceName(service_info_name);
- nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
- endpoint_info_name);
- nsd_service_info.SetServiceType(service_type);
- EXPECT_TRUE(wifi_lan_a.StartAdvertising(nsd_service_info));
- EXPECT_TRUE(discovered_latch.Await(kWaitDuration).result());
- EXPECT_TRUE(wifi_lan_a.StopAdvertising(nsd_service_info));
- EXPECT_TRUE(lost_latch.Await(kWaitDuration).result());
- EXPECT_TRUE(wifi_lan_b.StopDiscovery(service_type));
- env_.Stop();
-}
-
-TEST_F(WifiLanMediumTest, CanDiscoverThatOtherMediumAdvertise) {
- env_.Start();
- WifiLanMedium wifi_lan_a;
- WifiLanMedium wifi_lan_b;
- std::string service_id(kServiceId);
- std::string service_type(kServiceType);
- std::string service_info_name(kServiceInfoName);
- std::string endpoint_info_name(kEndpointName);
- CountDownLatch discovered_latch(1);
- CountDownLatch lost_latch(1);
-
- wifi_lan_a.StartDiscovery(
- service_id, service_type,
- DiscoveredServiceCallback{
- .service_discovered_cb =
- [&discovered_latch](NsdServiceInfo service_info,
- const std::string& service_type) {
- discovered_latch.CountDown();
- },
- .service_lost_cb =
- [&lost_latch](NsdServiceInfo service_info,
- const std::string& service_type) {
- lost_latch.CountDown();
- },
- });
-
- WifiLanServerSocket server_socket = wifi_lan_a.ListenForService();
- EXPECT_TRUE(server_socket.IsValid());
-
- NsdServiceInfo nsd_service_info;
- nsd_service_info.SetServiceName(service_info_name);
- nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
- endpoint_info_name);
- nsd_service_info.SetServiceType(service_type);
- EXPECT_TRUE(wifi_lan_b.StartAdvertising(nsd_service_info));
- EXPECT_TRUE(discovered_latch.Await(kWaitDuration).result());
- EXPECT_TRUE(wifi_lan_b.StopAdvertising(nsd_service_info));
- EXPECT_TRUE(lost_latch.Await(kWaitDuration).result());
- EXPECT_TRUE(wifi_lan_a.StopDiscovery(service_type));
- env_.Stop();
-}
-
-} // namespace
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/docs/ios_build.md b/chromium/third_party/nearby/src/docs/ios_build.md
new file mode 100644
index 00000000000..cd064e8c5e2
--- /dev/null
+++ b/chromium/third_party/nearby/src/docs/ios_build.md
@@ -0,0 +1,3 @@
+# Building Nearby on IOS
+
+We do not yet support build from source. Instead a prebuilt library is provided. See [this link](https://github.com/google/nearby/tree/master/cpp/platform/impl/ios/Example/NearbyConnectionsExample/README.md) for a sample app using the prebuilt library.
diff --git a/chromium/third_party/nearby/src/internal/analytics/BUILD b/chromium/third_party/nearby/src/internal/analytics/BUILD
new file mode 100644
index 00000000000..9e64355eee0
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/analytics/BUILD
@@ -0,0 +1,43 @@
+licenses(["notice"])
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+cc_library(
+ name = "analytics",
+ srcs = [
+ "analytics_recorder.cc",
+ ],
+ hdrs = [
+ "analytics_recorder.h",
+ "connection_attempt_metadata_params.h",
+ ],
+ copts = ["-DCORE_ADAPTER_DLL"],
+ visibility = [
+ "//connections:__subpackages__",
+ "//internal/proto/analytics:__subpackages__",
+ ],
+ deps = [
+ "//connections:core_types",
+ "//connections:event_logger",
+ "//internal/platform:base",
+ "//internal/platform:error_code_recorder",
+ "//internal/platform:logging",
+ "//internal/platform:types",
+ "//internal/proto/analytics:connections_log_cc_proto",
+ "//proto:connections_enums_cc_proto",
+ "//proto/errorcode:error_code_enums_cc_proto",
+ "@com_google_absl//absl/container:btree",
+ "@com_google_absl//absl/time",
+ ],
+)
diff --git a/chromium/third_party/nearby/src/internal/analytics/analytics_recorder.cc b/chromium/third_party/nearby/src/internal/analytics/analytics_recorder.cc
new file mode 100644
index 00000000000..a7ad8830a31
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/analytics/analytics_recorder.cc
@@ -0,0 +1,1220 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/analytics/analytics_recorder.h"
+
+#include <string>
+#include <utility>
+
+#include "absl/time/time.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/mutex_lock.h"
+#include "internal/platform/system_clock.h"
+#include "internal/proto/analytics/connections_log.pb.h"
+#include "proto/connections_enums.pb.h"
+
+namespace location {
+namespace nearby {
+namespace analytics {
+
+namespace {
+const char kVersion[] = "v1.0.0";
+} // namespace
+
+using ::location::nearby::analytics::proto::ConnectionsLog;
+using ::location::nearby::proto::connections::ACCEPTED;
+using ::location::nearby::proto::connections::ADVERTISER;
+using ::location::nearby::proto::connections::BandwidthUpgradeErrorStage;
+using ::location::nearby::proto::connections::BandwidthUpgradeResult;
+using ::location::nearby::proto::connections::BYTES;
+using ::location::nearby::proto::connections::CLIENT_SESSION;
+using ::location::nearby::proto::connections::CONNECTION_CLOSED;
+using ::location::nearby::proto::connections::ConnectionAttemptDirection;
+using ::location::nearby::proto::connections::ConnectionAttemptResult;
+using ::location::nearby::proto::connections::ConnectionAttemptType;
+using ::location::nearby::proto::connections::ConnectionBand;
+using ::location::nearby::proto::connections::ConnectionRequestResponse;
+using ::location::nearby::proto::connections::ConnectionsStrategy;
+using ::location::nearby::proto::connections::ConnectionTechnology;
+using ::location::nearby::proto::connections::DisconnectionReason;
+using ::location::nearby::proto::connections::DISCOVERER;
+using ::location::nearby::proto::connections::ERROR_CODE;
+using ::location::nearby::proto::connections::EventType;
+using ::location::nearby::proto::connections::FILE;
+using ::location::nearby::proto::connections::IGNORED;
+using ::location::nearby::proto::connections::INCOMING;
+using ::location::nearby::proto::connections::INITIAL;
+using ::location::nearby::proto::connections::Medium;
+using ::location::nearby::proto::connections::MOVED_TO_NEW_MEDIUM;
+using ::location::nearby::proto::connections::NOT_SENT;
+using ::location::nearby::proto::connections::OUTGOING;
+using ::location::nearby::proto::connections::P2P_CLUSTER;
+using ::location::nearby::proto::connections::P2P_POINT_TO_POINT;
+using ::location::nearby::proto::connections::P2P_STAR;
+using ::location::nearby::proto::connections::PayloadStatus;
+using ::location::nearby::proto::connections::PayloadType;
+using ::location::nearby::proto::connections::REJECTED;
+using ::location::nearby::proto::connections::RESULT_SUCCESS;
+using ::location::nearby::proto::connections::SessionRole;
+using ::location::nearby::proto::connections::START_CLIENT_SESSION;
+using ::location::nearby::proto::connections::START_STRATEGY_SESSION;
+using ::location::nearby::proto::connections::STOP_CLIENT_SESSION;
+using ::location::nearby::proto::connections::STOP_STRATEGY_SESSION;
+using ::location::nearby::proto::connections::STREAM;
+using ::location::nearby::proto::connections::UNFINISHED;
+using ::location::nearby::proto::connections::UNFINISHED_ERROR;
+using ::location::nearby::proto::connections::UNKNOWN_MEDIUM;
+using ::location::nearby::proto::connections::UNKNOWN_PAYLOAD_TYPE;
+using ::location::nearby::proto::connections::UNKNOWN_STRATEGY;
+using ::location::nearby::proto::connections::UPGRADE_RESULT_SUCCESS;
+using ::location::nearby::proto::connections::UPGRADE_SUCCESS;
+using ::location::nearby::proto::connections::UPGRADE_UNFINISHED;
+using ::location::nearby::proto::connections::UPGRADED;
+
+AnalyticsRecorder::AnalyticsRecorder(EventLogger *event_logger)
+ : event_logger_(event_logger) {
+ started_client_session_time_ = SystemClock::ElapsedRealtime();
+ NEARBY_LOGS(INFO) << "AnalyticsRecorder ctor event_logger_=" << event_logger_;
+ MutexLock lock(&mutex_);
+ if (CanRecordAnalyticsLocked("OnStartClientSession")) {
+ LogEvent(START_CLIENT_SESSION);
+ }
+}
+
+AnalyticsRecorder::~AnalyticsRecorder() {
+ MutexLock lock(&mutex_);
+ incoming_connection_requests_.clear();
+ outgoing_connection_requests_.clear();
+ active_connections_.clear();
+ bandwidth_upgrade_attempts_.clear();
+ serial_executor_.Shutdown();
+}
+
+void AnalyticsRecorder::OnStartAdvertising(
+ connections::Strategy strategy, const std::vector<Medium> &mediums,
+ bool is_extended_advertisement_supported, int connected_ap_frequency,
+ bool is_nfc_available) {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("OnStartAdvertising")) {
+ return;
+ }
+ if (!strategy.IsValid()) {
+ NEARBY_LOGS(INFO) << "AnalyticsRecorder OnStartAdvertising with unknown "
+ "strategy, bail out.";
+ return;
+ }
+ // Initialize/update a StrategySession.
+ UpdateStrategySessionLocked(strategy, ADVERTISER);
+
+ // Initialize and set a AdvertisingPhase.
+ started_advertising_phase_time_ = SystemClock::ElapsedRealtime();
+ current_advertising_phase_ =
+ absl::make_unique<ConnectionsLog::AdvertisingPhase>();
+ absl::c_copy(mediums, RepeatedFieldBackInserter(
+ current_advertising_phase_->mutable_medium()));
+ // Set a AdvertisingMetadata.
+ auto *advertising_metadata =
+ current_advertising_phase_->mutable_advertising_metadata();
+ advertising_metadata->set_supports_extended_ble_advertisements(
+ is_extended_advertisement_supported);
+ advertising_metadata->set_connected_ap_frequency(connected_ap_frequency);
+ advertising_metadata->set_supports_nfc_technology(is_nfc_available);
+}
+
+void AnalyticsRecorder::OnStopAdvertising() {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("OnStopAdvertising")) {
+ return;
+ }
+ RecordAdvertisingPhaseDurationLocked();
+}
+
+void AnalyticsRecorder::OnStartDiscovery(
+ connections::Strategy strategy, const std::vector<Medium> &mediums,
+ bool is_extended_advertisement_supported, int connected_ap_frequency,
+ bool is_nfc_available) {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("OnStartDiscovery")) {
+ return;
+ }
+ if (!strategy.IsValid()) {
+ NEARBY_LOGS(INFO) << "AnalyticsRecorder OnStartDiscovery unknown "
+ "strategy enter, bail out.";
+ return;
+ }
+
+ // Initialize/update a StrategySession.
+ UpdateStrategySessionLocked(strategy, DISCOVERER);
+
+ // Initialize and set a DiscoveryPhase.
+ started_discovery_phase_time_ = SystemClock::ElapsedRealtime();
+ current_discovery_phase_ =
+ absl::make_unique<ConnectionsLog::DiscoveryPhase>();
+ absl::c_copy(mediums, RepeatedFieldBackInserter(
+ current_discovery_phase_->mutable_medium()));
+ // Set a DiscoveryMetadata.
+ auto *discovery_metadata =
+ current_discovery_phase_->mutable_discovery_metadata();
+ discovery_metadata->set_supports_extended_ble_advertisements(
+ is_extended_advertisement_supported);
+ discovery_metadata->set_connected_ap_frequency(connected_ap_frequency);
+ discovery_metadata->set_supports_nfc_technology(is_nfc_available);
+}
+
+void AnalyticsRecorder::OnStopDiscovery() {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("OnStopDiscovery")) {
+ return;
+ }
+ RecordDiscoveryPhaseDurationLocked();
+}
+
+void AnalyticsRecorder::OnEndpointFound(Medium medium) {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("OnEndpointFound")) {
+ return;
+ }
+ if (current_discovery_phase_ == nullptr) {
+ NEARBY_LOGS(INFO) << "Unable to record discovered endpoint due to null "
+ "current_discovery_phase_";
+ return;
+ }
+ ConnectionsLog::DiscoveredEndpoint *discovered_endpoint =
+ current_discovery_phase_->add_discovered_endpoint();
+ discovered_endpoint->set_medium(medium);
+ discovered_endpoint->set_latency_millis(absl::ToInt64Milliseconds(
+ SystemClock::ElapsedRealtime() - started_discovery_phase_time_));
+}
+
+void AnalyticsRecorder::OnConnectionRequestReceived(
+ const std::string &remote_endpoint_id) {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("OnConnectionRequestReceived")) {
+ return;
+ }
+ absl::Time current_time = SystemClock::ElapsedRealtime();
+ auto connection_request =
+ absl::make_unique<ConnectionsLog::ConnectionRequest>();
+ connection_request->set_duration_millis(absl::ToUnixMillis(current_time));
+ connection_request->set_request_delay_millis(absl::ToInt64Milliseconds(
+ current_time - started_advertising_phase_time_));
+ incoming_connection_requests_.insert(
+ {remote_endpoint_id, std::move(connection_request)});
+}
+
+void AnalyticsRecorder::OnConnectionRequestSent(
+ const std::string &remote_endpoint_id) {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("OnConnectionRequestSent")) {
+ return;
+ }
+ absl::Time current_time = SystemClock::ElapsedRealtime();
+ auto connection_request =
+ absl::make_unique<ConnectionsLog::ConnectionRequest>();
+ connection_request->set_duration_millis(absl::ToUnixMillis(current_time));
+ connection_request->set_request_delay_millis(
+ absl::ToInt64Milliseconds(current_time - started_discovery_phase_time_));
+ outgoing_connection_requests_.insert(
+ {remote_endpoint_id, std::move(connection_request)});
+}
+
+void AnalyticsRecorder::OnRemoteEndpointAccepted(
+ const std::string &remote_endpoint_id) {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("OnRemoteEndpointAccepted")) {
+ return;
+ }
+ RemoteEndpointRespondedLocked(remote_endpoint_id, ACCEPTED);
+}
+
+void AnalyticsRecorder::OnLocalEndpointAccepted(
+ const std::string &remote_endpoint_id) {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("OnLocalEndpointAccepted")) {
+ return;
+ }
+ LocalEndpointRespondedLocked(remote_endpoint_id, ACCEPTED);
+}
+
+void AnalyticsRecorder::OnRemoteEndpointRejected(
+ const std::string &remote_endpoint_id) {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("OnRemoteEndpointRejected")) {
+ return;
+ }
+ RemoteEndpointRespondedLocked(remote_endpoint_id, REJECTED);
+}
+
+void AnalyticsRecorder::OnLocalEndpointRejected(
+ const std::string &remote_endpoint_id) {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("OnLocalEndpointRejected")) {
+ return;
+ }
+ LocalEndpointRespondedLocked(remote_endpoint_id, REJECTED);
+}
+
+void AnalyticsRecorder::OnIncomingConnectionAttempt(
+ ConnectionAttemptType type, Medium medium, ConnectionAttemptResult result,
+ absl::Duration duration, const std::string &connection_token,
+ ConnectionAttemptMetadataParams *connection_attempt_metadata_params) {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("OnIncomingConnectionAttempt")) {
+ return;
+ }
+ if (current_strategy_session_ == nullptr) {
+ NEARBY_LOGS(INFO) << "Unable to record incoming connection attempt due to "
+ "null current_strategy_session_";
+ return;
+ }
+ auto *connection_attempt =
+ current_strategy_session_->add_connection_attempt();
+ connection_attempt->set_duration_millis(absl::ToInt64Milliseconds(duration));
+ connection_attempt->set_type(type);
+ connection_attempt->set_direction(INCOMING);
+ connection_attempt->set_medium(medium);
+ connection_attempt->set_attempt_result(result);
+ connection_attempt->set_connection_token(connection_token);
+
+ ConnectionAttemptMetadataParams default_params = {};
+ if (connection_attempt_metadata_params == nullptr) {
+ connection_attempt_metadata_params = &default_params;
+ }
+ auto *connection_attempt_metadata =
+ connection_attempt->mutable_connection_attempt_metadata();
+ connection_attempt_metadata->set_technology(
+ connection_attempt_metadata_params->technology);
+ connection_attempt_metadata->set_band(
+ connection_attempt_metadata_params->band);
+ connection_attempt_metadata->set_frequency(
+ connection_attempt_metadata_params->frequency);
+ connection_attempt_metadata->set_network_operator(
+ connection_attempt_metadata_params->network_operator);
+ connection_attempt_metadata->set_country_code(
+ connection_attempt_metadata_params->country_code);
+ connection_attempt_metadata->set_frequency(
+ connection_attempt_metadata_params->frequency);
+ connection_attempt_metadata->set_is_tdls_used(
+ connection_attempt_metadata_params->is_tdls_used);
+ connection_attempt_metadata->set_wifi_hotspot_status(
+ connection_attempt_metadata_params->wifi_hotspot_enabled);
+ connection_attempt_metadata->set_try_counts(
+ connection_attempt_metadata_params->try_count);
+ connection_attempt_metadata->set_max_tx_speed(
+ connection_attempt_metadata_params->max_wifi_tx_speed);
+ connection_attempt_metadata->set_max_rx_speed(
+ connection_attempt_metadata_params->max_wifi_rx_speed);
+ connection_attempt_metadata->set_wifi_channel_width(
+ connection_attempt_metadata_params->channel_width);
+}
+
+void AnalyticsRecorder::OnOutgoingConnectionAttempt(
+ const std::string &remote_endpoint_id, ConnectionAttemptType type,
+ Medium medium, ConnectionAttemptResult result, absl::Duration duration,
+ const std::string &connection_token,
+ ConnectionAttemptMetadataParams *connection_attempt_metadata_params) {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("OnOutgoingConnectionAttempt")) {
+ return;
+ }
+ if (current_strategy_session_ == nullptr) {
+ NEARBY_LOGS(INFO) << "Unable to record outgoing connection attempt due to "
+ "null current_strategy_session_";
+ return;
+ }
+ auto *connection_attempt =
+ current_strategy_session_->add_connection_attempt();
+ connection_attempt->set_duration_millis(absl::ToInt64Milliseconds(duration));
+ connection_attempt->set_type(type);
+ connection_attempt->set_direction(OUTGOING);
+ connection_attempt->set_medium(medium);
+ connection_attempt->set_attempt_result(result);
+ connection_attempt->set_connection_token(connection_token);
+
+ ConnectionAttemptMetadataParams default_params = {};
+ if (connection_attempt_metadata_params == nullptr) {
+ connection_attempt_metadata_params = &default_params;
+ }
+ auto *connection_attempt_metadata =
+ connection_attempt->mutable_connection_attempt_metadata();
+ connection_attempt_metadata->set_technology(
+ connection_attempt_metadata_params->technology);
+ connection_attempt_metadata->set_band(
+ connection_attempt_metadata_params->band);
+ connection_attempt_metadata->set_frequency(
+ connection_attempt_metadata_params->frequency);
+ connection_attempt_metadata->set_network_operator(
+ connection_attempt_metadata_params->network_operator);
+ connection_attempt_metadata->set_country_code(
+ connection_attempt_metadata_params->country_code);
+ connection_attempt_metadata->set_frequency(
+ connection_attempt_metadata_params->frequency);
+ connection_attempt_metadata->set_is_tdls_used(
+ connection_attempt_metadata_params->is_tdls_used);
+ connection_attempt_metadata->set_wifi_hotspot_status(
+ connection_attempt_metadata_params->wifi_hotspot_enabled);
+ connection_attempt_metadata->set_try_counts(
+ connection_attempt_metadata_params->try_count);
+ connection_attempt_metadata->set_max_tx_speed(
+ connection_attempt_metadata_params->max_wifi_tx_speed);
+ connection_attempt_metadata->set_max_rx_speed(
+ connection_attempt_metadata_params->max_wifi_rx_speed);
+ connection_attempt_metadata->set_wifi_channel_width(
+ connection_attempt_metadata_params->channel_width);
+
+ if (type == INITIAL && result != RESULT_SUCCESS) {
+ auto it = outgoing_connection_requests_.find(remote_endpoint_id);
+ if (it != outgoing_connection_requests_.end()) {
+ // An outgoing, initial ConnectionAttempt has a corresponding
+ // ConnectionRequest that, since the ConnectionAttempt has failed, will
+ // never be delivered to the advertiser.
+ auto pair = outgoing_connection_requests_.extract(it);
+ std::unique_ptr<ConnectionsLog::ConnectionRequest> &connection_request =
+ pair.mapped();
+ connection_request->set_local_response(NOT_SENT);
+ connection_request->set_remote_response(NOT_SENT);
+ UpdateDiscovererConnectionRequestLocked(connection_request.get());
+ }
+ }
+}
+
+void AnalyticsRecorder::OnConnectionEstablished(
+ const std::string &endpoint_id, Medium medium,
+ const std::string &connection_token) {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("OnConnectionEstablished")) {
+ return;
+ }
+ auto it = active_connections_.find(endpoint_id);
+ if (it != active_connections_.end()) {
+ const std::unique_ptr<LogicalConnection> &logical_connection = it->second;
+ logical_connection->PhysicalConnectionEstablished(medium, connection_token);
+ } else {
+ active_connections_.insert(
+ {endpoint_id,
+ absl::make_unique<LogicalConnection>(medium, connection_token)});
+ }
+}
+
+void AnalyticsRecorder::OnConnectionClosed(const std::string &endpoint_id,
+ Medium medium,
+ DisconnectionReason reason) {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("OnConnectionClosed")) {
+ return;
+ }
+ auto it = active_connections_.find(endpoint_id);
+ if (it == active_connections_.end()) {
+ return;
+ }
+ const std::unique_ptr<LogicalConnection> &logical_connection = it->second;
+ logical_connection->PhysicalConnectionClosed(medium, reason);
+ if (reason != UPGRADED) {
+ // Unless this is an upgraded connection, remove this from our active
+ // connections. Any future communication with an endpoint will need to be
+ // re-established with a new ConnectionRequest.
+ auto pair = active_connections_.extract(it);
+ std::unique_ptr<LogicalConnection> &logical_connection = pair.mapped();
+ absl::c_copy(
+ logical_connection->GetEstablisedConnections(),
+ RepeatedFieldBackInserter(
+ current_strategy_session_->mutable_established_connection()));
+ }
+}
+void AnalyticsRecorder::OnIncomingPayloadStarted(
+ const std::string &endpoint_id, std::int64_t payload_id,
+ connections::Payload::Type type, std::int64_t total_size_bytes) {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("OnIncomingPayloadStarted")) {
+ return;
+ }
+ auto it = active_connections_.find(endpoint_id);
+ if (it == active_connections_.end()) {
+ return;
+ }
+ const std::unique_ptr<LogicalConnection> &logical_connection = it->second;
+ logical_connection->IncomingPayloadStarted(
+ payload_id, PayloadTypeToProtoPayloadType(type), total_size_bytes);
+}
+
+void AnalyticsRecorder::OnPayloadChunkReceived(const std::string &endpoint_id,
+ std::int64_t payload_id,
+ std::int64_t chunk_size_bytes) {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("OnPayloadChunkReceived")) {
+ return;
+ }
+ auto it = active_connections_.find(endpoint_id);
+ if (it == active_connections_.end()) {
+ return;
+ }
+ const std::unique_ptr<LogicalConnection> &logical_connection = it->second;
+ logical_connection->ChunkReceived(payload_id, chunk_size_bytes);
+}
+
+void AnalyticsRecorder::OnIncomingPayloadDone(const std::string &endpoint_id,
+ std::int64_t payload_id,
+ PayloadStatus status) {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("OnIncomingPayloadDone")) {
+ return;
+ }
+ auto it = active_connections_.find(endpoint_id);
+ if (it == active_connections_.end()) {
+ return;
+ }
+ const std::unique_ptr<LogicalConnection> &logical_connection = it->second;
+ logical_connection->IncomingPayloadDone(payload_id, status);
+}
+
+void AnalyticsRecorder::OnOutgoingPayloadStarted(
+ const std::vector<std::string> &endpoint_ids, std::int64_t payload_id,
+ connections::Payload::Type type, std::int64_t total_size_bytes) {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("OnOutgoingPayloadStarted")) {
+ return;
+ }
+ for (const auto &endpoint_id : endpoint_ids) {
+ auto it = active_connections_.find(endpoint_id);
+ if (it == active_connections_.end()) {
+ continue;
+ }
+ const std::unique_ptr<LogicalConnection> &logical_connection = it->second;
+ logical_connection->OutgoingPayloadStarted(
+ payload_id, PayloadTypeToProtoPayloadType(type), total_size_bytes);
+ }
+}
+
+void AnalyticsRecorder::OnPayloadChunkSent(const std::string &endpoint_id,
+ std::int64_t payload_id,
+ std::int64_t chunk_size_bytes) {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("OnPayloadChunkSent")) {
+ return;
+ }
+ auto it = active_connections_.find(endpoint_id);
+ if (it == active_connections_.end()) {
+ return;
+ }
+ const std::unique_ptr<LogicalConnection> &logical_connection = it->second;
+ logical_connection->ChunkSent(payload_id, chunk_size_bytes);
+}
+
+void AnalyticsRecorder::OnOutgoingPayloadDone(const std::string &endpoint_id,
+ std::int64_t payload_id,
+ PayloadStatus status) {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("OnOutgoingPayloadDone")) {
+ return;
+ }
+ auto it = active_connections_.find(endpoint_id);
+ if (it == active_connections_.end()) {
+ return;
+ }
+ const std::unique_ptr<LogicalConnection> &logical_connection = it->second;
+ logical_connection->OutgoingPayloadDone(payload_id, status);
+}
+
+void AnalyticsRecorder::OnBandwidthUpgradeStarted(
+ const std::string &endpoint_id, Medium from_medium, Medium to_medium,
+ ConnectionAttemptDirection direction, const std::string &connection_token) {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("OnBandwidthUpgradeStarted")) {
+ return;
+ }
+ auto bandwidth_upgrade_attempt =
+ absl::make_unique<ConnectionsLog::BandwidthUpgradeAttempt>();
+ bandwidth_upgrade_attempt->set_duration_millis(
+ absl::ToUnixMillis(SystemClock::ElapsedRealtime()));
+ bandwidth_upgrade_attempt->set_from_medium(from_medium);
+ bandwidth_upgrade_attempt->set_to_medium(to_medium);
+ bandwidth_upgrade_attempt->set_direction(direction);
+ bandwidth_upgrade_attempt->set_connection_token(connection_token);
+ bandwidth_upgrade_attempts_.insert(
+ {endpoint_id, std::move(bandwidth_upgrade_attempt)});
+}
+
+void AnalyticsRecorder::OnBandwidthUpgradeError(
+ const std::string &endpoint_id, BandwidthUpgradeResult result,
+ BandwidthUpgradeErrorStage error_stage) {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("OnBandwidthUpgradeError")) {
+ return;
+ }
+ FinishUpgradeAttemptLocked(endpoint_id, result, error_stage);
+}
+
+void AnalyticsRecorder::OnBandwidthUpgradeSuccess(
+ const std::string &endpoint_id) {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("OnBandwidthUpgradeSuccess")) {
+ return;
+ }
+ FinishUpgradeAttemptLocked(endpoint_id, UPGRADE_RESULT_SUCCESS,
+ UPGRADE_SUCCESS);
+}
+
+void AnalyticsRecorder::OnErrorCode(const ErrorCodeParams &params) {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("OnErrorCode")) {
+ return;
+ }
+ auto error_code = absl::make_unique<ConnectionsLog::ErrorCode>();
+ error_code->set_medium(params.medium);
+ error_code->set_event(params.event);
+ error_code->set_connection_token(params.connection_token);
+ error_code->set_description(params.description);
+
+ if (params.is_common_error) {
+ error_code->set_common_error(params.common_error);
+ } else {
+ switch (params.event) {
+ case errorcode::proto::START_ADVERTISING:
+ error_code->set_start_advertising_error(params.start_advertising_error);
+ break;
+ case errorcode::proto::STOP_ADVERTISING:
+ error_code->set_stop_advertising_error(params.stop_advertising_error);
+ break;
+ case errorcode::proto::START_LISTENING_INCOMING_CONNECTION:
+ error_code->set_start_listening_incoming_connection_error(
+ params.start_listening_incoming_connection_error);
+ break;
+ case errorcode::proto::STOP_LISTENING_INCOMING_CONNECTION:
+ error_code->set_stop_listening_incoming_connection_error(
+ params.stop_listening_incoming_connection_error);
+ break;
+ case errorcode::proto::START_DISCOVERING:
+ error_code->set_start_discovering_error(params.start_discovering_error);
+ break;
+ case errorcode::proto::STOP_DISCOVERING:
+ error_code->set_stop_discovering_error(params.stop_discovering_error);
+ break;
+ case errorcode::proto::CONNECT:
+ error_code->set_connect_error(params.connect_error);
+ break;
+ case errorcode::proto::DISCONNECT:
+ error_code->set_disconnect_error(params.disconnect_error);
+ break;
+ case errorcode::proto::UNKNOWN_EVENT:
+ default:
+ error_code->set_common_error(params.common_error);
+ break;
+ }
+ }
+
+ serial_executor_.Execute(
+ "analytics-recorder", [this, error_code = error_code.release()]() {
+ ConnectionsLog connections_log;
+ connections_log.set_event_type(ERROR_CODE);
+ connections_log.set_version(kVersion);
+ connections_log.set_allocated_error_code(error_code);
+
+ NEARBY_LOGS(VERBOSE)
+ << "AnalyticsRecorder LogErrorCode connections_log="
+ << connections_log.DebugString();
+
+ event_logger_->Log(connections_log);
+ });
+}
+
+void AnalyticsRecorder::LogSession() {
+ MutexLock lock(&mutex_);
+ if (!CanRecordAnalyticsLocked("LogSession")) {
+ return;
+ }
+ FinishStrategySessionLocked();
+ client_session_->set_duration_millis(absl::ToInt64Milliseconds(
+ SystemClock::ElapsedRealtime() - started_client_session_time_));
+ LogClientSession();
+ LogEvent(STOP_CLIENT_SESSION);
+ session_was_logged_ = true;
+}
+
+std::unique_ptr<ConnectionAttemptMetadataParams>
+AnalyticsRecorder::BuildConnectionAttemptMetadataParams(
+ ConnectionTechnology technology, ConnectionBand band, int frequency,
+ int try_count, const std::string &network_operator,
+ const std::string &country_code, bool is_tdls_used,
+ bool wifi_hotspot_enabled, int max_wifi_tx_speed, int max_wifi_rx_speed,
+ int channel_width) {
+ auto params = absl::make_unique<ConnectionAttemptMetadataParams>();
+ params->technology = technology;
+ params->band = band;
+ params->frequency = frequency;
+ params->try_count = try_count;
+ params->network_operator = network_operator;
+ params->country_code = country_code;
+ params->is_tdls_used = is_tdls_used;
+ params->wifi_hotspot_enabled = wifi_hotspot_enabled;
+ params->max_wifi_tx_speed = max_wifi_tx_speed;
+ params->max_wifi_rx_speed = max_wifi_rx_speed;
+ params->channel_width = channel_width;
+ return params;
+}
+
+bool AnalyticsRecorder::CanRecordAnalyticsLocked(
+ const std::string &method_name) {
+ NEARBY_LOGS(VERBOSE) << "AnalyticsRecorder LogEvent " << method_name
+ << " is calling.";
+ if (event_logger_ == nullptr) {
+ NEARBY_LOGS(WARNING)
+ << "AnalyticsRecorder CanRecordAnalytics Unexpected call "
+ << method_name << " due to event_logger is null.";
+ return false;
+ }
+
+ if (session_was_logged_) {
+ NEARBY_LOGS(WARNING)
+ << "AnalyticsRecorder CanRecordAnalytics Unexpected call "
+ << method_name << " after session has already been logged.";
+ return false;
+ }
+ return true;
+}
+
+void AnalyticsRecorder::LogClientSession() {
+ serial_executor_.Execute(
+ "analytics-recorder", [this]() {
+ ConnectionsLog connections_log;
+ connections_log.set_event_type(CLIENT_SESSION);
+ connections_log.set_allocated_client_session(client_session_.release());
+ connections_log.set_version(kVersion);
+
+ NEARBY_LOGS(VERBOSE)
+ << "AnalyticsRecorder LogClientSession connections_log="
+ << connections_log.DebugString();
+
+ event_logger_->Log(connections_log);
+ });
+}
+
+void AnalyticsRecorder::LogEvent(EventType event_type) {
+ serial_executor_.Execute("analytics-recorder", [this, event_type]() {
+ ConnectionsLog connections_log;
+ connections_log.set_event_type(event_type);
+ connections_log.set_version(kVersion);
+
+ NEARBY_LOGS(VERBOSE) << "AnalyticsRecorder LogEvent connections_log="
+ << connections_log.DebugString();
+
+ event_logger_->Log(connections_log);
+ });
+}
+
+void AnalyticsRecorder::UpdateStrategySessionLocked(
+ connections::Strategy strategy, SessionRole role) {
+ // If we're not switching strategies, just update the current StrategySession
+ // with the new role.
+ if (strategy == current_strategy_) {
+ if (absl::c_linear_search(current_strategy_session_->role(), role)) {
+ // We've already acted as this role before, so make sure we've finished
+ // recording the previous round.
+ switch (role) {
+ case ADVERTISER:
+ FinishAdvertisingPhaseLocked();
+ break;
+ case DISCOVERER:
+ FinishDiscoveryPhaseLocked();
+ break;
+ default:
+ break;
+ }
+ } else {
+ current_strategy_session_->add_role(role);
+ }
+ } else {
+ // Otherwise, we're starting a new Strategy.
+ current_strategy_ = strategy;
+ FinishStrategySessionLocked();
+ LogEvent(START_STRATEGY_SESSION);
+ current_strategy_session_ =
+ absl::make_unique<ConnectionsLog::StrategySession>();
+ started_strategy_session_time_ = SystemClock::ElapsedRealtime();
+ current_strategy_session_->set_strategy(
+ StrategyToConnectionStrategy(strategy));
+ current_strategy_session_->add_role(role);
+ }
+}
+
+void AnalyticsRecorder::RecordAdvertisingPhaseDurationLocked() const {
+ if (current_advertising_phase_ == nullptr) {
+ NEARBY_LOGS(INFO) << "Unable to record advertising phase duration due to "
+ "null current_advertising_phase_";
+ return;
+ }
+ if (!current_advertising_phase_->has_duration_millis()) {
+ current_advertising_phase_->set_duration_millis(absl::ToInt64Milliseconds(
+ SystemClock::ElapsedRealtime() - started_advertising_phase_time_));
+ }
+}
+
+void AnalyticsRecorder::FinishAdvertisingPhaseLocked() {
+ if (current_advertising_phase_ != nullptr) {
+ for (const auto &item : incoming_connection_requests_) {
+ // ConnectionRequests still pending have been ignored by the local or
+ // remote (or both) endpoints.
+ const std::unique_ptr<ConnectionsLog::ConnectionRequest>
+ &connection_request = item.second;
+ MarkConnectionRequestIgnoredLocked(connection_request.get());
+ UpdateAdvertiserConnectionRequestLocked(connection_request.get());
+ }
+ RecordAdvertisingPhaseDurationLocked();
+ *current_strategy_session_->add_advertising_phase() =
+ *std::move(current_advertising_phase_);
+ }
+ incoming_connection_requests_.clear();
+}
+
+void AnalyticsRecorder::RecordDiscoveryPhaseDurationLocked() const {
+ if (current_discovery_phase_ == nullptr) {
+ NEARBY_LOGS(INFO) << "Unable to record discovery phase duration due to "
+ "null current_discovery_phase_";
+ return;
+ }
+ if (!current_discovery_phase_->has_duration_millis()) {
+ current_discovery_phase_->set_duration_millis(absl::ToInt64Milliseconds(
+ SystemClock::ElapsedRealtime() - started_discovery_phase_time_));
+ }
+}
+
+void AnalyticsRecorder::FinishDiscoveryPhaseLocked() {
+ if (current_discovery_phase_ != nullptr) {
+ for (const auto &item : outgoing_connection_requests_) {
+ // ConnectionRequests still pending have been ignored by the local or
+ // remote (or both) endpoints.
+ const std::unique_ptr<ConnectionsLog::ConnectionRequest>
+ &connection_request = item.second;
+ MarkConnectionRequestIgnoredLocked(connection_request.get());
+ UpdateDiscovererConnectionRequestLocked(connection_request.get());
+ }
+ RecordDiscoveryPhaseDurationLocked();
+ *current_strategy_session_->add_discovery_phase() =
+ *std::move(current_discovery_phase_);
+ }
+ outgoing_connection_requests_.clear();
+}
+
+bool AnalyticsRecorder::UpdateAdvertiserConnectionRequestLocked(
+ ConnectionsLog::ConnectionRequest *request) {
+ if (current_advertising_phase_ == nullptr) {
+ NEARBY_LOGS(INFO)
+ << "Unable to record advertiser connection request due to null "
+ "current_advertising_phase_";
+ return false;
+ }
+ if (BothEndpointsRespondedLocked(request)) {
+ request->set_duration_millis(
+ absl::ToUnixMillis(SystemClock::ElapsedRealtime()) -
+ request->duration_millis());
+ *current_advertising_phase_->add_received_connection_request() = *request;
+ return true;
+ }
+ return false;
+}
+
+bool AnalyticsRecorder::UpdateDiscovererConnectionRequestLocked(
+ ConnectionsLog::ConnectionRequest *request) {
+ if (current_discovery_phase_ == nullptr) {
+ NEARBY_LOGS(INFO) << "Unable to record discoverer connection request due "
+ "to null current_discovery_phase_.";
+ return false;
+ }
+ if (BothEndpointsRespondedLocked(request) ||
+ request->local_response() == NOT_SENT) {
+ request->set_duration_millis(
+ absl::ToUnixMillis(SystemClock::ElapsedRealtime()) -
+ request->duration_millis());
+ *current_discovery_phase_->add_sent_connection_request() = *request;
+ return true;
+ }
+ return false;
+}
+
+bool AnalyticsRecorder::BothEndpointsRespondedLocked(
+ ConnectionsLog::ConnectionRequest *request) {
+ return request->has_local_response() && request->has_remote_response();
+}
+
+void AnalyticsRecorder::LocalEndpointRespondedLocked(
+ const std::string &remote_endpoint_id, ConnectionRequestResponse response) {
+ auto out = outgoing_connection_requests_.find(remote_endpoint_id);
+ if (out != outgoing_connection_requests_.end()) {
+ ConnectionsLog::ConnectionRequest *connection_request = out->second.get();
+ connection_request->set_local_response(response);
+ if (UpdateDiscovererConnectionRequestLocked(connection_request)) {
+ outgoing_connection_requests_.erase(out);
+ }
+ }
+ auto in = incoming_connection_requests_.find(remote_endpoint_id);
+ if (in != incoming_connection_requests_.end()) {
+ ConnectionsLog::ConnectionRequest *connection_request = in->second.get();
+ connection_request->set_local_response(response);
+ if (UpdateAdvertiserConnectionRequestLocked(connection_request)) {
+ incoming_connection_requests_.erase(in);
+ }
+ }
+}
+
+void AnalyticsRecorder::RemoteEndpointRespondedLocked(
+ const std::string &remote_endpoint_id, ConnectionRequestResponse response) {
+ auto out = outgoing_connection_requests_.find(remote_endpoint_id);
+ if (out != outgoing_connection_requests_.end()) {
+ ConnectionsLog::ConnectionRequest *connection_request = out->second.get();
+ connection_request->set_remote_response(response);
+ if (UpdateDiscovererConnectionRequestLocked(connection_request)) {
+ outgoing_connection_requests_.erase(out);
+ }
+ }
+ auto in = incoming_connection_requests_.find(remote_endpoint_id);
+ if (in != incoming_connection_requests_.end()) {
+ ConnectionsLog::ConnectionRequest *connection_request = in->second.get();
+ connection_request->set_remote_response(response);
+ if (UpdateAdvertiserConnectionRequestLocked(connection_request)) {
+ incoming_connection_requests_.erase(in);
+ }
+ }
+}
+
+void AnalyticsRecorder::MarkConnectionRequestIgnoredLocked(
+ ConnectionsLog::ConnectionRequest *request) {
+ if (!request->has_local_response()) {
+ request->set_local_response(IGNORED);
+ }
+ if (!request->has_remote_response()) {
+ request->set_remote_response(IGNORED);
+ }
+}
+
+void AnalyticsRecorder::FinishUpgradeAttemptLocked(
+ const std::string &endpoint_id, BandwidthUpgradeResult result,
+ BandwidthUpgradeErrorStage error_stage, bool erase_item) {
+ if (current_strategy_session_ == nullptr) {
+ NEARBY_LOGS(INFO) << "Unable to record upgrade attempt due to null "
+ "current_strategy_session_";
+ return;
+ }
+ // Add the BandwidthUpgradeAttempt in the current StrategySession.
+ auto it = bandwidth_upgrade_attempts_.find(endpoint_id);
+ if (it != bandwidth_upgrade_attempts_.end()) {
+ ConnectionsLog::BandwidthUpgradeAttempt *attempt = it->second.get();
+ attempt->set_duration_millis(
+ absl::ToUnixMillis(SystemClock::ElapsedRealtime()) -
+ attempt->duration_millis());
+ attempt->set_error_stage(error_stage);
+ attempt->set_upgrade_result(result);
+ *current_strategy_session_->add_upgrade_attempt() = *attempt;
+ if (erase_item) {
+ bandwidth_upgrade_attempts_.erase(it);
+ }
+ }
+}
+
+void AnalyticsRecorder::FinishStrategySessionLocked() {
+ if (current_strategy_session_ != nullptr) {
+ FinishAdvertisingPhaseLocked();
+ FinishDiscoveryPhaseLocked();
+
+ // Finish any unfinished LogicalConnections.
+ for (const auto &item : active_connections_) {
+ const std::unique_ptr<LogicalConnection> &logical_connection =
+ item.second;
+ logical_connection->CloseAllPhysicalConnections();
+ absl::c_copy(
+ logical_connection->GetEstablisedConnections(),
+ RepeatedFieldBackInserter(
+ current_strategy_session_->mutable_established_connection()));
+ }
+ active_connections_.clear();
+
+ // Finish any pending upgrade attempts.
+ for (const auto &item : bandwidth_upgrade_attempts_) {
+ FinishUpgradeAttemptLocked(item.first, UNFINISHED_ERROR,
+ UPGRADE_UNFINISHED, /*erase_item=*/false);
+ }
+ bandwidth_upgrade_attempts_.clear();
+
+ // Add the StrategySession in ClientSession
+ current_strategy_session_->set_duration_millis(absl::ToInt64Milliseconds(
+ started_strategy_session_time_ - SystemClock::ElapsedRealtime()));
+ *client_session_->add_strategy_session() =
+ *std::move(current_strategy_session_);
+ LogEvent(STOP_STRATEGY_SESSION);
+ }
+}
+
+ConnectionsStrategy AnalyticsRecorder::StrategyToConnectionStrategy(
+ connections::Strategy strategy) {
+ if (strategy == connections::Strategy::kP2pCluster) {
+ return P2P_CLUSTER;
+ }
+ if (strategy == connections::Strategy::kP2pStar) {
+ return P2P_STAR;
+ }
+ if (strategy == connections::Strategy::kP2pPointToPoint) {
+ return P2P_POINT_TO_POINT;
+ }
+ return UNKNOWN_STRATEGY;
+}
+
+PayloadType AnalyticsRecorder::PayloadTypeToProtoPayloadType(
+ connections::Payload::Type type) {
+ switch (type) {
+ case connections::Payload::Type::kBytes:
+ return BYTES;
+ case connections::Payload::Type::kFile:
+ return FILE;
+ case connections::Payload::Type::kStream:
+ return STREAM;
+ default:
+ return UNKNOWN_PAYLOAD_TYPE;
+ }
+}
+
+void AnalyticsRecorder::PendingPayload::AddChunk(
+ std::int64_t chunk_size_bytes) {
+ num_bytes_transferred_ += chunk_size_bytes;
+ num_chunks_++;
+}
+
+ConnectionsLog::Payload AnalyticsRecorder::PendingPayload::GetProtoPayload(
+ PayloadStatus status) {
+ ConnectionsLog::Payload payload;
+ payload.set_duration_millis(
+ absl::ToInt64Milliseconds(SystemClock::ElapsedRealtime() - start_time_));
+ payload.set_type(type_);
+ payload.set_total_size_bytes(total_size_bytes_);
+ payload.set_num_bytes_transferred(num_bytes_transferred_);
+ payload.set_num_chunks(num_chunks_);
+ payload.set_status(status);
+
+ return payload;
+}
+
+void AnalyticsRecorder::LogicalConnection::PhysicalConnectionEstablished(
+ Medium medium, const std::string &connection_token) {
+ if (current_medium_ != UNKNOWN_MEDIUM) {
+ NEARBY_LOGS(WARNING)
+ << "Unexpected call to PhysicalConnectionEstablished while "
+ "AnalyticsRecorder still has an active current medium.";
+ }
+
+ auto established_connection =
+ absl::make_unique<ConnectionsLog::EstablishedConnection>();
+ established_connection->set_medium(medium);
+ established_connection->set_duration_millis(
+ absl::ToUnixMillis(SystemClock::ElapsedRealtime()));
+ established_connection->set_connection_token(connection_token);
+ physical_connections_.insert({medium, std::move(established_connection)});
+ current_medium_ = medium;
+}
+
+void AnalyticsRecorder::LogicalConnection::PhysicalConnectionClosed(
+ Medium medium, DisconnectionReason reason) {
+ if (current_medium_ == UNKNOWN_MEDIUM) {
+ NEARBY_LOGS(WARNING)
+ << "Unexpected call to PhysicalConnectionClosed() for medium "
+ << Medium_Name(medium)
+ << " while AnalyticsRecorder has no active current medium";
+ } else if (current_medium_ != medium) {
+ NEARBY_LOGS(WARNING)
+ << "Unexpected call to PhysicalConnectionClosed() for medium "
+ << Medium_Name(medium) << "while AnalyticsRecorder has active medium "
+ << Medium_Name(current_medium_);
+ }
+
+ auto it = physical_connections_.find(medium);
+ if (it == physical_connections_.end()) {
+ NEARBY_LOGS(WARNING)
+ << "Unexpected call to physicalConnectionClosed() for medium "
+ << Medium_Name(medium)
+ << " with no corresponding EstablishedConnection that was previously"
+ " opened.";
+ return;
+ }
+ ConnectionsLog::EstablishedConnection *established_connection =
+ it->second.get();
+ if (established_connection->has_disconnection_reason()) {
+ NEARBY_LOGS(WARNING)
+ << "Unexpected call to physicalConnectionClosed() for medium "
+ << Medium_Name(medium) << " which already has disconnection reason "
+ << DisconnectionReason_Name(
+ established_connection->disconnection_reason());
+ return;
+ }
+ FinishPhysicalConnection(established_connection, reason);
+
+ if (medium == current_medium_) {
+ // If the EstablishedConnection we just closed was the one that we have
+ // marked as current, unset currentMedium.
+ current_medium_ = UNKNOWN_MEDIUM;
+ }
+}
+
+void AnalyticsRecorder::LogicalConnection::CloseAllPhysicalConnections() {
+ for (const auto &physical_connection : physical_connections_) {
+ ConnectionsLog::EstablishedConnection *established_connection =
+ physical_connection.second.get();
+ if (!established_connection->has_disconnection_reason()) {
+ FinishPhysicalConnection(established_connection, UNFINISHED);
+ }
+ }
+ current_medium_ = UNKNOWN_MEDIUM;
+}
+
+std::vector<ConnectionsLog::EstablishedConnection>
+AnalyticsRecorder::LogicalConnection::GetEstablisedConnections() {
+ std::vector<ConnectionsLog::EstablishedConnection> established_connections;
+ if (current_medium_ != UNKNOWN_MEDIUM) {
+ NEARBY_LOGS(WARNING)
+ << "AnalyticsRecorder expected no more active physical connections "
+ "before logging this endpoint connection.";
+ return established_connections;
+ }
+ std::transform(physical_connections_.begin(), physical_connections_.end(),
+ std::back_inserter(established_connections),
+ [](auto &kv) { return *kv.second; });
+ physical_connections_.clear();
+ return established_connections;
+}
+
+void AnalyticsRecorder::LogicalConnection::IncomingPayloadStarted(
+ std::int64_t payload_id, PayloadType type, std::int64_t total_size_bytes) {
+ incoming_payloads_.insert(
+ {payload_id, absl::make_unique<PendingPayload>(type, total_size_bytes)});
+}
+
+void AnalyticsRecorder::LogicalConnection::ChunkReceived(
+ std::int64_t payload_id, std::int64_t size_bytes) {
+ auto it = incoming_payloads_.find(payload_id);
+ if (it == incoming_payloads_.end()) {
+ return;
+ }
+ PendingPayload *pending_payload = it->second.get();
+ pending_payload->AddChunk(size_bytes);
+}
+
+void AnalyticsRecorder::LogicalConnection::IncomingPayloadDone(
+ std::int64_t payload_id, PayloadStatus status) {
+ if (current_medium_ == UNKNOWN_MEDIUM) {
+ NEARBY_LOGS(WARNING) << "Unexpected call to incomingPayloadDone() while "
+ "AnalyticsRecorder has no active current medium.";
+ return;
+ }
+ auto it = physical_connections_.find(current_medium_);
+ if (it != physical_connections_.end()) {
+ const std::unique_ptr<ConnectionsLog::EstablishedConnection>
+ &established_connection = it->second;
+ auto it = incoming_payloads_.find(payload_id);
+ if (it != incoming_payloads_.end()) {
+ *established_connection->add_received_payload() =
+ it->second->GetProtoPayload(status);
+ incoming_payloads_.erase(it);
+ }
+ }
+}
+
+void AnalyticsRecorder::LogicalConnection::OutgoingPayloadStarted(
+ std::int64_t payload_id, PayloadType type, std::int64_t total_size_bytes) {
+ outgoing_payloads_.insert(
+ {payload_id, absl::make_unique<PendingPayload>(type, total_size_bytes)});
+}
+
+void AnalyticsRecorder::LogicalConnection::ChunkSent(std::int64_t payload_id,
+ std::int64_t size_bytes) {
+ auto it = outgoing_payloads_.find(payload_id);
+ if (it == outgoing_payloads_.end()) {
+ return;
+ }
+ PendingPayload *payload = it->second.get();
+ payload->AddChunk(size_bytes);
+}
+
+void AnalyticsRecorder::LogicalConnection::OutgoingPayloadDone(
+ std::int64_t payload_id, PayloadStatus status) {
+ if (current_medium_ == UNKNOWN_MEDIUM) {
+ NEARBY_LOGS(WARNING) << "Unexpected call to outgoingPayloadDone() while "
+ "AnalyticsRecorder has no active current medium.";
+ return;
+ }
+ auto it = physical_connections_.find(current_medium_);
+ if (it != physical_connections_.end()) {
+ const std::unique_ptr<ConnectionsLog::EstablishedConnection>
+ &established_connection = it->second;
+ auto it = outgoing_payloads_.find(payload_id);
+ if (it != outgoing_payloads_.end()) {
+ *established_connection->add_sent_payload() =
+ it->second->GetProtoPayload(status);
+ outgoing_payloads_.erase(it);
+ }
+ }
+}
+
+void AnalyticsRecorder::LogicalConnection::FinishPhysicalConnection(
+ ConnectionsLog::EstablishedConnection *established_connection,
+ DisconnectionReason reason) {
+ established_connection->set_disconnection_reason(reason);
+ established_connection->set_duration_millis(
+ absl::ToUnixMillis(SystemClock::ElapsedRealtime()) -
+ established_connection->duration_millis());
+
+ // Add any not-yet-finished payloads to this EstablishedConnection.
+ std::vector<ConnectionsLog::Payload> in_payloads =
+ ResolvePendingPayloads(incoming_payloads_, reason);
+ absl::c_move(in_payloads,
+ RepeatedFieldBackInserter(
+ established_connection->mutable_received_payload()));
+ std::vector<ConnectionsLog::Payload> out_payloads =
+ ResolvePendingPayloads(outgoing_payloads_, reason);
+ absl::c_move(out_payloads,
+ RepeatedFieldBackInserter(
+ established_connection->mutable_sent_payload()));
+}
+
+std::vector<ConnectionsLog::Payload>
+AnalyticsRecorder::LogicalConnection::ResolvePendingPayloads(
+ absl::btree_map<std::int64_t, std::unique_ptr<PendingPayload>>
+ &pending_payloads,
+ DisconnectionReason reason) {
+ std::vector<ConnectionsLog::Payload> completed_payloads;
+ absl::btree_map<std::int64_t, std::unique_ptr<PendingPayload>>
+ upgraded_payloads;
+ PayloadStatus status =
+ reason == UPGRADED ? MOVED_TO_NEW_MEDIUM : CONNECTION_CLOSED;
+ for (const auto &item : pending_payloads) {
+ const std::unique_ptr<PendingPayload> &pending_payload = item.second;
+ ConnectionsLog::Payload proto_payload =
+ pending_payload->GetProtoPayload(status);
+ completed_payloads.push_back(proto_payload);
+ if (reason == UPGRADED) {
+ upgraded_payloads.insert(
+ {item.first,
+ absl::make_unique<PendingPayload>(
+ pending_payload->type(), pending_payload->total_size_bytes())});
+ }
+ }
+ pending_payloads.clear();
+
+ if (reason == UPGRADED) {
+ // Re-populate the map with a new PendingPayload for each pending payload,
+ // since we expect them to be completed on the next EstablishedConnection.
+ pending_payloads = std::move(upgraded_payloads);
+ }
+ // Return the list of completed payloads to be added to the current
+ // EstablishedConnection.
+ return completed_payloads;
+}
+
+} // namespace analytics
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/analytics/analytics_recorder.h b/chromium/third_party/nearby/src/internal/analytics/analytics_recorder.h
new file mode 100644
index 00000000000..866574c0c51
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/analytics/analytics_recorder.h
@@ -0,0 +1,369 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef ANALYTICS_ANALYTICS_RECORDER_H_
+#define ANALYTICS_ANALYTICS_RECORDER_H_
+
+#include <string>
+
+#include "absl/container/btree_map.h"
+#include "absl/time/time.h"
+#include "connections/event_logger.h"
+#include "connections/payload.h"
+#include "connections/strategy.h"
+#include "internal/platform/error_code_params.h"
+#include "internal/platform/mutex.h"
+#include "internal/platform/single_thread_executor.h"
+#include "internal/analytics/connection_attempt_metadata_params.h"
+#include "internal/proto/analytics/connections_log.pb.h"
+#include "proto/connections_enums.pb.h"
+
+namespace location {
+namespace nearby {
+namespace analytics {
+
+class AnalyticsRecorder {
+ public:
+ explicit AnalyticsRecorder(EventLogger *event_logger);
+ virtual ~AnalyticsRecorder();
+
+ // TODO(edwinwu): Implement to pass real values for AdvertisingMetadata and
+ // DiscoveryMetaData: is_extended_advertisement_supported,
+ // connected_ap_frequency, and is_nfc_available. Set as default values for
+ // analytics recorder.
+ // Advertising phase
+ void OnStartAdvertising(
+ connections::Strategy strategy,
+ const std::vector<location::nearby::proto::connections::Medium> &mediums,
+ bool is_extended_advertisement_supported = false,
+ int connected_ap_frequency = 0, bool is_nfc_available = false)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ void OnStopAdvertising() ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Discovery phase
+ void OnStartDiscovery(
+ connections::Strategy strategy,
+ const std::vector<location::nearby::proto::connections::Medium> &mediums,
+ bool is_extended_advertisement_supported = false,
+ int connected_ap_frequency = 0, bool is_nfc_available = false)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ void OnStopDiscovery() ABSL_LOCKS_EXCLUDED(mutex_);
+ void OnEndpointFound(location::nearby::proto::connections::Medium medium)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Connection request
+ void OnConnectionRequestReceived(const std::string &remote_endpoint_id)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ void OnConnectionRequestSent(const std::string &remote_endpoint_id)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ void OnRemoteEndpointAccepted(const std::string &remote_endpoint_id)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ void OnLocalEndpointAccepted(const std::string &remote_endpoint_id)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ void OnRemoteEndpointRejected(const std::string &remote_endpoint_id)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ void OnLocalEndpointRejected(const std::string &remote_endpoint_id)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Connection attempt
+ void OnIncomingConnectionAttempt(
+ location::nearby::proto::connections::ConnectionAttemptType type,
+ location::nearby::proto::connections::Medium medium,
+ location::nearby::proto::connections::ConnectionAttemptResult result,
+ absl::Duration duration, const std::string &connection_token,
+ ConnectionAttemptMetadataParams *connection_attempt_metadata_params)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ void OnOutgoingConnectionAttempt(
+ const std::string &remote_endpoint_id,
+ location::nearby::proto::connections::ConnectionAttemptType type,
+ location::nearby::proto::connections::Medium medium,
+ location::nearby::proto::connections::ConnectionAttemptResult result,
+ absl::Duration duration, const std::string &connection_token,
+ ConnectionAttemptMetadataParams *connection_attempt_metadata_params)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ // TODO(edwinwu): Implement network operator, country code, tdls, wifi hotspot
+ //, max wifi tx/rx speed and channel width. Set as default values for
+ // analytics recorder.
+ static std::unique_ptr<ConnectionAttemptMetadataParams>
+ BuildConnectionAttemptMetadataParams(
+ location::nearby::proto::connections::ConnectionTechnology technology,
+ location::nearby::proto::connections::ConnectionBand band, int frequency,
+ int try_count, const std::string &network_operator = {},
+ const std::string &country_code = {}, bool is_tdls_used = false,
+ bool wifi_hotspot_enabled = false, int max_wifi_tx_speed = 0,
+ int max_wifi_rx_speed = 0, int channel_width = -1);
+
+ // Connection established
+ void OnConnectionEstablished(
+ const std::string &endpoint_id,
+ location::nearby::proto::connections::Medium medium,
+ const std::string &connection_token) ABSL_LOCKS_EXCLUDED(mutex_);
+ void OnConnectionClosed(
+ const std::string &endpoint_id,
+ location::nearby::proto::connections::Medium medium,
+ location::nearby::proto::connections ::DisconnectionReason reason)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Payload
+ void OnIncomingPayloadStarted(const std::string &endpoint_id,
+ std::int64_t payload_id,
+ connections::Payload::Type type,
+ std::int64_t total_size_bytes)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ void OnPayloadChunkReceived(const std::string &endpoint_id,
+ std::int64_t payload_id,
+ std::int64_t chunk_size_bytes)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ void OnIncomingPayloadDone(
+ const std::string &endpoint_id, std::int64_t payload_id,
+ location::nearby::proto::connections::PayloadStatus status)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ void OnOutgoingPayloadStarted(const std::vector<std::string> &endpoint_ids,
+ std::int64_t payload_id,
+ connections::Payload::Type type,
+ std::int64_t total_size_bytes)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ void OnPayloadChunkSent(const std::string &endpoint_id,
+ std::int64_t payload_id,
+ std::int64_t chunk_size_bytes)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ void OnOutgoingPayloadDone(
+ const std::string &endpoint_id, std::int64_t payload_id,
+ location::nearby::proto::connections::PayloadStatus status)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // BandwidthUpgrade
+ void OnBandwidthUpgradeStarted(
+ const std::string &endpoint_id,
+ location::nearby::proto::connections::Medium from_medium,
+ location::nearby::proto::connections::Medium to_medium,
+ location::nearby::proto::connections::ConnectionAttemptDirection
+ direction,
+ const std::string &connection_token) ABSL_LOCKS_EXCLUDED(mutex_);
+ void OnBandwidthUpgradeError(
+ const std::string &endpoint_id,
+ location::nearby::proto::connections::BandwidthUpgradeResult result,
+ location::nearby::proto::connections::BandwidthUpgradeErrorStage
+ error_stage) ABSL_LOCKS_EXCLUDED(mutex_);
+ void OnBandwidthUpgradeSuccess(const std::string &endpoint_id)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Error Code
+ void OnErrorCode(const ErrorCodeParams &params);
+
+ // Invokes event_logger_.Log() at the end of life of client. Log action is
+ // called in a separate thread to allow synchronous potentially lengthy
+ // execution.
+ void LogSession() ABSL_LOCKS_EXCLUDED(mutex_);
+
+ private:
+ // Tracks the chunks and duration of a Payload on a particular medium.
+ class PendingPayload {
+ public:
+ PendingPayload(location::nearby::proto::connections::PayloadType type,
+ std::int64_t total_size_bytes)
+ : start_time_(SystemClock::ElapsedRealtime()),
+ type_(type),
+ total_size_bytes_(total_size_bytes),
+ num_bytes_transferred_(0),
+ num_chunks_(0) {}
+ ~PendingPayload() = default;
+
+ void AddChunk(std::int64_t chunk_size_bytes);
+
+ proto::ConnectionsLog::Payload GetProtoPayload(
+ location::nearby::proto::connections::PayloadStatus status);
+
+ location::nearby::proto::connections::PayloadType type() const {
+ return type_;
+ }
+
+ std::int64_t total_size_bytes() const { return total_size_bytes_; }
+
+ private:
+ absl::Time start_time_;
+ location::nearby::proto::connections::PayloadType type_;
+ std::int64_t total_size_bytes_;
+ std::int64_t num_bytes_transferred_;
+ int num_chunks_;
+ };
+
+ class LogicalConnection {
+ public:
+ LogicalConnection(
+ location::nearby::proto::connections::Medium initial_medium,
+ const std::string &connection_token) {
+ PhysicalConnectionEstablished(initial_medium, connection_token);
+ }
+ LogicalConnection(const LogicalConnection &) = delete;
+ LogicalConnection(LogicalConnection &&other)
+ : current_medium_(std::move(other.current_medium_)),
+ physical_connections_(std::move(other.physical_connections_)),
+ incoming_payloads_(std::move(other.incoming_payloads_)),
+ outgoing_payloads_(std::move(other.outgoing_payloads_)) {}
+ LogicalConnection &operator=(const LogicalConnection &) = delete;
+ LogicalConnection &&operator=(LogicalConnection &&) = delete;
+ ~LogicalConnection() = default;
+
+ void PhysicalConnectionEstablished(
+ location::nearby::proto::connections::Medium medium,
+ const std::string &connection_token);
+ void PhysicalConnectionClosed(
+ location::nearby::proto::connections::Medium medium,
+ location::nearby::proto::connections::DisconnectionReason reason);
+ void CloseAllPhysicalConnections();
+
+ void IncomingPayloadStarted(
+ std::int64_t payload_id,
+ location::nearby::proto::connections::PayloadType type,
+ std::int64_t total_size_bytes);
+ void ChunkReceived(std::int64_t payload_id, std::int64_t size_bytes);
+ void IncomingPayloadDone(
+ std::int64_t payload_id,
+ location::nearby::proto::connections::PayloadStatus status);
+ void OutgoingPayloadStarted(
+ std::int64_t payload_id,
+ location::nearby::proto::connections::PayloadType type,
+ std::int64_t total_size_bytes);
+ void ChunkSent(std::int64_t payload_id, std::int64_t size_bytes);
+ void OutgoingPayloadDone(
+ std::int64_t payload_id,
+ location::nearby::proto::connections::PayloadStatus status);
+
+ std::vector<proto::ConnectionsLog::EstablishedConnection>
+ GetEstablisedConnections();
+
+ private:
+ void FinishPhysicalConnection(
+ proto::ConnectionsLog::EstablishedConnection *established_connection,
+ location::nearby::proto::connections::DisconnectionReason reason);
+ std::vector<proto::ConnectionsLog::Payload> ResolvePendingPayloads(
+ absl::btree_map<std::int64_t, std::unique_ptr<PendingPayload>>
+ &pending_payloads,
+ location::nearby::proto::connections::DisconnectionReason reason);
+
+ location::nearby::proto::connections::Medium current_medium_ =
+ location::nearby::proto::connections::UNKNOWN_MEDIUM;
+ absl::btree_map<
+ location::nearby::proto::connections::Medium,
+ std::unique_ptr<proto::ConnectionsLog::EstablishedConnection>>
+ physical_connections_;
+ absl::btree_map<std::int64_t, std::unique_ptr<PendingPayload>>
+ incoming_payloads_;
+ absl::btree_map<std::int64_t, std::unique_ptr<PendingPayload>>
+ outgoing_payloads_;
+ };
+
+ bool CanRecordAnalyticsLocked(const std::string &method_name)
+ ABSL_SHARED_LOCKS_REQUIRED(mutex_);
+
+ // Callbacks the ConnectionsLog proto byte array data to the EventLogger with
+ // ClientSession sub-proto.
+ void LogClientSession();
+ // Callbacks the ConnectionsLog proto byte array data to the EventLogger.
+ void LogEvent(location::nearby::proto::connections::EventType event_type);
+
+ void UpdateStrategySessionLocked(
+ connections::Strategy strategy,
+ location::nearby::proto::connections::SessionRole role)
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+ void RecordAdvertisingPhaseDurationLocked() const
+ ABSL_SHARED_LOCKS_REQUIRED(mutex_);
+ void FinishAdvertisingPhaseLocked() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+ void RecordDiscoveryPhaseDurationLocked() const
+ ABSL_SHARED_LOCKS_REQUIRED(mutex_);
+ void FinishDiscoveryPhaseLocked() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+ bool UpdateAdvertiserConnectionRequestLocked(
+ proto::ConnectionsLog::ConnectionRequest *request)
+ ABSL_SHARED_LOCKS_REQUIRED(mutex_);
+ bool UpdateDiscovererConnectionRequestLocked(
+ proto::ConnectionsLog::ConnectionRequest *request)
+ ABSL_SHARED_LOCKS_REQUIRED(mutex_);
+ bool BothEndpointsRespondedLocked(
+ proto::ConnectionsLog::ConnectionRequest *request)
+ ABSL_SHARED_LOCKS_REQUIRED(mutex_);
+ void LocalEndpointRespondedLocked(
+ const std::string &remote_endpoint_id,
+ location::nearby::proto::connections::ConnectionRequestResponse response)
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+ void RemoteEndpointRespondedLocked(
+ const std::string &remote_endpoint_id,
+ location::nearby::proto::connections::ConnectionRequestResponse response)
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+ void MarkConnectionRequestIgnoredLocked(
+ proto::ConnectionsLog::ConnectionRequest *request)
+ ABSL_SHARED_LOCKS_REQUIRED(mutex_);
+ void FinishUpgradeAttemptLocked(
+ const std::string &endpoint_id,
+ location::nearby::proto::connections::BandwidthUpgradeResult result,
+ location::nearby::proto::connections::BandwidthUpgradeErrorStage
+ error_stage,
+ bool erase_item = true) ABSL_SHARED_LOCKS_REQUIRED(mutex_);
+ void FinishStrategySessionLocked() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ location::nearby::proto::connections::ConnectionsStrategy
+ StrategyToConnectionStrategy(connections::Strategy strategy);
+ location::nearby::proto::connections::PayloadType
+ PayloadTypeToProtoPayloadType(connections::Payload::Type type);
+
+ // Not owned by AnalyticsRecorder. Pointer must refer to a valid object
+ // that outlives the one constructed.
+ EventLogger *event_logger_;
+
+ SingleThreadExecutor serial_executor_;
+ // Protects all sub-protos reading and writing in ConnectionLog.
+ Mutex mutex_;
+
+ // ClientSession
+ std::unique_ptr<proto::ConnectionsLog::ClientSession> client_session_ =
+ absl::make_unique<proto::ConnectionsLog::ClientSession>();
+ absl::Time started_client_session_time_;
+ bool session_was_logged_ ABSL_GUARDED_BY(mutex_) = false;
+
+ // Current StrategySession
+ connections::Strategy current_strategy_ ABSL_GUARDED_BY(mutex_) =
+ connections::Strategy::kNone;
+ std::unique_ptr<proto::ConnectionsLog::StrategySession>
+ current_strategy_session_ ABSL_GUARDED_BY(mutex_);
+ absl::Time started_strategy_session_time_ ABSL_GUARDED_BY(mutex_);
+
+ // Current AdvertisingPhase
+ std::unique_ptr<proto::ConnectionsLog::AdvertisingPhase>
+ current_advertising_phase_;
+ absl::Time started_advertising_phase_time_;
+
+ // Current DiscoveryPhase
+ std::unique_ptr<proto::ConnectionsLog::DiscoveryPhase>
+ current_discovery_phase_;
+ absl::Time started_discovery_phase_time_;
+
+ absl::btree_map<std::string,
+ std::unique_ptr<proto::ConnectionsLog::ConnectionRequest>>
+ incoming_connection_requests_ ABSL_GUARDED_BY(mutex_);
+ absl::btree_map<std::string,
+ std::unique_ptr<proto::ConnectionsLog::ConnectionRequest>>
+ outgoing_connection_requests_ ABSL_GUARDED_BY(mutex_);
+ absl::btree_map<std::string, std::unique_ptr<LogicalConnection>>
+ active_connections_ ABSL_GUARDED_BY(mutex_);
+ absl::btree_map<
+ std::string,
+ std::unique_ptr<proto::ConnectionsLog::BandwidthUpgradeAttempt>>
+ bandwidth_upgrade_attempts_ ABSL_GUARDED_BY(mutex_);
+};
+
+} // namespace analytics
+} // namespace nearby
+} // namespace location
+
+#endif // ANALYTICS_ANALYTICS_RECORDER_H_
diff --git a/chromium/third_party/nearby/src/internal/analytics/analytics_recorder_test.cc b/chromium/third_party/nearby/src/internal/analytics/analytics_recorder_test.cc
new file mode 100644
index 00000000000..8127ff6f759
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/analytics/analytics_recorder_test.cc
@@ -0,0 +1,941 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/analytics/analytics_recorder.h"
+
+#include <string>
+#include <utility>
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "absl/time/time.h"
+#include "internal/platform/error_code_params.h"
+#include "internal/platform/error_code_recorder.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/logging.h"
+#include "internal/analytics/connection_attempt_metadata_params.h"
+#include "internal/proto/analytics/connections_log.pb.h"
+#include "proto/connections_enums.pb.h"
+
+namespace location {
+namespace nearby {
+namespace analytics {
+namespace {
+
+using ::location::nearby::analytics::proto::ConnectionsLog;
+using ::location::nearby::errorcode::proto::DISCONNECT;
+using ::location::nearby::errorcode::proto::DISCONNECT_NETWORK_FAILED;
+using ::location::nearby::errorcode::proto::INVALID_PARAMETER;
+using ::location::nearby::errorcode::proto::NULL_BLUETOOTH_DEVICE_NAME;
+using ::location::nearby::errorcode::proto::START_DISCOVERING;
+using ::location::nearby::errorcode::proto::START_EXTENDED_DISCOVERING_FAILED;
+using ::location::nearby::errorcode::proto::
+ TACHYON_SEND_MESSAGE_STATUS_EXCEPTION;
+using ::location::nearby::proto::connections::BLE;
+using ::location::nearby::proto::connections::BLUETOOTH;
+using ::location::nearby::proto::connections::CLIENT_SESSION;
+using ::location::nearby::proto::connections::ERROR_CODE;
+using ::location::nearby::proto::connections::EventType;
+using ::location::nearby::proto::connections::INCOMING;
+using ::location::nearby::proto::connections::INITIAL;
+using ::location::nearby::proto::connections::LOCAL_DISCONNECTION;
+using ::location::nearby::proto::connections::Medium;
+using ::location::nearby::proto::connections::RESULT_ERROR;
+using ::location::nearby::proto::connections::RESULT_SUCCESS;
+using ::location::nearby::proto::connections::START_STRATEGY_SESSION;
+using ::location::nearby::proto::connections::STOP_CLIENT_SESSION;
+using ::location::nearby::proto::connections::STOP_STRATEGY_SESSION;
+using ::location::nearby::proto::connections::SUCCESS;
+using ::location::nearby::proto::connections::UPGRADED;
+using ::location::nearby::proto::connections::WEB_RTC;
+using ::location::nearby::proto::connections::WIFI_LAN;
+using ::location::nearby::proto::connections::WIFI_LAN_MEDIUM_ERROR;
+using ::location::nearby::proto::connections::WIFI_LAN_SOCKET_CREATION;
+
+using ::testing::Contains;
+using ::protobuf_matchers::EqualsProto;
+using ::testing::proto::Partially;
+
+constexpr absl::Duration kDefaultTimeout = absl::Milliseconds(1000);
+
+class FakeEventLogger : public EventLogger {
+ public:
+ explicit FakeEventLogger(CountDownLatch& client_session_done_latch)
+ : client_session_done_latch_(client_session_done_latch) {}
+
+ void Log(const ConnectionsLog& connections_log) override {
+ EventType event_type = connections_log.event_type();
+ logged_event_types_.push_back(event_type);
+ if (event_type == CLIENT_SESSION) {
+ logged_client_session_count_++;
+ logged_client_session_ = connections_log.client_session();
+ }
+ if (event_type == ERROR_CODE) {
+ error_code_ = connections_log.error_code();
+ }
+ if (event_type == STOP_CLIENT_SESSION) {
+ client_session_done_latch_.CountDown();
+ }
+ }
+
+ int GetLoggedClientSessionCount() const {
+ return logged_client_session_count_;
+ }
+
+ const ConnectionsLog::ClientSession& GetLoggedClientSession() {
+ return logged_client_session_;
+ }
+
+ const ConnectionsLog::ErrorCode& GetErrorCode() { return error_code_; }
+
+ std::vector<EventType> GetLoggedEventTypes() { return logged_event_types_; }
+
+ private:
+ int logged_client_session_count_ = 0;
+ CountDownLatch& client_session_done_latch_;
+ ConnectionsLog::ClientSession logged_client_session_;
+ ConnectionsLog::ErrorCode error_code_;
+ std::vector<EventType> logged_event_types_;
+};
+
+TEST(AnalyticsRecorderTest, SessionOnlyLoggedOnceWorks) {
+ CountDownLatch client_session_done_latch(1);
+ FakeEventLogger event_logger(client_session_done_latch);
+ AnalyticsRecorder analytics_recorder(&event_logger);
+
+ analytics_recorder.LogSession();
+ analytics_recorder.LogSession();
+ analytics_recorder.LogSession();
+ analytics_recorder.LogSession();
+ ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
+
+ // Only called once.
+ EXPECT_EQ(event_logger.GetLoggedClientSessionCount(), 1);
+}
+
+TEST(AnalyticsRecorderTest, SetFieldsCorrectlyForNestedAdvertisingCalls) {
+ connections::Strategy strategy = connections::Strategy::kP2pStar;
+ std::vector<Medium> mediums = {BLE, BLUETOOTH};
+
+ CountDownLatch client_session_done_latch(1);
+ FakeEventLogger event_logger(client_session_done_latch);
+ AnalyticsRecorder analytics_recorder(&event_logger);
+
+ analytics_recorder.OnStartAdvertising(strategy, mediums);
+ analytics_recorder.OnStopAdvertising();
+ analytics_recorder.OnStartAdvertising(strategy, {BLUETOOTH});
+
+ analytics_recorder.LogSession();
+ ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
+
+ EXPECT_THAT(event_logger.GetLoggedClientSession(), Partially(EqualsProto(R"pb(
+ strategy_session <
+ strategy: P2P_STAR
+ role: ADVERTISER
+ advertising_phase <
+ medium: BLE
+ medium: BLUETOOTH
+ advertising_metadata <
+ supports_extended_ble_advertisements: false
+ connected_ap_frequency: 0
+ supports_nfc_technology: false
+ >
+ >
+ advertising_phase <
+ medium: BLUETOOTH
+ advertising_metadata <
+ supports_extended_ble_advertisements: false
+ connected_ap_frequency: 0
+ supports_nfc_technology: false
+ >
+ >
+ >)pb")));
+}
+
+TEST(AnalyticsRecorderTest, SetFieldsCorrectlyForNestedDiscoveryCalls) {
+ connections::Strategy strategy = connections::Strategy::kP2pStar;
+ std::vector<Medium> mediums = {BLE, BLUETOOTH};
+
+ CountDownLatch client_session_done_latch(1);
+ FakeEventLogger event_logger(client_session_done_latch);
+ AnalyticsRecorder analytics_recorder(&event_logger);
+
+ analytics_recorder.OnStartDiscovery(strategy, mediums, true, 1, false);
+ analytics_recorder.OnStopDiscovery();
+ analytics_recorder.OnEndpointFound(BLUETOOTH);
+ analytics_recorder.OnEndpointFound(BLE);
+ analytics_recorder.OnStartDiscovery(strategy, {BLUETOOTH}, true, 1, false);
+
+ analytics_recorder.LogSession();
+ ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
+
+ EXPECT_THAT(event_logger.GetLoggedClientSession(), Partially(EqualsProto(R"pb(
+ strategy_session <
+ strategy: P2P_STAR
+ role: DISCOVERER
+ discovery_phase <
+ medium: BLE
+ medium: BLUETOOTH
+ discovered_endpoint < medium: BLUETOOTH >
+ discovered_endpoint < medium: BLE >
+ discovery_metadata <
+ supports_extended_ble_advertisements: true
+ connected_ap_frequency: 1
+ supports_nfc_technology: false
+ >
+ >
+ discovery_phase <
+ medium: BLUETOOTH
+ discovery_metadata <
+ supports_extended_ble_advertisements: true
+ connected_ap_frequency: 1
+ supports_nfc_technology: false
+ >
+ >
+ >)pb")));
+}
+
+TEST(AnalyticsRecorderTest,
+ OneStrategySessionForMultipleRoundsOfDiscoveryAdvertising) {
+ connections::Strategy strategy = connections::Strategy::kP2pStar;
+ std::vector<Medium> mediums = {BLE, BLUETOOTH};
+
+ CountDownLatch client_session_done_latch(1);
+ FakeEventLogger event_logger(client_session_done_latch);
+ AnalyticsRecorder analytics_recorder(&event_logger);
+
+ analytics_recorder.OnStartAdvertising(strategy, mediums);
+ analytics_recorder.OnStartDiscovery(strategy, mediums);
+ analytics_recorder.OnStopAdvertising();
+ analytics_recorder.OnStopDiscovery();
+ analytics_recorder.OnStartAdvertising(strategy, mediums);
+ analytics_recorder.OnStopAdvertising();
+ analytics_recorder.OnStartDiscovery(strategy, mediums);
+ analytics_recorder.OnStopDiscovery();
+ analytics_recorder.OnStartDiscovery(strategy, mediums);
+ analytics_recorder.OnStartAdvertising(strategy, mediums);
+ analytics_recorder.OnStopDiscovery();
+ analytics_recorder.OnStopAdvertising();
+
+ analytics_recorder.LogSession();
+ ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
+
+ std::vector<EventType> event_types = event_logger.GetLoggedEventTypes();
+ EXPECT_THAT(event_types, Contains(START_STRATEGY_SESSION).Times(1));
+ EXPECT_THAT(event_types, Contains(STOP_STRATEGY_SESSION).Times(1));
+
+ EXPECT_THAT(event_logger.GetLoggedClientSession(), Partially(EqualsProto(R"pb(
+ strategy_session <
+ strategy: P2P_STAR
+ role: ADVERTISER
+ role: DISCOVERER
+ discovery_phase <
+ medium: BLE
+ medium: BLUETOOTH
+ discovery_metadata <
+ supports_extended_ble_advertisements: false
+ connected_ap_frequency: 0
+ supports_nfc_technology: false
+ >
+ >
+ discovery_phase <
+ medium: BLE
+ medium: BLUETOOTH
+ discovery_metadata <
+ supports_extended_ble_advertisements: false
+ connected_ap_frequency: 0
+ supports_nfc_technology: false
+ >
+ >
+ discovery_phase <
+ medium: BLE
+ medium: BLUETOOTH
+ discovery_metadata <
+ supports_extended_ble_advertisements: false
+ connected_ap_frequency: 0
+ supports_nfc_technology: false
+ >
+ >
+ advertising_phase <
+ medium: BLE
+ medium: BLUETOOTH
+ advertising_metadata <
+ supports_extended_ble_advertisements: false
+ connected_ap_frequency: 0
+ supports_nfc_technology: false
+ >
+ >
+ advertising_phase <
+ medium: BLE
+ medium: BLUETOOTH
+ advertising_metadata <
+ supports_extended_ble_advertisements: false
+ connected_ap_frequency: 0
+ supports_nfc_technology: false
+ >
+ >
+ advertising_phase <
+ medium: BLE
+ medium: BLUETOOTH
+ advertising_metadata <
+ supports_extended_ble_advertisements: false
+ connected_ap_frequency: 0
+ supports_nfc_technology: false
+ >
+ >
+ >)pb")));
+}
+
+TEST(AnalyticsRecorderTest, AdvertiserConnectionRequestsWorks) {
+ connections::Strategy strategy = connections::Strategy::kP2pStar;
+ std::vector<Medium> mediums = {BLE, BLUETOOTH};
+ std::string endpoint_id_0 = "endpoint_id_0";
+ std::string endpoint_id_1 = "endpoint_id_1";
+ std::string endpoint_id_2 = "endpoint_id_2";
+ std::string endpoint_id_3 = "endpoint_id_3";
+
+ CountDownLatch client_session_done_latch(1);
+ FakeEventLogger event_logger(client_session_done_latch);
+ AnalyticsRecorder analytics_recorder(&event_logger);
+
+ analytics_recorder.OnStartAdvertising(strategy, mediums);
+ analytics_recorder.OnConnectionRequestReceived(endpoint_id_0);
+ analytics_recorder.OnLocalEndpointAccepted(endpoint_id_0);
+ analytics_recorder.OnRemoteEndpointAccepted(endpoint_id_0);
+
+ analytics_recorder.OnConnectionRequestReceived(endpoint_id_1);
+ analytics_recorder.OnLocalEndpointAccepted(endpoint_id_1);
+ analytics_recorder.OnRemoteEndpointRejected(endpoint_id_1);
+
+ analytics_recorder.OnConnectionRequestReceived(endpoint_id_2);
+ analytics_recorder.OnLocalEndpointRejected(endpoint_id_2);
+ analytics_recorder.OnRemoteEndpointAccepted(endpoint_id_2);
+
+ analytics_recorder.OnConnectionRequestReceived(endpoint_id_3);
+ analytics_recorder.OnLocalEndpointRejected(endpoint_id_3);
+ analytics_recorder.OnRemoteEndpointRejected(endpoint_id_3);
+
+ analytics_recorder.LogSession();
+ ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
+
+ EXPECT_THAT(event_logger.GetLoggedClientSession(), Partially(EqualsProto(R"pb(
+ strategy_session <
+ strategy: P2P_STAR
+ role: ADVERTISER
+ advertising_phase <
+ medium: BLE
+ medium: BLUETOOTH
+ advertising_metadata <
+ supports_extended_ble_advertisements: false
+ connected_ap_frequency: 0
+ supports_nfc_technology: false
+ >
+ received_connection_request <
+ local_response: ACCEPTED
+ remote_response: ACCEPTED
+ >
+ received_connection_request <
+ local_response: ACCEPTED
+ remote_response: REJECTED
+ >
+ received_connection_request <
+ local_response: REJECTED
+ remote_response: ACCEPTED
+ >
+ received_connection_request <
+ local_response: REJECTED
+ remote_response: REJECTED
+ >
+ >
+ >)pb")));
+}
+
+TEST(AnalyticsRecorderTest, DiscoveryConnectionRequestsWorks) {
+ connections::Strategy strategy = connections::Strategy::kP2pStar;
+ std::vector<Medium> mediums = {BLE, BLUETOOTH};
+ std::string endpoint_id_0 = "endpoint_id_0";
+ std::string endpoint_id_1 = "endpoint_id_1";
+ std::string endpoint_id_2 = "endpoint_id_2";
+ std::string endpoint_id_3 = "endpoint_id_3";
+
+ CountDownLatch client_session_done_latch(1);
+ FakeEventLogger event_logger(client_session_done_latch);
+ AnalyticsRecorder analytics_recorder(&event_logger);
+
+ analytics_recorder.OnStartDiscovery(strategy, mediums);
+
+ analytics_recorder.OnConnectionRequestSent(endpoint_id_0);
+ analytics_recorder.OnLocalEndpointAccepted(endpoint_id_0);
+ analytics_recorder.OnRemoteEndpointAccepted(endpoint_id_0);
+
+ analytics_recorder.OnConnectionRequestSent(endpoint_id_1);
+ analytics_recorder.OnLocalEndpointAccepted(endpoint_id_1);
+ analytics_recorder.OnRemoteEndpointRejected(endpoint_id_1);
+
+ analytics_recorder.OnConnectionRequestSent(endpoint_id_2);
+ analytics_recorder.OnLocalEndpointRejected(endpoint_id_2);
+ analytics_recorder.OnRemoteEndpointAccepted(endpoint_id_2);
+
+ analytics_recorder.OnConnectionRequestSent(endpoint_id_3);
+ analytics_recorder.OnLocalEndpointRejected(endpoint_id_3);
+ analytics_recorder.OnRemoteEndpointRejected(endpoint_id_3);
+
+ analytics_recorder.LogSession();
+ ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
+
+ EXPECT_THAT(event_logger.GetLoggedClientSession(), Partially(EqualsProto(R"pb(
+ strategy_session <
+ strategy: P2P_STAR
+ role: DISCOVERER
+ discovery_phase <
+ medium: BLE
+ medium: BLUETOOTH
+ discovery_metadata <
+ supports_extended_ble_advertisements: false
+ connected_ap_frequency: 0
+ supports_nfc_technology: false
+ >
+ sent_connection_request <
+ local_response: ACCEPTED
+ remote_response: ACCEPTED
+ >
+ sent_connection_request <
+ local_response: ACCEPTED
+ remote_response: REJECTED
+ >
+ sent_connection_request <
+ local_response: REJECTED
+ remote_response: ACCEPTED
+ >
+ sent_connection_request <
+ local_response: REJECTED
+ remote_response: REJECTED
+ >
+ >
+ >)pb")));
+}
+
+TEST(AnalyticsRecorderTest,
+ AdvertiserUnfinishedConnectionRequestsIncludedAsIgnored) {
+ connections::Strategy strategy = connections::Strategy::kP2pStar;
+ std::vector<Medium> mediums = {BLE, BLUETOOTH};
+ std::string endpoint_id_0 = "endpoint_id_0";
+ std::string endpoint_id_1 = "endpoint_id_1";
+ std::string endpoint_id_2 = "endpoint_id_2";
+
+ CountDownLatch client_session_done_latch(1);
+ FakeEventLogger event_logger(client_session_done_latch);
+ AnalyticsRecorder analytics_recorder(&event_logger);
+
+ analytics_recorder.OnStartAdvertising(strategy, mediums);
+ // Ignored by local.
+ analytics_recorder.OnConnectionRequestReceived(endpoint_id_0);
+ analytics_recorder.OnRemoteEndpointAccepted(endpoint_id_0);
+
+ // Ignored by remote.
+ analytics_recorder.OnConnectionRequestReceived(endpoint_id_1);
+ analytics_recorder.OnLocalEndpointAccepted(endpoint_id_1);
+
+ // Ignored by both.
+ analytics_recorder.OnConnectionRequestReceived(endpoint_id_2);
+
+ analytics_recorder.LogSession();
+ ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
+
+ EXPECT_THAT(event_logger.GetLoggedClientSession(), Partially(EqualsProto(R"pb(
+ strategy_session <
+ strategy: P2P_STAR
+ role: ADVERTISER
+ advertising_phase <
+ medium: BLE
+ medium: BLUETOOTH
+ advertising_metadata <
+ supports_extended_ble_advertisements: false
+ connected_ap_frequency: 0
+ supports_nfc_technology: false
+ >
+ received_connection_request <
+ local_response: IGNORED
+ remote_response: ACCEPTED
+ >
+ received_connection_request <
+ local_response: ACCEPTED
+ remote_response: IGNORED
+ >
+ received_connection_request <
+ local_response: IGNORED
+ remote_response: IGNORED
+ >
+ >
+ >)pb")));
+}
+
+TEST(AnalyticsRecorderTest,
+ DiscovererUnfinishedConnectionRequestsIncludedAsIgnored) {
+ connections::Strategy strategy = connections::Strategy::kP2pStar;
+ std::vector<Medium> mediums = {BLE, BLUETOOTH};
+ std::string endpoint_id_0 = "endpoint_id_0";
+ std::string endpoint_id_1 = "endpoint_id_1";
+ std::string endpoint_id_2 = "endpoint_id_2";
+
+ CountDownLatch client_session_done_latch(1);
+ FakeEventLogger event_logger(client_session_done_latch);
+ AnalyticsRecorder analytics_recorder(&event_logger);
+
+ analytics_recorder.OnStartDiscovery(strategy, mediums);
+
+ // Ignored by local.
+ analytics_recorder.OnConnectionRequestSent(endpoint_id_0);
+ analytics_recorder.OnRemoteEndpointAccepted(endpoint_id_0);
+
+ // Ignored by remote.
+ analytics_recorder.OnConnectionRequestSent(endpoint_id_1);
+ analytics_recorder.OnLocalEndpointAccepted(endpoint_id_1);
+
+ // Ignored by both.
+ analytics_recorder.OnConnectionRequestSent(endpoint_id_2);
+
+ analytics_recorder.LogSession();
+ ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
+
+ EXPECT_THAT(event_logger.GetLoggedClientSession(), Partially(EqualsProto(R"pb(
+ strategy_session <
+ strategy: P2P_STAR
+ role: DISCOVERER
+ discovery_phase <
+ medium: BLE
+ medium: BLUETOOTH
+ discovery_metadata <
+ supports_extended_ble_advertisements: false
+ connected_ap_frequency: 0
+ supports_nfc_technology: false
+ >
+ sent_connection_request <
+ local_response: IGNORED
+ remote_response: ACCEPTED
+ >
+ sent_connection_request <
+ local_response: ACCEPTED
+ remote_response: IGNORED
+ >
+ sent_connection_request <
+ local_response: IGNORED
+ remote_response: IGNORED
+ >
+ >
+ >)pb")));
+}
+
+TEST(AnalyticsRecorderTest, SuccessfulIncomingConnectionAttempt) {
+ connections::Strategy strategy = connections::Strategy::kP2pStar;
+ std::vector<Medium> mediums = {BLE, BLUETOOTH};
+ std::string endpoint_id = "endpoint_id";
+ std::string connection_token = "";
+
+ CountDownLatch client_session_done_latch(1);
+ FakeEventLogger event_logger(client_session_done_latch);
+ AnalyticsRecorder analytics_recorder{&event_logger};
+
+ analytics_recorder.OnStartAdvertising(strategy, mediums);
+ analytics_recorder.OnIncomingConnectionAttempt(
+ INITIAL, BLUETOOTH, RESULT_SUCCESS, absl::Duration{}, connection_token,
+ nullptr);
+ analytics_recorder.OnStopAdvertising();
+
+ analytics_recorder.LogSession();
+ ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
+
+ EXPECT_THAT(event_logger.GetLoggedClientSession(), Partially(EqualsProto(R"pb(
+ strategy_session <
+ strategy: P2P_STAR
+ role: ADVERTISER
+ advertising_phase <
+ medium: BLE
+ medium: BLUETOOTH
+ advertising_metadata <
+ supports_extended_ble_advertisements: false
+ connected_ap_frequency: 0
+ supports_nfc_technology: false
+ >
+ >
+ connection_attempt <
+ type: INITIAL
+ direction: INCOMING
+ medium: BLUETOOTH
+ attempt_result: RESULT_SUCCESS
+ connection_token: ""
+ connection_attempt_metadata <
+ technology: CONNECTION_TECHNOLOGY_UNKNOWN_TECHNOLOGY
+ band: CONNECTION_BAND_UNKNOWN_BAND
+ frequency: -1
+ network_operator: ""
+ country_code: ""
+ is_tdls_used: false
+ try_counts: 0
+ wifi_hotspot_status: false
+ max_tx_speed: 0
+ max_rx_speed: 0
+ wifi_channel_width: -1
+ >
+ >
+ >)pb")));
+}
+
+TEST(AnalyticsRecorderTest,
+ FailedConnectionAttemptUpdatesConnectionRequestNotSent) {
+ connections::Strategy strategy = connections::Strategy::kP2pStar;
+ std::vector<Medium> mediums = {BLE, BLUETOOTH};
+ std::string endpoint_id = "endpoint_id";
+ std::string connection_token = "";
+
+ CountDownLatch client_session_done_latch(1);
+ FakeEventLogger event_logger(client_session_done_latch);
+ AnalyticsRecorder analytics_recorder(&event_logger);
+
+ auto connections_attempt_metadata_params =
+ analytics_recorder.BuildConnectionAttemptMetadataParams(
+ ::location::nearby::proto::connections::
+ CONNECTION_TECHNOLOGY_HOTSPOT_LOCALONLY,
+ ::location::nearby::proto::connections::
+ CONNECTION_BAND_WIFI_BAND_6GHZ,
+ /*frequency*/ 2400, /*try_count*/ 0, /*network_operator*/ {},
+ /*country_code*/ {}, /*is_tdls_used*/ false,
+ /*wifi_hotspot_enabled*/ false, /*max_wifi_tx_speed*/ 0,
+ /*max_wifi_rx_speed*/ 0, /*channel_width*/ 0);
+ analytics_recorder.OnStartDiscovery(strategy, mediums);
+ analytics_recorder.OnConnectionRequestSent(endpoint_id);
+ analytics_recorder.OnOutgoingConnectionAttempt(
+ endpoint_id, INITIAL, BLUETOOTH, RESULT_ERROR, absl::Duration{},
+ connection_token, connections_attempt_metadata_params.get());
+
+ analytics_recorder.LogSession();
+ ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
+
+ EXPECT_THAT(event_logger.GetLoggedClientSession(), Partially(EqualsProto(R"pb(
+ strategy_session <
+ strategy: P2P_STAR
+ role: DISCOVERER
+ discovery_phase <
+ medium: BLE
+ medium: BLUETOOTH
+ discovery_metadata <
+ supports_extended_ble_advertisements: false
+ connected_ap_frequency: 0
+ supports_nfc_technology: false
+ >
+ sent_connection_request <
+ local_response: NOT_SENT
+ remote_response: NOT_SENT
+ >
+ >
+ connection_attempt <
+ type: INITIAL
+ direction: OUTGOING
+ medium: BLUETOOTH
+ attempt_result: RESULT_ERROR
+ connection_token: ""
+ connection_attempt_metadata <
+ technology: CONNECTION_TECHNOLOGY_HOTSPOT_LOCALONLY
+ band: CONNECTION_BAND_WIFI_BAND_6GHZ
+ frequency: 2400
+ network_operator: ""
+ country_code: ""
+ is_tdls_used: false
+ try_counts: 0
+ wifi_hotspot_status: false
+ max_tx_speed: 0
+ max_rx_speed: 0
+ wifi_channel_width: 0
+ >
+ >
+ >)pb")));
+}
+
+TEST(AnalyticsRecorderTest, UnfinishedEstablishedConnectionsAddedAsUnfinished) {
+ connections::Strategy strategy = connections::Strategy::kP2pStar;
+ std::vector<Medium> mediums = {BLE, BLUETOOTH};
+ std::string endpoint_id = "endpoint_id";
+ std::string connection_token = "connection_token";
+
+ CountDownLatch client_session_done_latch(1);
+ FakeEventLogger event_logger(client_session_done_latch);
+ AnalyticsRecorder analytics_recorder(&event_logger);
+
+ analytics_recorder.OnStartAdvertising(strategy, mediums);
+ analytics_recorder.OnConnectionEstablished(endpoint_id, BLUETOOTH,
+ connection_token);
+ analytics_recorder.OnConnectionClosed(endpoint_id, BLUETOOTH, UPGRADED);
+ analytics_recorder.OnConnectionEstablished(endpoint_id, WIFI_LAN,
+ connection_token);
+
+ analytics_recorder.LogSession();
+ ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
+
+ EXPECT_THAT(event_logger.GetLoggedClientSession(), Partially(EqualsProto(R"pb(
+ strategy_session <
+ strategy: P2P_STAR
+ role: ADVERTISER
+ advertising_phase <
+ medium: BLE
+ medium: BLUETOOTH
+ advertising_metadata <
+ supports_extended_ble_advertisements: false
+ connected_ap_frequency: 0
+ supports_nfc_technology: false
+ >
+ >
+ established_connection <
+ medium: BLUETOOTH
+ disconnection_reason: UPGRADED
+ connection_token: "connection_token"
+ >
+ established_connection <
+ medium: WIFI_LAN
+ disconnection_reason: UNFINISHED
+ connection_token: "connection_token"
+ >
+ >)pb")));
+}
+
+TEST(AnalyticsRecorderTest, OutgoingPayloadUpgraded) {
+ connections::Strategy strategy = connections::Strategy::kP2pStar;
+ std::vector<Medium> mediums = {BLE, BLUETOOTH};
+ std::string endpoint_id = "endpoint_id";
+ std::int64_t payload_id = 123456789;
+ std::string connection_token = "connection_token";
+
+ CountDownLatch client_session_done_latch(1);
+ FakeEventLogger event_logger(client_session_done_latch);
+ AnalyticsRecorder analytics_recorder(&event_logger);
+
+ analytics_recorder.OnStartAdvertising(strategy, mediums);
+ analytics_recorder.OnConnectionEstablished(endpoint_id, BLUETOOTH,
+ connection_token);
+ analytics_recorder.OnOutgoingPayloadStarted(
+ {endpoint_id}, payload_id, connections::Payload::Type::kFile, 50);
+ analytics_recorder.OnPayloadChunkSent(endpoint_id, payload_id, 10);
+ analytics_recorder.OnPayloadChunkSent(endpoint_id, payload_id, 10);
+ analytics_recorder.OnConnectionClosed(endpoint_id, BLUETOOTH, UPGRADED);
+ analytics_recorder.OnConnectionEstablished(endpoint_id, WIFI_LAN,
+ connection_token);
+ analytics_recorder.OnPayloadChunkSent(endpoint_id, payload_id, 10);
+ analytics_recorder.OnPayloadChunkSent(endpoint_id, payload_id, 10);
+ analytics_recorder.OnPayloadChunkSent(endpoint_id, payload_id, 10);
+ analytics_recorder.OnOutgoingPayloadDone(endpoint_id, payload_id, SUCCESS);
+ analytics_recorder.OnConnectionClosed(endpoint_id, WIFI_LAN,
+ LOCAL_DISCONNECTION);
+
+ analytics_recorder.LogSession();
+ ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
+
+ EXPECT_THAT(event_logger.GetLoggedClientSession(), Partially(EqualsProto(R"pb(
+ strategy_session <
+ strategy: P2P_STAR
+ role: ADVERTISER
+ advertising_phase <
+ medium: BLE
+ medium: BLUETOOTH
+ advertising_metadata <
+ supports_extended_ble_advertisements: false
+ connected_ap_frequency: 0
+ supports_nfc_technology: false
+ >
+ >
+ established_connection <
+ medium: BLUETOOTH
+ sent_payload <
+ type: FILE
+ total_size_bytes: 50
+ num_bytes_transferred: 20
+ num_chunks: 2
+ status: MOVED_TO_NEW_MEDIUM
+ >
+ disconnection_reason: UPGRADED
+ connection_token: "connection_token"
+ >
+ established_connection <
+ medium: WIFI_LAN
+ sent_payload <
+ type: FILE
+ total_size_bytes: 50
+ num_bytes_transferred: 30
+ num_chunks: 3
+ status: SUCCESS
+ >
+ disconnection_reason: LOCAL_DISCONNECTION
+ connection_token: "connection_token"
+ >
+ >)pb")));
+}
+
+TEST(AnalyticsRecorderTest, UpgradeAttemptWorks) {
+ connections::Strategy strategy = connections::Strategy::kP2pStar;
+ std::vector<Medium> mediums = {BLE, BLUETOOTH};
+ std::string endpoint_id = "endpoint_id";
+ std::string endpoint_id_1 = "endpoint_id_1";
+ std::string endpoint_id_2 = "endpoint_id_2";
+ std::string connection_token = "connection_token";
+
+ CountDownLatch client_session_done_latch(1);
+ FakeEventLogger event_logger(client_session_done_latch);
+ AnalyticsRecorder analytics_recorder(&event_logger);
+
+ analytics_recorder.OnStartAdvertising(strategy, mediums);
+
+ analytics_recorder.OnBandwidthUpgradeStarted(endpoint_id, BLE, WIFI_LAN,
+ INCOMING, connection_token);
+
+ analytics_recorder.OnBandwidthUpgradeStarted(
+ endpoint_id_1, BLUETOOTH, WIFI_LAN, INCOMING, connection_token);
+ // Error to upgrade.
+ analytics_recorder.OnBandwidthUpgradeError(endpoint_id, WIFI_LAN_MEDIUM_ERROR,
+ WIFI_LAN_SOCKET_CREATION);
+ // Success to upgrade.
+ analytics_recorder.OnBandwidthUpgradeSuccess(endpoint_id_1);
+ // Upgrade is unfinished.
+ analytics_recorder.OnBandwidthUpgradeStarted(
+ endpoint_id_2, BLUETOOTH, WIFI_LAN, INCOMING, connection_token);
+
+ analytics_recorder.LogSession();
+ ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
+
+ EXPECT_THAT(event_logger.GetLoggedClientSession(), Partially(EqualsProto(R"pb(
+ strategy_session <
+ strategy: P2P_STAR
+ role: ADVERTISER
+ advertising_phase <
+ medium: BLE
+ medium: BLUETOOTH
+ advertising_metadata <
+ supports_extended_ble_advertisements: false
+ connected_ap_frequency: 0
+ supports_nfc_technology: false
+ >
+ >
+ upgrade_attempt <
+ direction: INCOMING
+ from_medium: BLE
+ to_medium: WIFI_LAN
+ upgrade_result: WIFI_LAN_MEDIUM_ERROR
+ error_stage: WIFI_LAN_SOCKET_CREATION
+ connection_token: "connection_token"
+ >
+ upgrade_attempt <
+ direction: INCOMING
+ from_medium: BLUETOOTH
+ to_medium: WIFI_LAN
+ upgrade_result: UPGRADE_RESULT_SUCCESS
+ error_stage: UPGRADE_SUCCESS
+ connection_token: "connection_token"
+ >
+ upgrade_attempt {
+ direction: INCOMING
+ from_medium: BLUETOOTH
+ to_medium: WIFI_LAN
+ upgrade_result: UNFINISHED_ERROR
+ error_stage: UPGRADE_UNFINISHED
+ connection_token: "connection_token"
+ }
+ >)pb")));
+}
+
+TEST(AnalyticsRecorderTest, SetErrorCodeFieldsCorrectly) {
+ connections::Strategy strategy = connections::Strategy::kP2pStar;
+ std::vector<Medium> mediums = {WEB_RTC};
+ std::string connection_token = "connection_token";
+
+ CountDownLatch client_session_done_latch(1);
+ FakeEventLogger event_logger(client_session_done_latch);
+ AnalyticsRecorder analytics_recorder(&event_logger);
+ analytics_recorder.OnStartDiscovery(strategy, mediums);
+
+ ErrorCodeParams error_code_params = ErrorCodeRecorder::BuildErrorCodeParams(
+ WEB_RTC, DISCONNECT, DISCONNECT_NETWORK_FAILED,
+ TACHYON_SEND_MESSAGE_STATUS_EXCEPTION, "", connection_token);
+ analytics_recorder.OnErrorCode(error_code_params);
+
+ analytics_recorder.LogSession();
+ ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
+
+ EXPECT_THAT(event_logger.GetErrorCode(), Partially(EqualsProto(R"pb(
+ medium: WEB_RTC
+ event: DISCONNECT
+ description: TACHYON_SEND_MESSAGE_STATUS_EXCEPTION
+ disconnect_error: DISCONNECT_NETWORK_FAILED
+ connection_token: "connection_token"
+ )pb")));
+}
+
+TEST(AnalyticsRecorderTest, SetErrorCodeFieldsCorrectlyForUnknownDescription) {
+ connections::Strategy strategy = connections::Strategy::kP2pStar;
+ std::vector<Medium> mediums = {BLUETOOTH};
+ std::string connection_token = "connection_token";
+
+ CountDownLatch client_session_done_latch(1);
+ FakeEventLogger event_logger(client_session_done_latch);
+ AnalyticsRecorder analytics_recorder(&event_logger);
+ analytics_recorder.OnStartDiscovery(strategy, mediums);
+
+ ErrorCodeParams error_code_params;
+ // Skip setting error_code_params.description
+ error_code_params.medium = BLUETOOTH;
+ error_code_params.event = START_DISCOVERING;
+ error_code_params.start_discovering_error = START_EXTENDED_DISCOVERING_FAILED;
+ error_code_params.connection_token = connection_token;
+ analytics_recorder.OnErrorCode(error_code_params);
+
+ analytics_recorder.LogSession();
+ ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
+
+ EXPECT_THAT(event_logger.GetErrorCode(), Partially(EqualsProto(R"pb(
+ medium: BLUETOOTH
+ event: START_DISCOVERING
+ description: UNKNOWN
+ start_discovering_error: START_EXTENDED_DISCOVERING_FAILED
+ connection_token: "connection_token"
+ )pb")));
+}
+
+TEST(AnalyticsRecorderTest, SetErrorCodeFieldsCorrectlyForCommonError) {
+ connections::Strategy strategy = connections::Strategy::kP2pStar;
+ std::vector<Medium> mediums = {BLUETOOTH};
+ std::string connection_token = "connection_token";
+
+ CountDownLatch client_session_done_latch(1);
+ FakeEventLogger event_logger(client_session_done_latch);
+ AnalyticsRecorder analytics_recorder(&event_logger);
+ analytics_recorder.OnStartDiscovery(strategy, mediums);
+
+ ErrorCodeParams error_code_params = ErrorCodeRecorder::BuildErrorCodeParams(
+ BLUETOOTH, START_DISCOVERING, INVALID_PARAMETER,
+ NULL_BLUETOOTH_DEVICE_NAME, "", connection_token);
+ analytics_recorder.OnErrorCode(error_code_params);
+
+ analytics_recorder.LogSession();
+ ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
+
+ EXPECT_THAT(event_logger.GetErrorCode(), Partially(EqualsProto(R"pb(
+ medium: BLUETOOTH
+ event: START_DISCOVERING
+ description: NULL_BLUETOOTH_DEVICE_NAME
+ common_error: INVALID_PARAMETER
+ connection_token: "connection_token"
+ )pb")));
+}
+
+} // namespace
+} // namespace analytics
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/analytics/connection_attempt_metadata_params.h b/chromium/third_party/nearby/src/internal/analytics/connection_attempt_metadata_params.h
new file mode 100644
index 00000000000..47a208afb19
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/analytics/connection_attempt_metadata_params.h
@@ -0,0 +1,44 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef ANALYTICS_CONNECTION_ATTEMPT_METADATA_PARAMS_H_
+#define ANALYTICS_CONNECTION_ATTEMPT_METADATA_PARAMS_H_
+
+#include "proto/connections_enums.pb.h"
+
+namespace location {
+namespace nearby {
+
+// A struct to construct ConnectionAttemptMetadata for the analytics recorder.
+struct ConnectionAttemptMetadataParams {
+ location::nearby::proto::connections::ConnectionTechnology technology =
+ location::nearby::proto::connections::
+ CONNECTION_TECHNOLOGY_UNKNOWN_TECHNOLOGY;
+ location::nearby::proto::connections::ConnectionBand band =
+ location::nearby::proto::connections::CONNECTION_BAND_UNKNOWN_BAND;
+ int frequency = -1; // -1 as Unknown.
+ int try_count = 0;
+ std::string network_operator = {};
+ std::string country_code = {};
+ bool is_tdls_used = false;
+ bool wifi_hotspot_enabled = false;
+ int max_wifi_tx_speed = 0;
+ int max_wifi_rx_speed = 0;
+ int channel_width = -1; // -1 as Unknown.
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // ANALYTICS_CONNECTION_ATTEMPT_METADATA_PARAMS_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/BUILD b/chromium/third_party/nearby/src/internal/platform/BUILD
new file mode 100644
index 00000000000..a8ab755bcaa
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/BUILD
@@ -0,0 +1,396 @@
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+load("//tools/build_defs/cc:cc_fake_binary.bzl", "cc_fake_binary")
+
+licenses(["notice"])
+
+cc_library(
+ name = "base",
+ srcs = [
+ "base64_utils.cc",
+ "bluetooth_utils.cc",
+ "input_stream.cc",
+ "nsd_service_info.cc",
+ "prng.cc",
+ ],
+ hdrs = [
+ "base64_utils.h",
+ "bluetooth_utils.h",
+ "byte_array.h",
+ "callable.h",
+ "exception.h",
+ "feature_flags.h",
+ "input_stream.h",
+ "listeners.h",
+ "nsd_service_info.h",
+ "output_stream.h",
+ "payload_id.h",
+ "prng.h",
+ "runnable.h",
+ "socket.h",
+ "types.h",
+ ],
+ copts = ["-DCORE_ADAPTER_DLL"],
+ defines = ["NO_WEBRTC"],
+ visibility = [
+ "//connections:__subpackages__",
+ "//internal/analytics:__subpackages__",
+ "//internal/platform:__subpackages__",
+ "//internal/platform/implementation:__subpackages__",
+ "//internal/proto/analytics:__subpackages__",
+ "//third_party/nearby/cpp/cal:__subpackages__",
+ ],
+ deps = [
+ "@com_google_absl//absl/container:flat_hash_map",
+ "@com_google_absl//absl/meta:type_traits",
+ "@com_google_absl//absl/strings",
+ "@com_google_absl//absl/strings:str_format",
+ "@com_google_absl//absl/synchronization",
+ "@com_google_absl//absl/time",
+ ],
+)
+
+cc_library(
+ name = "util",
+ srcs = [
+ "base_input_stream.cc",
+ "base_pipe.cc",
+ "byte_utils.cc",
+ ],
+ hdrs = [
+ "base_input_stream.h",
+ "base_mutex_lock.h",
+ "base_pipe.h",
+ "byte_utils.h",
+ ],
+ defines = ["NO_WEBRTC"],
+ visibility = [
+ "//connections:__subpackages__",
+ "//internal/platform:__pkg__",
+ "//internal/platform/implementation:__subpackages__",
+ ],
+ deps = [
+ ":base",
+ "//internal/platform/implementation:types",
+ "@com_google_absl//absl/base:core_headers",
+ "@com_google_absl//absl/strings:str_format",
+ ],
+)
+
+cc_library(
+ name = "logging",
+ hdrs = [
+ "logging.h",
+ ],
+ copts = ["-DCORE_ADAPTER_DLL"],
+ defines = ["NO_WEBRTC"],
+ visibility = [
+ "//connections:__subpackages__",
+ "//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
+ "//internal/analytics:__subpackages__",
+ "//internal/platform:__subpackages__",
+ "//internal/proto/analytics:__subpackages__",
+ ],
+ deps = [
+ "//internal/platform/implementation:platform",
+ "//internal/platform/implementation:types",
+ "@com_google_glog//:glog",
+ ],
+)
+
+cc_library(
+ name = "cancellation_flag",
+ srcs = [
+ "cancellation_flag.cc",
+ ],
+ hdrs = [
+ "cancellation_flag.h",
+ "cancellation_flag_listener.h",
+ ],
+ defines = ["NO_WEBRTC"],
+ visibility = [
+ "//connections/implementation:__subpackages__",
+ "//internal/platform:__pkg__",
+ "//internal/platform/implementation:__subpackages__",
+ ],
+ deps = [
+ ":base",
+ ":util",
+ "@com_google_absl//absl/container:flat_hash_set",
+ "@com_google_absl//absl/synchronization",
+ ],
+)
+
+cc_library(
+ name = "error_code_recorder",
+ srcs = [
+ "error_code_recorder.cc",
+ ],
+ hdrs = [
+ "error_code_params.h",
+ "error_code_recorder.h",
+ ],
+ defines = ["NO_WEBRTC"],
+ visibility = [
+ "//connections/implementation:__subpackages__",
+ "//internal/analytics:__subpackages__",
+ "//internal/platform/implementation:__subpackages__",
+ ],
+ deps = [
+ ":logging",
+ "//proto:connections_enums_cc_proto",
+ "//proto/errorcode:error_code_enums_cc_proto",
+ ],
+)
+
+cc_library(
+ name = "test_util",
+ testonly = True,
+ srcs = [
+ "medium_environment.cc",
+ ],
+ hdrs = [
+ "medium_environment.h",
+ ],
+ defines = ["NO_WEBRTC"],
+ visibility = [
+ "//connections:__subpackages__",
+ "//internal/platform:__pkg__",
+ "//internal/platform/implementation:__subpackages__",
+ ],
+ deps = [
+ ":base",
+ ":logging",
+ "//internal/platform:types",
+ "//internal/platform/implementation:comm",
+ "@com_google_absl//absl/container:flat_hash_map",
+ "@com_google_absl//absl/strings",
+ ],
+)
+
+cc_test(
+ name = "platform_base_test",
+ srcs = [
+ "bluetooth_utils_test.cc",
+ "byte_array_test.cc",
+ "feature_flags_test.cc",
+ "prng_test.cc",
+ ],
+ defines = ["NO_WEBRTC"],
+ deps = [
+ ":base",
+ ":test_util",
+ "//internal/platform/implementation/g3", # build_cleaner: keep
+ "@com_github_protobuf_matchers//protobuf-matchers",
+ "@com_google_googletest//:gtest_main",
+ ],
+)
+
+cc_test(
+ name = "platform_util_test",
+ srcs = [
+ "byte_utils_test.cc",
+ ],
+ defines = ["NO_WEBRTC"],
+ deps = [
+ ":base",
+ ":util",
+ "@com_github_protobuf_matchers//protobuf-matchers",
+ "@com_google_googletest//:gtest_main",
+ ],
+)
+
+cc_test(
+ name = "cancellation_flag_test",
+ srcs = [
+ "cancellation_flag_test.cc",
+ ],
+ defines = ["NO_WEBRTC"],
+ deps = [
+ ":base",
+ ":cancellation_flag",
+ ":test_util",
+ "//internal/platform/implementation/g3", # build_cleaner: keep
+ "@com_github_protobuf_matchers//protobuf-matchers",
+ "@com_google_googletest//:gtest_main",
+ ],
+)
+
+cc_test(
+ name = "error_code_recorder_test",
+ srcs = [
+ "error_code_recorder_test.cc",
+ ],
+ defines = ["NO_WEBRTC"],
+ deps = [
+ ":error_code_recorder",
+ ":test_util",
+ "//internal/platform/implementation/g3", # build_cleaner: keep
+ "@com_github_protobuf_matchers//protobuf-matchers",
+ "@com_google_googletest//:gtest_main",
+ ],
+)
+
+cc_library(
+ name = "types",
+ srcs = [
+ "monitored_runnable.cc",
+ "pending_job_registry.cc",
+ "pipe.cc",
+ ],
+ hdrs = [
+ "atomic_boolean.h",
+ "atomic_reference.h",
+ "cancelable.h",
+ "cancelable_alarm.h",
+ "cancellable_task.h",
+ "condition_variable.h",
+ "core_config.h",
+ "count_down_latch.h",
+ "crypto.h",
+ "file.h",
+ "future.h",
+ "lockable.h",
+ "logging.h",
+ "monitored_runnable.h",
+ "multi_thread_executor.h",
+ "mutex.h",
+ "mutex_lock.h",
+ "pending_job_registry.h",
+ "pipe.h",
+ "scheduled_executor.h",
+ "settable_future.h",
+ "single_thread_executor.h",
+ "submittable_executor.h",
+ "system_clock.h",
+ "thread_check_callable.h",
+ "thread_check_runnable.h",
+ ],
+ defines = ["NO_WEBRTC"],
+ visibility = [
+ "//connections:__subpackages__",
+ "//internal/analytics:__subpackages__",
+ "//internal/platform:__pkg__",
+ "//internal/platform/implementation/ios:__subpackages__",
+ "//internal/platform/implementation/windows:__subpackages__",
+ ],
+ deps = [
+ ":base",
+ ":logging",
+ ":util",
+ "//internal/platform/implementation:platform",
+ "//internal/platform/implementation:types",
+ "@com_google_absl//absl/base:core_headers",
+ "@com_google_absl//absl/time",
+ ],
+)
+
+cc_library(
+ name = "comm",
+ srcs = [
+ "ble.cc",
+ "bluetooth_classic.cc",
+ "file.cc",
+ "wifi_lan.cc",
+ ],
+ hdrs = [
+ "ble.h",
+ "bluetooth_adapter.h",
+ "bluetooth_classic.h",
+ "wifi_lan.h",
+ ],
+ copts = ["-DCORE_ADAPTER_DLL"],
+ defines = ["NO_WEBRTC"],
+ visibility = [
+ "//connections:__subpackages__",
+ "//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
+ "//internal/analytics:__subpackages__",
+ "//internal/platform:__pkg__",
+ ],
+ deps = [
+ ":logging",
+ ":types",
+ "//internal/platform:base",
+ "//internal/platform:cancellation_flag",
+ "//internal/platform/implementation:comm",
+ "//internal/platform/implementation:platform",
+ "@com_google_absl//absl/container:flat_hash_map",
+ "@com_google_absl//absl/strings",
+ ],
+)
+
+cc_test(
+ name = "public_test",
+ size = "small",
+ timeout = "moderate",
+ srcs = [
+ "atomic_boolean_test.cc",
+ "atomic_reference_test.cc",
+ "ble_test.cc",
+ "bluetooth_adapter_test.cc",
+ "bluetooth_classic_test.cc",
+ "cancelable_alarm_test.cc",
+ "condition_variable_test.cc",
+ "count_down_latch_test.cc",
+ "crypto_test.cc",
+ "future_test.cc",
+ "logging_test.cc",
+ "multi_thread_executor_test.cc",
+ "mutex_test.cc",
+ "pipe_test.cc",
+ "scheduled_executor_test.cc",
+ "single_thread_executor_test.cc",
+ "wifi_lan_test.cc",
+ ],
+ copts = ["-DCORE_ADAPTER_DLL"],
+ defines = ["NO_WEBRTC"],
+ shard_count = 16,
+ deps = [
+ ":comm",
+ ":logging",
+ ":types",
+ "//internal/platform:base",
+ "//internal/platform:test_util",
+ "//internal/platform/implementation/g3", # build_cleaner: keep
+ "@com_github_protobuf_matchers//protobuf-matchers",
+ "@com_google_absl//absl/strings",
+ "@com_google_absl//absl/synchronization",
+ "@com_google_absl//absl/time",
+ "@com_google_googletest//:gtest_main",
+ ],
+)
+
+cc_fake_binary(
+ name = "thread_check_nocompile",
+ srcs = ["thread_check_nocompile.cc"],
+ deps = [
+ ":types",
+ "@com_google_absl//absl/time",
+ ],
+)
+
+py_test(
+ name = "thread_check_nocompile_test",
+ size = "large",
+ srcs = ["thread_check_nocompile_test.py"],
+ data = ["thread_check_nocompile"],
+ python_version = "PY3",
+ srcs_version = "PY3",
+ tags = ["non_compile_test"],
+ deps = [
+ "//testing/pybase",
+ "//testing/pybase:fake_target_util",
+ ],
+)
diff --git a/chromium/third_party/nearby/src/internal/platform/atomic_boolean.h b/chromium/third_party/nearby/src/internal/platform/atomic_boolean.h
new file mode 100644
index 00000000000..7bd991a75cb
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/atomic_boolean.h
@@ -0,0 +1,50 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_ATOMIC_BOOLEAN_H_
+#define PLATFORM_PUBLIC_ATOMIC_BOOLEAN_H_
+
+#include <memory>
+
+#include "internal/platform/implementation/atomic_boolean.h"
+#include "internal/platform/implementation/platform.h"
+
+namespace location {
+namespace nearby {
+
+// A boolean value that may be updated atomically.
+// See documentation in
+// cpp/platform/api/atomic_boolean.h
+class AtomicBoolean final : public api::AtomicBoolean {
+ public:
+ using Platform = api::ImplementationPlatform;
+ explicit AtomicBoolean(bool value = false)
+ : impl_(Platform::CreateAtomicBoolean(value)) {}
+ ~AtomicBoolean() override = default;
+ AtomicBoolean(AtomicBoolean&&) = default;
+ AtomicBoolean& operator=(AtomicBoolean&&) = default;
+
+ bool Get() const override { return impl_->Get(); }
+ bool Set(bool value) override { return impl_->Set(value); }
+
+ explicit operator bool() const { return Get(); }
+
+ private:
+ std::unique_ptr<api::AtomicBoolean> impl_;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_ATOMIC_BOOLEAN_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/atomic_boolean_test.cc b/chromium/third_party/nearby/src/internal/platform/atomic_boolean_test.cc
new file mode 100644
index 00000000000..8c4ef8beefe
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/atomic_boolean_test.cc
@@ -0,0 +1,50 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/atomic_boolean.h"
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+
+namespace location {
+namespace nearby {
+namespace {
+
+TEST(AtomicBooleanTest, SetReturnsPrevoiusValue) {
+ AtomicBoolean value(false);
+ EXPECT_FALSE(value.Set(true));
+ EXPECT_TRUE(value.Set(true));
+}
+
+TEST(AtomicBooleanTest, GetReturnsWhatWasSet) {
+ AtomicBoolean value(false);
+ EXPECT_FALSE(value.Set(true));
+ EXPECT_TRUE(value.Get());
+}
+
+TEST(AtomicBooleanTest, ImplicitGetTrueValue) {
+ AtomicBoolean value(true);
+
+ EXPECT_TRUE(value);
+}
+
+TEST(AtomicBooleanTest, ImplicitGetFalseValue) {
+ AtomicBoolean value(false);
+
+ EXPECT_FALSE(value);
+}
+} // namespace
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/atomic_reference.h b/chromium/third_party/nearby/src/internal/platform/atomic_reference.h
new file mode 100644
index 00000000000..c2b014bce9a
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/atomic_reference.h
@@ -0,0 +1,87 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_ATOMIC_REFERENCE_H_
+#define PLATFORM_PUBLIC_ATOMIC_REFERENCE_H_
+
+#include <memory>
+#include <type_traits>
+
+#include "internal/platform/implementation/atomic_reference.h"
+#include "internal/platform/implementation/platform.h"
+#include "internal/platform/mutex.h"
+#include "internal/platform/mutex_lock.h"
+
+namespace location {
+namespace nearby {
+
+// An object reference that may be updated atomically.
+template <typename, typename = void>
+class AtomicReference;
+
+// Platform-based atomic type, for something convertible to std::uint32_t.
+template <typename T>
+class AtomicReference<T, std::enable_if_t<sizeof(T) <= sizeof(std::uint32_t) &&
+ std::is_trivially_copyable<T>::value>>
+ final {
+ public:
+ using Platform = api::ImplementationPlatform;
+ explicit AtomicReference(T value)
+ : impl_(Platform::CreateAtomicUint32(static_cast<std::uint32_t>(value))) {
+ }
+ ~AtomicReference() = default;
+ AtomicReference(AtomicReference&&) = default;
+ AtomicReference& operator=(AtomicReference&&) = default;
+
+ T Get() const { return static_cast<T>(impl_->Get()); }
+ void Set(T value) { impl_->Set(static_cast<std::uint32_t>(value)); }
+
+ private:
+ std::unique_ptr<api::AtomicUint32> impl_;
+};
+
+// Atomic type that is using Platform mutex to provide atomicity.
+// Supports any copyable type.
+template <typename T>
+class AtomicReference<T,
+ std::enable_if_t<(sizeof(T) > sizeof(std::uint32_t) ||
+ !std::is_trivially_copyable<T>::value)>>
+ final {
+ public:
+ explicit AtomicReference(T value) {
+ MutexLock lock(&mutex_);
+ value_ = std::move(value);
+ }
+ void Set(T value) {
+ MutexLock lock(&mutex_);
+ value_ = std::move(value);
+ }
+ T Get() const& {
+ MutexLock lock(&mutex_);
+ return value_;
+ }
+ T&& Get() const&& {
+ MutexLock lock(&mutex_);
+ return std::move(value_);
+ }
+
+ private:
+ mutable Mutex mutex_;
+ T value_;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_ATOMIC_REFERENCE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/atomic_reference_test.cc b/chromium/third_party/nearby/src/internal/platform/atomic_reference_test.cc
new file mode 100644
index 00000000000..8c83037f71c
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/atomic_reference_test.cc
@@ -0,0 +1,89 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/atomic_reference.h"
+
+#include "gtest/gtest.h"
+
+namespace location {
+namespace nearby {
+namespace {
+
+struct BigSizedStruct {
+ int data[100]{};
+};
+
+enum TestEnum {
+ kValue1 = 1,
+ kValue2 = 2,
+};
+
+enum class ScopedTestEnum {
+ kValue1 = 1,
+ kValue2 = 2,
+};
+
+bool operator==(const BigSizedStruct& a, const BigSizedStruct& b) {
+ return memcmp(a.data, b.data, sizeof(BigSizedStruct::data)) == 0;
+}
+
+bool operator!=(const BigSizedStruct& a, const BigSizedStruct& b) {
+ return !(a == b);
+}
+
+} // namespace
+
+TEST(AtomicReferenceTest, SupportIntegralTypes) {
+ AtomicReference<int> atomic_ref({});
+ atomic_ref.Set(5);
+ EXPECT_EQ(atomic_ref.Get(), 5);
+}
+
+TEST(AtomicReferenceTest, SupportEnum) {
+ AtomicReference<TestEnum> atomic_ref({});
+ atomic_ref.Set(TestEnum::kValue1);
+ EXPECT_EQ(atomic_ref.Get(), TestEnum::kValue1);
+}
+
+TEST(AtomicReferenceTest, SupportScopedEnum) {
+ AtomicReference<ScopedTestEnum> atomic_ref({});
+ atomic_ref.Set(ScopedTestEnum::kValue1);
+ EXPECT_EQ(atomic_ref.Get(), ScopedTestEnum::kValue1);
+}
+
+TEST(AtomicReferenceTest, SetTakesCopyOfValue) {
+ // Default constructor is zero-initalizing all data in BigSizedStruct.
+ BigSizedStruct v1;
+ AtomicReference<BigSizedStruct> atomic_ref({});
+ v1.data[0] = 5; // Changing value before calling set() will affect stored
+ v1.data[7] = 3; // value.
+ atomic_ref.Set(v1);
+ v1.data[1] = 6; // Changing value after calling set() will not affect stored
+ v1.data[5] = 4; // value.
+ BigSizedStruct v2 = atomic_ref.Get();
+ EXPECT_NE(v1, v2);
+ v1.data[1] = 0;
+ v1.data[5] = 0;
+ EXPECT_EQ(v2, v1);
+}
+
+TEST(AtomicReferenceTest, SupportObjects) {
+ std::string s{"test"};
+ AtomicReference<std::string> atomic_ref({});
+ atomic_ref.Set(s);
+ EXPECT_EQ(s, atomic_ref.Get());
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/base64_utils.cc b/chromium/third_party/nearby/src/internal/platform/base64_utils.cc
new file mode 100644
index 00000000000..57ae3efc8a6
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/base64_utils.cc
@@ -0,0 +1,41 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/base64_utils.h"
+
+#include "absl/strings/escaping.h"
+#include "internal/platform/byte_array.h"
+
+namespace location {
+namespace nearby {
+
+std::string Base64Utils::Encode(const ByteArray& bytes) {
+ std::string base64_string;
+
+ absl::WebSafeBase64Escape(std::string(bytes), &base64_string);
+
+ return base64_string;
+}
+
+ByteArray Base64Utils::Decode(absl::string_view base64_string) {
+ std::string decoded_string;
+ if (!absl::WebSafeBase64Unescape(base64_string, &decoded_string)) {
+ return ByteArray();
+ }
+
+ return ByteArray(decoded_string.data(), decoded_string.size());
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/base64_utils.h b/chromium/third_party/nearby/src/internal/platform/base64_utils.h
new file mode 100644
index 00000000000..e3f6a4d8ff7
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/base64_utils.h
@@ -0,0 +1,33 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_BASE_BASE64_UTILS_H_
+#define PLATFORM_BASE_BASE64_UTILS_H_
+
+#include "absl/strings/string_view.h"
+#include "internal/platform/byte_array.h"
+
+namespace location {
+namespace nearby {
+
+class Base64Utils {
+ public:
+ static std::string Encode(const ByteArray& bytes);
+ static ByteArray Decode(absl::string_view base64_string);
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_BASE_BASE64_UTILS_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/base_input_stream.cc b/chromium/third_party/nearby/src/internal/platform/base_input_stream.cc
new file mode 100644
index 00000000000..0bbe4b20c24
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/base_input_stream.cc
@@ -0,0 +1,99 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/base_input_stream.h"
+
+namespace location {
+namespace nearby {
+
+ExceptionOr<ByteArray> BaseInputStream::Read(std::int64_t size) {
+ if (!IsAvailable(size)) {
+ return ExceptionOr<ByteArray>{Exception::kIo};
+ }
+
+ ByteArray read_bytes{static_cast<size_t>(size)};
+ if (read_bytes.CopyAt(/*offset=*/0, buffer_,
+ /*source_offset=*/position_)) {
+ position_ += size;
+ return ExceptionOr<ByteArray>{read_bytes};
+ } else {
+ return ExceptionOr<ByteArray>{Exception::kIo};
+ }
+}
+
+std::uint8_t BaseInputStream::ReadUint8() {
+ constexpr int byte_size = sizeof(std::uint8_t);
+ ByteArray read_bytes = ReadBytes(byte_size);
+ if (read_bytes.Empty() || read_bytes.size() != byte_size) {
+ return -1;
+ }
+
+ return read_bytes.data()[0];
+}
+
+std::uint16_t BaseInputStream::ReadUint16() {
+ constexpr int byte_size = sizeof(std::uint16_t);
+ ByteArray read_bytes = ReadBytes(byte_size);
+ if (read_bytes.Empty() || read_bytes.size() != byte_size) {
+ return -1;
+ }
+
+ // Convert from network order.
+ const char *data = read_bytes.data();
+ return static_cast<uint16_t>(data[0]) << 8 | static_cast<uint16_t>(data[1]);
+}
+
+std::uint32_t BaseInputStream::ReadUint32() {
+ constexpr int byte_size = sizeof(std::uint32_t);
+ ByteArray read_bytes = ReadBytes(byte_size);
+ if (read_bytes.Empty() || read_bytes.size() != byte_size) {
+ return -1;
+ }
+
+ // Convert from network order.
+ const char *data = read_bytes.data();
+ return static_cast<uint32_t>(data[0]) << 24 |
+ static_cast<uint32_t>(data[1]) << 16 |
+ static_cast<uint32_t>(data[2]) << 8 | static_cast<uint32_t>(data[3]);
+}
+
+std::uint64_t BaseInputStream::ReadUint64() {
+ constexpr int byte_size = sizeof(std::uint64_t);
+ ByteArray read_bytes = ReadBytes(byte_size);
+ if (read_bytes.Empty() || read_bytes.size() != byte_size) {
+ return -1;
+ }
+
+ // Convert from network order.
+ const char *data = read_bytes.data();
+ return static_cast<uint64_t>(data[0]) << 56 |
+ static_cast<uint64_t>(data[1]) << 48 |
+ static_cast<uint64_t>(data[2]) << 40 |
+ static_cast<uint64_t>(data[3]) << 32 |
+ static_cast<uint64_t>(data[4]) << 24 |
+ static_cast<uint64_t>(data[5]) << 16 |
+ static_cast<uint64_t>(data[6]) << 8 | static_cast<uint64_t>(data[7]);
+}
+
+ByteArray BaseInputStream::ReadBytes(int size) {
+ ExceptionOr<ByteArray> read_bytes_result = Read(size);
+ if (!read_bytes_result.ok()) {
+ return ByteArray{};
+ }
+
+ return read_bytes_result.GetResult();
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/base_input_stream.h b/chromium/third_party/nearby/src/internal/platform/base_input_stream.h
new file mode 100644
index 00000000000..7324e0a22ab
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/base_input_stream.h
@@ -0,0 +1,63 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_BASE_BASE_INPUT_STREAM_H_
+#define PLATFORM_BASE_BASE_INPUT_STREAM_H_
+
+#include "internal/platform/byte_array.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/input_stream.h"
+
+namespace location {
+namespace nearby {
+
+// A base {@link InputStream } for reading the contents of a byte array.
+class BaseInputStream : public InputStream {
+ public:
+ explicit BaseInputStream(ByteArray &buffer) : buffer_{buffer} {}
+ BaseInputStream(const BaseInputStream &) = delete;
+ BaseInputStream &operator=(const BaseInputStream &) = delete;
+ ~BaseInputStream() override { Close(); }
+
+ ExceptionOr<ByteArray> Read(std::int64_t size) override;
+
+ ExceptionOr<size_t> Skip(size_t offset) override {
+ size_t real_offset = std::min(offset, buffer_.size() - position_);
+ position_ += real_offset;
+ return ExceptionOr<size_t>(real_offset);
+ }
+
+ Exception Close() override {
+ // Do nothing.
+ return {Exception::kSuccess};
+ }
+
+ std::uint8_t ReadUint8();
+ std::uint16_t ReadUint16();
+ std::uint32_t ReadUint32();
+ std::uint64_t ReadUint64();
+ ByteArray ReadBytes(int size);
+ bool IsAvailable(int size) const {
+ return buffer_.size() - position_ >= size;
+ }
+
+ private:
+ ByteArray &buffer_;
+ int position_{0};
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_BASE_BASE_INPUT_STREAM_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/base_mutex_lock.h b/chromium/third_party/nearby/src/internal/platform/base_mutex_lock.h
new file mode 100644
index 00000000000..5f59391ec0d
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/base_mutex_lock.h
@@ -0,0 +1,40 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_BASE_BASE_MUTEX_LOCK_H_
+#define PLATFORM_BASE_BASE_MUTEX_LOCK_H_
+
+#include "absl/base/thread_annotations.h"
+#include "internal/platform/implementation/mutex.h"
+
+namespace location {
+namespace nearby {
+
+// An RAII mechanism to acquire a Lock over a block of code.
+class ABSL_SCOPED_LOCKABLE BaseMutexLock final {
+ public:
+ explicit BaseMutexLock(api::Mutex* mutex) ABSL_EXCLUSIVE_LOCK_FUNCTION(mutex)
+ : mutex_(mutex) {
+ mutex_->Lock();
+ }
+ ~BaseMutexLock() ABSL_UNLOCK_FUNCTION() { mutex_->Unlock(); }
+
+ private:
+ api::Mutex* mutex_;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_BASE_BASE_MUTEX_LOCK_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/base_pipe.cc b/chromium/third_party/nearby/src/internal/platform/base_pipe.cc
new file mode 100644
index 00000000000..b97357ad5e1
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/base_pipe.cc
@@ -0,0 +1,109 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/base_pipe.h"
+
+#include "internal/platform/base_mutex_lock.h"
+#include "internal/platform/input_stream.h"
+#include "internal/platform/output_stream.h"
+
+namespace location {
+namespace nearby {
+
+ExceptionOr<ByteArray> BasePipe::Read(size_t size) {
+ BaseMutexLock lock(mutex_.get());
+
+ // We're done reading all the chunks that were written before the OutputStream
+ // was closed, so there's nothing to do here other than return an empty chunk
+ // to serve as an EOF indication to callers.
+ if (read_all_chunks_) {
+ return ExceptionOr<ByteArray>{ByteArray{}};
+ }
+
+ while (buffer_.empty() && !input_stream_closed_) {
+ Exception wait_exception = cond_->Wait();
+
+ if (wait_exception.Raised()) {
+ return ExceptionOr<ByteArray>{wait_exception};
+ }
+ }
+
+ if (input_stream_closed_) {
+ return ExceptionOr<ByteArray>{Exception::kIo};
+ }
+
+ ByteArray first_chunk{buffer_.front()};
+ buffer_.pop_front();
+
+ // If we received our sentinel chunk, mark the fact that there cannot
+ // possibly be any more chunks to read here on in, and return an empty chunk
+ // to serve as an EOF indication to callers.
+ if (first_chunk.Empty()) {
+ read_all_chunks_ = true;
+ return ExceptionOr<ByteArray>{ByteArray{}};
+ }
+
+ // If first_chunk is small enough to not overshoot the requested 'size', just
+ // return that.
+ if (first_chunk.size() <= size) {
+ return ExceptionOr<ByteArray>{first_chunk};
+ } else {
+ // Break first_chunk into 2 parts -- the first one of which (next_chunk)
+ // will be 'size' bytes long, and will be returned, and the second one of
+ // which (overflow_chunk) will be re-inserted into buffer_, at the head of
+ // the queue, to be served up in the next call to read().
+ ByteArray next_chunk(first_chunk.data(), size);
+ buffer_.push_front(
+ ByteArray(first_chunk.data() + size, first_chunk.size() - size));
+ return ExceptionOr<ByteArray>{next_chunk};
+ }
+}
+
+Exception BasePipe::Write(const ByteArray& data) {
+ BaseMutexLock lock(mutex_.get());
+
+ return WriteLocked(data);
+}
+
+void BasePipe::MarkInputStreamClosed() {
+ BaseMutexLock lock(mutex_.get());
+
+ input_stream_closed_ = true;
+ // Trigger cond_ to unblock a potentially-blocked call to read(), and to let
+ // it know to return Exception::IO.
+ cond_->Notify();
+}
+
+void BasePipe::MarkOutputStreamClosed() {
+ BaseMutexLock lock(mutex_.get());
+
+ // Write a sentinel null chunk before marking output_stream_closed as true.
+ WriteLocked(ByteArray{});
+ output_stream_closed_ = true;
+}
+
+Exception BasePipe::WriteLocked(const ByteArray& data) {
+ if (input_stream_closed_ || output_stream_closed_) {
+ return {Exception::kIo};
+ }
+
+ buffer_.push_back(data);
+ // Trigger cond_ to unblock a potentially-blocked call to read(), now that
+ // there's more data for it to consume.
+ cond_->Notify();
+ return {Exception::kSuccess};
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/base_pipe.h b/chromium/third_party/nearby/src/internal/platform/base_pipe.h
new file mode 100644
index 00000000000..766b2fc557f
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/base_pipe.h
@@ -0,0 +1,138 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_BASE_BASE_PIPE_H_
+#define PLATFORM_BASE_BASE_PIPE_H_
+
+#include <cstdint>
+#include <deque>
+#include <memory>
+
+#include "absl/base/thread_annotations.h"
+#include "internal/platform/implementation/condition_variable.h"
+#include "internal/platform/implementation/mutex.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/input_stream.h"
+#include "internal/platform/output_stream.h"
+
+namespace location {
+namespace nearby {
+
+// Common Pipe implenentation.
+// It does not depend on platform implementation, and this allows it to
+// be used in the platform implementation itself.
+// Concrete class must be derived from it, as follows:
+//
+// class DerivedPipe : public BasePipe {
+// public:
+// DerivedPipe() {
+// auto mutex = /* construct platform-dependent mutex */;
+// auto cond = /* construct platform-dependent condition variable */;
+// Setup(std::move(mutex), std::move(cond));
+// }
+// ~DerivedPipe() override = default;
+// DerivedPipe(DerivedPipe&&) = default;
+// DerivedPipe& operator=(DerivedPipe&&) = default;
+// };
+class BasePipe {
+ public:
+ static constexpr const size_t kChunkSize = 64 * 1024;
+ virtual ~BasePipe() = default;
+
+ // Pipe is not copyable or movable, because copy/move will invalidate
+ // references to input and output streams.
+ // If move is required, Pipe could be wrapped with std::unique_ptr<>.
+ BasePipe(BasePipe&&) = delete;
+ BasePipe& operator=(BasePipe&&) = delete;
+
+ // Get...() methods return references to input and output steam facades.
+ // It is safe to call Get...() methods multiple times.
+ InputStream& GetInputStream() { return input_stream_; }
+ OutputStream& GetOutputStream() { return output_stream_; }
+
+ protected:
+ BasePipe() = default;
+
+ void Setup(std::unique_ptr<api::Mutex> mutex,
+ std::unique_ptr<api::ConditionVariable> cond) {
+ mutex_ = std::move(mutex);
+ cond_ = std::move(cond);
+ }
+
+ private:
+ class BasePipeInputStream : public InputStream {
+ public:
+ explicit BasePipeInputStream(BasePipe* pipe) : pipe_(pipe) {}
+ ~BasePipeInputStream() override { DoClose(); }
+
+ ExceptionOr<ByteArray> Read(std::int64_t size) override {
+ return pipe_->Read(size);
+ }
+ Exception Close() override { return DoClose(); }
+
+ private:
+ Exception DoClose() {
+ pipe_->MarkInputStreamClosed();
+ return {Exception::kSuccess};
+ }
+ BasePipe* pipe_;
+ };
+ class BasePipeOutputStream : public OutputStream {
+ public:
+ explicit BasePipeOutputStream(BasePipe* pipe) : pipe_(pipe) {}
+ ~BasePipeOutputStream() override { DoClose(); }
+
+ Exception Write(const ByteArray& data) override {
+ return pipe_->Write(data);
+ }
+ Exception Flush() override { return {Exception::kSuccess}; }
+ Exception Close() override { return DoClose(); }
+
+ private:
+ Exception DoClose() {
+ pipe_->MarkOutputStreamClosed();
+ return {Exception::kSuccess};
+ }
+ BasePipe* pipe_;
+ };
+
+ ExceptionOr<ByteArray> Read(size_t size) ABSL_LOCKS_EXCLUDED(mutex_);
+ Exception Write(const ByteArray& data) ABSL_LOCKS_EXCLUDED(mutex_);
+
+ void MarkInputStreamClosed() ABSL_LOCKS_EXCLUDED(mutex_);
+ void MarkOutputStreamClosed() ABSL_LOCKS_EXCLUDED(mutex_);
+
+ Exception WriteLocked(const ByteArray& data)
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Order of declaration matters:
+ // - mutex must be defined before condvar;
+ // - input & output streams must be after both mutex and condvar.
+ bool input_stream_closed_ ABSL_GUARDED_BY(mutex_) = false;
+ bool output_stream_closed_ ABSL_GUARDED_BY(mutex_) = false;
+ bool read_all_chunks_ ABSL_GUARDED_BY(mutex_) = false;
+
+ std::deque<ByteArray> ABSL_GUARDED_BY(mutex_) buffer_;
+ std::unique_ptr<api::Mutex> mutex_;
+ std::unique_ptr<api::ConditionVariable> cond_;
+
+ BasePipeInputStream input_stream_{this};
+ BasePipeOutputStream output_stream_{this};
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_BASE_BASE_PIPE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/ble.cc b/chromium/third_party/nearby/src/internal/platform/ble.cc
new file mode 100644
index 00000000000..54945e04e0f
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/ble.cc
@@ -0,0 +1,138 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/ble.h"
+
+#include "internal/platform/logging.h"
+#include "internal/platform/mutex_lock.h"
+
+namespace location {
+namespace nearby {
+
+bool BleMedium::StartAdvertising(
+ const std::string& service_id, const ByteArray& advertisement_bytes,
+ const std::string& fast_advertisement_service_uuid) {
+ return impl_->StartAdvertising(service_id, advertisement_bytes,
+ fast_advertisement_service_uuid);
+}
+
+bool BleMedium::StopAdvertising(const std::string& service_id) {
+ return impl_->StopAdvertising(service_id);
+}
+
+bool BleMedium::StartScanning(
+ const std::string& service_id,
+ const std::string& fast_advertisement_service_uuid,
+ DiscoveredPeripheralCallback callback) {
+ {
+ MutexLock lock(&mutex_);
+ discovered_peripheral_callback_ = std::move(callback);
+ peripherals_.clear();
+ }
+ return impl_->StartScanning(
+ service_id, fast_advertisement_service_uuid,
+ {
+ .peripheral_discovered_cb =
+ [this](api::BlePeripheral& peripheral,
+ const std::string& service_id, bool fast_advertisement) {
+ MutexLock lock(&mutex_);
+ auto pair = peripherals_.emplace(
+ &peripheral, absl::make_unique<ScanningInfo>());
+ auto& context = *pair.first->second;
+ if (pair.second) {
+ context.peripheral = BlePeripheral(&peripheral);
+ discovered_peripheral_callback_.peripheral_discovered_cb(
+ context.peripheral, service_id,
+ context.peripheral.GetAdvertisementBytes(service_id),
+ fast_advertisement);
+ }
+ },
+ .peripheral_lost_cb =
+ [this](api::BlePeripheral& peripheral,
+ const std::string& service_id) {
+ MutexLock lock(&mutex_);
+ if (peripherals_.empty()) return;
+ auto context = peripherals_.find(&peripheral);
+ if (context == peripherals_.end()) return;
+ NEARBY_LOG(INFO, "Removing peripheral=%p, impl=%p",
+ &(context->second->peripheral), &peripheral);
+ discovered_peripheral_callback_.peripheral_lost_cb(
+ context->second->peripheral, service_id);
+ },
+ });
+}
+
+bool BleMedium::StopScanning(const std::string& service_id) {
+ {
+ MutexLock lock(&mutex_);
+ discovered_peripheral_callback_ = {};
+ peripherals_.clear();
+ NEARBY_LOG(INFO, "Ble Scanning disabled: impl=%p", &GetImpl());
+ }
+ return impl_->StopScanning(service_id);
+}
+
+bool BleMedium::StartAcceptingConnections(const std::string& service_id,
+ AcceptedConnectionCallback callback) {
+ {
+ MutexLock lock(&mutex_);
+ accepted_connection_callback_ = std::move(callback);
+ }
+ return impl_->StartAcceptingConnections(
+ service_id,
+ {
+ .accepted_cb =
+ [this](api::BleSocket& socket, const std::string& service_id) {
+ MutexLock lock(&mutex_);
+ auto pair = sockets_.emplace(
+ &socket, absl::make_unique<AcceptedConnectionInfo>());
+ auto& context = *pair.first->second;
+ if (!pair.second) {
+ NEARBY_LOG(INFO, "Accepting (again) socket=%p, impl=%p",
+ &context.socket, &socket);
+ } else {
+ context.socket = BleSocket(&socket);
+ NEARBY_LOG(INFO, "Accepting socket=%p, impl=%p",
+ &context.socket, &socket);
+ }
+ accepted_connection_callback_.accepted_cb(context.socket,
+ service_id);
+ },
+ });
+}
+
+bool BleMedium::StopAcceptingConnections(const std::string& service_id) {
+ {
+ MutexLock lock(&mutex_);
+ accepted_connection_callback_ = {};
+ sockets_.clear();
+ NEARBY_LOG(INFO, "Ble accepted connection disabled: impl=%p", &GetImpl());
+ }
+ return impl_->StopAcceptingConnections(service_id);
+}
+
+BleSocket BleMedium::Connect(BlePeripheral& peripheral,
+ const std::string& service_id,
+ CancellationFlag* cancellation_flag) {
+ {
+ MutexLock lock(&mutex_);
+ NEARBY_LOG(INFO, "BleMedium::Connect: peripheral=%p [impl=%p]", &peripheral,
+ &peripheral.GetImpl());
+ }
+ return BleSocket(
+ impl_->Connect(peripheral.GetImpl(), service_id, cancellation_flag));
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/ble.h b/chromium/third_party/nearby/src/internal/platform/ble.h
new file mode 100644
index 00000000000..e3ba127b5d5
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/ble.h
@@ -0,0 +1,166 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_BLE_H_
+#define PLATFORM_PUBLIC_BLE_H_
+
+#include "absl/container/flat_hash_map.h"
+#include "internal/platform/implementation/ble.h"
+#include "internal/platform/implementation/platform.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/cancellation_flag.h"
+#include "internal/platform/input_stream.h"
+#include "internal/platform/output_stream.h"
+#include "internal/platform/bluetooth_adapter.h"
+#include "internal/platform/mutex.h"
+
+namespace location {
+namespace nearby {
+
+class BleSocket final {
+ public:
+ BleSocket() = default;
+ BleSocket(const BleSocket&) = default;
+ BleSocket& operator=(const BleSocket&) = default;
+ explicit BleSocket(api::BleSocket* socket) : impl_(socket) {}
+ explicit BleSocket(std::unique_ptr<api::BleSocket> socket)
+ : impl_(socket.release()) {}
+ ~BleSocket() = default;
+
+ // Returns the InputStream of the BleSocket.
+ // On error, returned stream will report Exception::kIo on any operation.
+ //
+ // The returned object is not owned by the caller, and can be invalidated once
+ // the BleSocket object is destroyed.
+ InputStream& GetInputStream() { return impl_->GetInputStream(); }
+
+ // Returns the OutputStream of the BleSocket.
+ // On error, returned stream will report Exception::kIo on any operation.
+ //
+ // The returned object is not owned by the caller, and can be invalidated once
+ // the BleSocket object is destroyed.
+ OutputStream& GetOutputStream() { return impl_->GetOutputStream(); }
+
+ // Returns Exception::kIo on error, Exception::kSuccess otherwise.
+ Exception Close() { return impl_->Close(); }
+
+ BlePeripheral GetRemotePeripheral() {
+ return BlePeripheral(impl_->GetRemotePeripheral());
+ }
+
+ // Returns true if a socket is usable. If this method returns false,
+ // it is not safe to call any other method.
+ // NOTE(socket validity):
+ // Socket created by a default public constructor is not valid, because
+ // it is missing platform implementation.
+ // The only way to obtain a valid socket is through connection, such as
+ // an object returned by BleMedium::Connect
+ // These methods may also return an invalid socket if connection failed for
+ // any reason.
+ bool IsValid() const { return impl_ != nullptr; }
+
+ // Returns reference to platform implementation.
+ // This is used to communicate with platform code, and for debugging purposes.
+ // Returned reference will remain valid for while BleSocket object is
+ // itself valid. Typically BleSocket lifetime matches duration of the
+ // connection, and is controlled by end user, since they hold the instance.
+ api::BleSocket& GetImpl() { return *impl_; }
+
+ private:
+ std::shared_ptr<api::BleSocket> impl_;
+};
+
+// Container of operations that can be performed over the BLE medium.
+class BleMedium final {
+ public:
+ using Platform = api::ImplementationPlatform;
+ struct DiscoveredPeripheralCallback {
+ std::function<void(BlePeripheral& peripheral, const std::string& service_id,
+ const ByteArray& advertisement_bytes,
+ bool fast_advertisement)>
+ peripheral_discovered_cb =
+ DefaultCallback<BlePeripheral&, const std::string&,
+ const ByteArray&, bool>();
+ std::function<void(BlePeripheral& peripheral,
+ const std::string& service_id)>
+ peripheral_lost_cb =
+ DefaultCallback<BlePeripheral&, const std::string&>();
+ };
+ struct ScanningInfo {
+ BlePeripheral peripheral;
+ };
+
+ struct AcceptedConnectionCallback {
+ std::function<void(BleSocket& socket, const std::string& service_id)>
+ accepted_cb = DefaultCallback<BleSocket&, const std::string&>();
+ };
+ struct AcceptedConnectionInfo {
+ BleSocket socket;
+ };
+
+ explicit BleMedium(BluetoothAdapter& adapter)
+ : impl_(Platform::CreateBleMedium(adapter.GetImpl())),
+ adapter_(adapter) {}
+ ~BleMedium() = default;
+
+ // Returns true once the BLE advertising has been initiated.
+ bool StartAdvertising(const std::string& service_id,
+ const ByteArray& advertisement_bytes,
+ const std::string& fast_advertisement_service_uuid);
+ bool StopAdvertising(const std::string& service_id);
+
+ // Returns true once the BLE scan has been initiated.
+ bool StartScanning(const std::string& service_id,
+ const std::string& fast_advertisement_service_uuid,
+ DiscoveredPeripheralCallback callback);
+
+ // Returns true once BLE scanning for service_id is well and truly stopped;
+ // after this returns, there must be no more invocations of the
+ // DiscoveredPeripheralCallback passed in to StartScanning() for service_id.
+ bool StopScanning(const std::string& service_id);
+
+ // Returns true once BLE socket connection requests to service_id can be
+ // accepted.
+ bool StartAcceptingConnections(const std::string& service_id,
+ AcceptedConnectionCallback callback);
+ bool StopAcceptingConnections(const std::string& service_id);
+
+ // Returns a new BleSocket. On Success, BleSocket::IsValid()
+ // returns true.
+ BleSocket Connect(BlePeripheral& peripheral, const std::string& service_id,
+ CancellationFlag* cancellation_flag);
+
+ bool IsValid() const { return impl_ != nullptr; }
+
+ api::BleMedium& GetImpl() { return *impl_; }
+ BluetoothAdapter& GetAdapter() { return adapter_; }
+
+ private:
+ Mutex mutex_;
+ std::unique_ptr<api::BleMedium> impl_;
+ BluetoothAdapter& adapter_;
+ absl::flat_hash_map<api::BlePeripheral*, std::unique_ptr<ScanningInfo>>
+ peripherals_ ABSL_GUARDED_BY(mutex_);
+ absl::flat_hash_map<api::BleSocket*, std::unique_ptr<AcceptedConnectionInfo>>
+ sockets_ ABSL_GUARDED_BY(mutex_);
+ DiscoveredPeripheralCallback discovered_peripheral_callback_
+ ABSL_GUARDED_BY(mutex_);
+ AcceptedConnectionCallback accepted_connection_callback_
+ ABSL_GUARDED_BY(mutex_);
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_BLE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/ble_test.cc b/chromium/third_party/nearby/src/internal/platform/ble_test.cc
new file mode 100644
index 00000000000..abe4ca63557
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/ble_test.cc
@@ -0,0 +1,306 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/ble.h"
+
+#include <memory>
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "internal/platform/medium_environment.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace {
+
+using FeatureFlags = FeatureFlags::Flags;
+
+constexpr FeatureFlags kTestCases[] = {
+ FeatureFlags{
+ .enable_cancellation_flag = true,
+ },
+ FeatureFlags{
+ .enable_cancellation_flag = false,
+ },
+};
+
+constexpr absl::Duration kWaitDuration = absl::Milliseconds(1000);
+constexpr absl::string_view kServiceID{"com.google.location.nearby.apps.test"};
+constexpr absl::string_view kAdvertisementString{"\x0a\x0b\x0c\x0d"};
+constexpr absl::string_view kFastAdvertisementServiceUuid{"\xf3\xfe"};
+
+class BleMediumTest : public ::testing::TestWithParam<FeatureFlags> {
+ protected:
+ using DiscoveredPeripheralCallback = BleMedium::DiscoveredPeripheralCallback;
+ using AcceptedConnectionCallback = BleMedium::AcceptedConnectionCallback;
+
+ BleMediumTest() { env_.Stop(); }
+
+ MediumEnvironment& env_{MediumEnvironment::Instance()};
+};
+
+TEST_P(BleMediumTest, CanStartAcceptingConnectionsAndConnect) {
+ FeatureFlags feature_flags = GetParam();
+ env_.SetFeatureFlags(feature_flags);
+ env_.Start();
+ BluetoothAdapter adapter_a_;
+ BluetoothAdapter adapter_b_;
+ BleMedium ble_a{adapter_a_};
+ BleMedium ble_b{adapter_b_};
+ std::string service_id(kServiceID);
+ ByteArray advertisement_bytes{std::string(kAdvertisementString)};
+ std::string fast_advertisement_service_uuid(kFastAdvertisementServiceUuid);
+ CountDownLatch found_latch(1);
+ CountDownLatch accepted_latch(1);
+ CancellationFlag flag;
+
+ BlePeripheral* discovered_peripheral = nullptr;
+ ble_a.StartScanning(
+ service_id, fast_advertisement_service_uuid,
+ DiscoveredPeripheralCallback{
+ .peripheral_discovered_cb =
+ [&found_latch, &discovered_peripheral](
+ BlePeripheral& peripheral, const std::string& service_id,
+ const ByteArray& advertisement_bytes,
+ bool fast_advertisement) {
+ NEARBY_LOG(
+ INFO,
+ "Peripheral discovered: %s, %p, fast advertisement: %d",
+ peripheral.GetName().c_str(), &peripheral,
+ fast_advertisement);
+ discovered_peripheral = &peripheral;
+ found_latch.CountDown();
+ },
+ });
+ ble_b.StartAdvertising(service_id, advertisement_bytes,
+ fast_advertisement_service_uuid);
+ ble_b.StartAcceptingConnections(
+ service_id,
+ AcceptedConnectionCallback{
+ .accepted_cb = [&accepted_latch](BleSocket socket,
+ const std::string& service_id) {
+ NEARBY_LOG(INFO, "Connection accepted: socket=%p, service_id=%s",
+ &socket, service_id.c_str());
+ accepted_latch.CountDown();
+ }});
+ EXPECT_TRUE(found_latch.Await(kWaitDuration).result());
+
+ BleSocket socket_a;
+ EXPECT_FALSE(socket_a.IsValid());
+ {
+ SingleThreadExecutor client_executor;
+ client_executor.Execute(
+ [&ble_a, &socket_a, discovered_peripheral, &service_id, &flag]() {
+ socket_a = ble_a.Connect(*discovered_peripheral, service_id, &flag);
+ });
+ }
+ EXPECT_TRUE(accepted_latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(socket_a.IsValid());
+ ble_b.StopAdvertising(service_id);
+ ble_a.StopScanning(service_id);
+ env_.Stop();
+}
+
+TEST_P(BleMediumTest, CanCancelConnect) {
+ FeatureFlags feature_flags = GetParam();
+ env_.SetFeatureFlags(feature_flags);
+ env_.Start();
+ BluetoothAdapter adapter_a_;
+ BluetoothAdapter adapter_b_;
+ BleMedium ble_a{adapter_a_};
+ BleMedium ble_b{adapter_b_};
+ std::string service_id(kServiceID);
+ ByteArray advertisement_bytes{std::string(kAdvertisementString)};
+ std::string fast_advertisement_service_uuid(kFastAdvertisementServiceUuid);
+ CountDownLatch found_latch(1);
+ CountDownLatch accepted_latch(1);
+ CancellationFlag flag(true);
+
+ BlePeripheral* discovered_peripheral = nullptr;
+ ble_a.StartScanning(
+ service_id, fast_advertisement_service_uuid,
+ DiscoveredPeripheralCallback{
+ .peripheral_discovered_cb =
+ [&found_latch, &discovered_peripheral](
+ BlePeripheral& peripheral, const std::string& service_id,
+ const ByteArray& advertisement_bytes,
+ bool fast_advertisement) {
+ NEARBY_LOG(
+ INFO,
+ "Peripheral discovered: %s, %p, fast advertisement: %d",
+ peripheral.GetName().c_str(), &peripheral,
+ fast_advertisement);
+ discovered_peripheral = &peripheral;
+ found_latch.CountDown();
+ },
+ });
+ ble_b.StartAdvertising(service_id, advertisement_bytes,
+ fast_advertisement_service_uuid);
+ ble_b.StartAcceptingConnections(
+ service_id,
+ AcceptedConnectionCallback{
+ .accepted_cb = [&accepted_latch](BleSocket socket,
+ const std::string& service_id) {
+ NEARBY_LOG(INFO, "Connection accepted: socket=%p, service_id=%s",
+ &socket, service_id.c_str());
+ accepted_latch.CountDown();
+ }});
+ EXPECT_TRUE(found_latch.Await(kWaitDuration).result());
+
+ BleSocket socket_a;
+ EXPECT_FALSE(socket_a.IsValid());
+ {
+ SingleThreadExecutor client_executor;
+ client_executor.Execute(
+ [&ble_a, &socket_a, discovered_peripheral, &service_id, &flag]() {
+ socket_a = ble_a.Connect(*discovered_peripheral, service_id, &flag);
+ });
+ }
+ // If FeatureFlag is disabled, Cancelled is false as no-op.
+ if (!feature_flags.enable_cancellation_flag) {
+ EXPECT_TRUE(accepted_latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(socket_a.IsValid());
+ } else {
+ EXPECT_FALSE(accepted_latch.Await(kWaitDuration).result());
+ EXPECT_FALSE(socket_a.IsValid());
+ }
+ ble_b.StopAdvertising(service_id);
+ ble_a.StopScanning(service_id);
+ env_.Stop();
+}
+
+INSTANTIATE_TEST_SUITE_P(ParametrisedBleMediumTest, BleMediumTest,
+ ::testing::ValuesIn(kTestCases));
+
+TEST_F(BleMediumTest, ConstructorDestructorWorks) {
+ env_.Start();
+ BluetoothAdapter adapter_a_;
+ BluetoothAdapter adapter_b_;
+ BleMedium ble_a{adapter_a_};
+ BleMedium ble_b{adapter_b_};
+
+ // Make sure we can create functional mediums.
+ ASSERT_TRUE(ble_a.IsValid());
+ ASSERT_TRUE(ble_b.IsValid());
+
+ // Make sure we can create 2 distinct mediums.
+ EXPECT_NE(&ble_a.GetImpl(), &ble_b.GetImpl());
+ env_.Stop();
+}
+
+TEST_F(BleMediumTest, CanStartAdvertising) {
+ env_.Start();
+ BluetoothAdapter adapter_a_;
+ BluetoothAdapter adapter_b_;
+ BleMedium ble_a{adapter_a_};
+ BleMedium ble_b{adapter_b_};
+ std::string service_id(kServiceID);
+ ByteArray advertisement_bytes{std::string(kAdvertisementString)};
+ std::string fast_advertisement_service_uuid(kFastAdvertisementServiceUuid);
+ CountDownLatch found_latch(1);
+
+ ble_a.StartAdvertising(service_id, advertisement_bytes,
+ fast_advertisement_service_uuid);
+
+ EXPECT_TRUE(ble_b.StartScanning(
+ service_id, fast_advertisement_service_uuid,
+ DiscoveredPeripheralCallback{
+ .peripheral_discovered_cb =
+ [&found_latch](
+ BlePeripheral& peripheral, const std::string& service_id,
+ const ByteArray& advertisement_bytes,
+ bool fast_advertisement) { found_latch.CountDown(); },
+ }));
+ EXPECT_TRUE(found_latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(ble_a.StopAdvertising(service_id));
+ EXPECT_TRUE(ble_b.StopScanning(service_id));
+ env_.Stop();
+}
+
+TEST_F(BleMediumTest, CanStartScanning) {
+ env_.Start();
+ BluetoothAdapter adapter_a_;
+ BluetoothAdapter adapter_b_;
+ BleMedium ble_a{adapter_a_};
+ BleMedium ble_b{adapter_b_};
+ std::string service_id(kServiceID);
+ ByteArray advertisement_bytes{std::string(kAdvertisementString)};
+ std::string fast_advertisement_service_uuid(kFastAdvertisementServiceUuid);
+ CountDownLatch found_latch(1);
+ CountDownLatch lost_latch(1);
+
+ ble_a.StartScanning(
+ service_id, fast_advertisement_service_uuid,
+ DiscoveredPeripheralCallback{
+ .peripheral_discovered_cb =
+ [&found_latch](
+ BlePeripheral& peripheral, const std::string& service_id,
+ const ByteArray& advertisement_bytes,
+ bool fast_advertisement) { found_latch.CountDown(); },
+ .peripheral_lost_cb =
+ [&lost_latch](BlePeripheral& peripheral,
+ const std::string& service_id) {
+ lost_latch.CountDown();
+ },
+ });
+ EXPECT_TRUE(ble_b.StartAdvertising(service_id, advertisement_bytes,
+ fast_advertisement_service_uuid));
+ EXPECT_TRUE(found_latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(ble_b.StopAdvertising(service_id));
+ EXPECT_TRUE(lost_latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(ble_a.StopScanning(service_id));
+ env_.Stop();
+}
+
+TEST_F(BleMediumTest, CanStopDiscovery) {
+ env_.Start();
+ BluetoothAdapter adapter_a_;
+ BluetoothAdapter adapter_b_;
+ BleMedium ble_a{adapter_a_};
+ BleMedium ble_b{adapter_b_};
+ std::string service_id(kServiceID);
+ ByteArray advertisement_bytes{std::string(kAdvertisementString)};
+ std::string fast_advertisement_service_uuid(kFastAdvertisementServiceUuid);
+ CountDownLatch found_latch(1);
+ CountDownLatch lost_latch(1);
+
+ ble_a.StartScanning(
+ service_id, fast_advertisement_service_uuid,
+ DiscoveredPeripheralCallback{
+ .peripheral_discovered_cb =
+ [&found_latch](
+ BlePeripheral& peripheral, const std::string& service_id,
+ const ByteArray& advertisement_bytes,
+ bool fast_advertisement) { found_latch.CountDown(); },
+ .peripheral_lost_cb =
+ [&lost_latch](BlePeripheral& peripheral,
+ const std::string& service_id) {
+ lost_latch.CountDown();
+ },
+ });
+ EXPECT_TRUE(ble_b.StartAdvertising(service_id, advertisement_bytes,
+ fast_advertisement_service_uuid));
+ EXPECT_TRUE(found_latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(ble_a.StopScanning(service_id));
+ EXPECT_TRUE(ble_b.StopAdvertising(service_id));
+ EXPECT_FALSE(lost_latch.Await(kWaitDuration).result());
+ env_.Stop();
+}
+
+} // namespace
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/bluetooth_adapter.h b/chromium/third_party/nearby/src/internal/platform/bluetooth_adapter.h
new file mode 100644
index 00000000000..903e1cc2b35
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/bluetooth_adapter.h
@@ -0,0 +1,126 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_BLUETOOTH_ADAPTER_H_
+#define PLATFORM_PUBLIC_BLUETOOTH_ADAPTER_H_
+
+#include <string>
+
+#include "absl/strings/string_view.h"
+#include "internal/platform/implementation/bluetooth_adapter.h"
+#include "internal/platform/implementation/bluetooth_classic.h"
+#include "internal/platform/implementation/platform.h"
+
+namespace location {
+namespace nearby {
+
+// Opaque wrapper over a BLE peripheral. Must contain enough data about a
+// particular BLE peripheral to connect to its GATT server.
+class BlePeripheral final {
+ public:
+ BlePeripheral() = default;
+ BlePeripheral(const BlePeripheral&) = default;
+ BlePeripheral& operator=(const BlePeripheral&) = default;
+ explicit BlePeripheral(api::BlePeripheral* peripheral) : impl_(peripheral) {}
+ ~BlePeripheral() = default;
+
+ std::string GetName() const { return impl_->GetName(); }
+
+ ByteArray GetAdvertisementBytes(const std::string& service_id) const {
+ return impl_->GetAdvertisementBytes(service_id);
+ }
+
+ api::BlePeripheral& GetImpl() { return *impl_; }
+ bool IsValid() const { return impl_ != nullptr; }
+
+ private:
+ api::BlePeripheral* impl_;
+};
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html.
+class BluetoothDevice final {
+ public:
+ BluetoothDevice() = default;
+ BluetoothDevice(const BluetoothDevice&) = default;
+ BluetoothDevice& operator=(const BluetoothDevice&) = default;
+ explicit BluetoothDevice(api::BluetoothDevice* device) : impl_(device) {}
+ ~BluetoothDevice() = default;
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#getName()
+ std::string GetName() const { return impl_->GetName(); }
+ std::string GetMacAddress() const { return impl_->GetMacAddress(); }
+
+ api::BluetoothDevice& GetImpl() { return *impl_; }
+ bool IsValid() const { return impl_ != nullptr; }
+
+ private:
+ api::BluetoothDevice* impl_;
+};
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html
+class BluetoothAdapter final {
+ public:
+ using Status = api::BluetoothAdapter::Status;
+ using ScanMode = api::BluetoothAdapter::ScanMode;
+
+ BluetoothAdapter()
+ : impl_(api::ImplementationPlatform::CreateBluetoothAdapter()) {}
+ ~BluetoothAdapter() = default;
+ BluetoothAdapter(BluetoothAdapter&&) = default;
+ BluetoothAdapter& operator=(BluetoothAdapter&&) = default;
+
+ // Synchronously sets the status of the BluetoothAdapter to 'status', and
+ // returns true if the operation was a success.
+ bool SetStatus(Status status) { return impl_->SetStatus(status); }
+ Status GetStatus() const {
+ return IsEnabled() ? Status::kEnabled : Status::kDisabled;
+ }
+
+ // Returns true if the BluetoothAdapter's current status is
+ // Status::Value::kEnabled.
+ bool IsEnabled() const { return impl_->IsEnabled(); }
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getScanMode()
+ //
+ // Returns ScanMode::kUnknown on error.
+ ScanMode GetScanMode() const { return impl_->GetScanMode(); }
+
+ // Synchronously sets the scan mode of the adapter, and returns true if the
+ // operation was a success.
+ bool SetScanMode(ScanMode scan_mode) { return impl_->SetScanMode(scan_mode); }
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getName()
+ // Returns an empty string on error
+ std::string GetName() const { return impl_->GetName(); }
+ std::string GetMacAddress() const { return impl_->GetMacAddress(); }
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#setName(java.lang.String)
+ bool SetName(absl::string_view name) { return impl_->SetName(name); }
+
+ bool IsValid() const { return impl_ != nullptr; }
+
+ // Returns reference to platform implementation.
+ // This is used to communicate with platform code, and for debugging purposes.
+ // Returned reference will remain valid for while BluetoothAdapter object is
+ // itself valid. It matches Core() object lifetime.
+ api::BluetoothAdapter& GetImpl() { return *impl_; }
+
+ private:
+ std::unique_ptr<api::BluetoothAdapter> impl_;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_BLUETOOTH_ADAPTER_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/bluetooth_adapter_test.cc b/chromium/third_party/nearby/src/internal/platform/bluetooth_adapter_test.cc
new file mode 100644
index 00000000000..cf6c87d9f2f
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/bluetooth_adapter_test.cc
@@ -0,0 +1,69 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/bluetooth_adapter.h"
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "internal/platform/bluetooth_utils.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace {
+
+TEST(BluetoothAdapterTest, ConstructorDestructorWorks) {
+ BluetoothAdapter adapter;
+ EXPECT_TRUE(adapter.IsValid());
+}
+
+TEST(BluetoothAdapterTest, CanSetName) {
+ constexpr char kAdapterName[] = "MyBtAdapter";
+ BluetoothAdapter adapter;
+ EXPECT_EQ(adapter.GetStatus(), BluetoothAdapter::Status::kDisabled);
+ EXPECT_TRUE(adapter.SetName(kAdapterName));
+ EXPECT_EQ(adapter.GetName(), std::string(kAdapterName));
+}
+
+TEST(BluetoothAdapterTest, CanSetStatus) {
+ BluetoothAdapter adapter;
+ EXPECT_EQ(adapter.GetStatus(), BluetoothAdapter::Status::kDisabled);
+ EXPECT_TRUE(adapter.SetStatus(BluetoothAdapter::Status::kEnabled));
+ EXPECT_EQ(adapter.GetStatus(), BluetoothAdapter::Status::kEnabled);
+}
+
+TEST(BluetoothAdapterTest, CanSetMode) {
+ BluetoothAdapter adapter;
+ EXPECT_TRUE(adapter.SetScanMode(BluetoothAdapter::ScanMode::kConnectable));
+ EXPECT_EQ(adapter.GetScanMode(), BluetoothAdapter::ScanMode::kConnectable);
+ EXPECT_TRUE(adapter.SetScanMode(
+ BluetoothAdapter::ScanMode::kConnectableDiscoverable));
+ EXPECT_EQ(adapter.GetScanMode(),
+ BluetoothAdapter::ScanMode::kConnectableDiscoverable);
+ EXPECT_TRUE(adapter.SetScanMode(BluetoothAdapter::ScanMode::kNone));
+ EXPECT_EQ(adapter.GetScanMode(), BluetoothAdapter::ScanMode::kNone);
+}
+
+TEST(BluetoothAdapterTest, CanGetMacAddress) {
+ BluetoothAdapter adapter;
+ std::string bt_mac =
+ BluetoothUtils::ToString(ByteArray(adapter.GetMacAddress()));
+ NEARBY_LOG(INFO, "BT MAC: '%s'", bt_mac.c_str());
+ EXPECT_NE(bt_mac, "");
+}
+
+} // namespace
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/bluetooth_classic.cc b/chromium/third_party/nearby/src/internal/platform/bluetooth_classic.cc
new file mode 100644
index 00000000000..9eb6bafb2a1
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/bluetooth_classic.cc
@@ -0,0 +1,99 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/bluetooth_classic.h"
+
+#include "internal/platform/logging.h"
+#include "internal/platform/mutex_lock.h"
+
+namespace location {
+namespace nearby {
+
+BluetoothClassicMedium::~BluetoothClassicMedium() { StopDiscovery(); }
+
+BluetoothSocket BluetoothClassicMedium::ConnectToService(
+ BluetoothDevice& remote_device, const std::string& service_uuid,
+ CancellationFlag* cancellation_flag) {
+ NEARBY_LOG(INFO,
+ "BluetoothClassicMedium::ConnectToService: device=%p [impl=%p]",
+ &remote_device, &remote_device.GetImpl());
+ return BluetoothSocket(impl_->ConnectToService(
+ remote_device.GetImpl(), service_uuid, cancellation_flag));
+}
+
+bool BluetoothClassicMedium::StartDiscovery(DiscoveryCallback callback) {
+ MutexLock lock(&mutex_);
+ if (discovery_enabled_) {
+ NEARBY_LOG(INFO, "BT Discovery already enabled; impl=%p", &GetImpl());
+ return false;
+ }
+ bool success = impl_->StartDiscovery({
+ .device_discovered_cb =
+ [this](api::BluetoothDevice& device) {
+ MutexLock lock(&mutex_);
+ auto pair = devices_.emplace(
+ &device, absl::make_unique<DeviceDiscoveryInfo>());
+ auto& context = *pair.first->second;
+ if (!pair.second) {
+ NEARBY_LOG(INFO, "Adding (again) device=%p, impl=%p",
+ &context.device, &device);
+ return;
+ }
+ context.device = BluetoothDevice(&device);
+ NEARBY_LOG(INFO, "Adding device=%p, impl=%p", &context.device,
+ &device);
+ if (!discovery_enabled_) return;
+ discovery_callback_.device_discovered_cb(context.device);
+ },
+ .device_name_changed_cb =
+ [this](api::BluetoothDevice& device) {
+ MutexLock lock(&mutex_);
+ auto& context = *devices_[&device];
+ NEARBY_LOG(INFO, "Renaming device=%p, impl=%p", &context.device,
+ &device);
+ if (!discovery_enabled_) return;
+ discovery_callback_.device_name_changed_cb(context.device);
+ },
+ .device_lost_cb =
+ [this](api::BluetoothDevice& device) {
+ MutexLock lock(&mutex_);
+ auto item = devices_.extract(&device);
+ auto& context = *item.mapped();
+ NEARBY_LOG(INFO, "Removing device=%p, impl=%p", &context.device,
+ &device);
+ if (!discovery_enabled_) return;
+ discovery_callback_.device_lost_cb(context.device);
+ },
+ });
+ if (success) {
+ discovery_callback_ = std::move(callback);
+ devices_.clear();
+ discovery_enabled_ = true;
+ NEARBY_LOG(INFO, "BT Discovery enabled; impl=%p", &GetImpl());
+ }
+ return success;
+}
+
+bool BluetoothClassicMedium::StopDiscovery() {
+ MutexLock lock(&mutex_);
+ if (!discovery_enabled_) return true;
+ discovery_enabled_ = false;
+ discovery_callback_ = {};
+ devices_.clear();
+ NEARBY_LOG(INFO, "BT Discovery disabled: impl=%p", &GetImpl());
+ return impl_->StopDiscovery();
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/bluetooth_classic.h b/chromium/third_party/nearby/src/internal/platform/bluetooth_classic.h
new file mode 100644
index 00000000000..a2dde684a77
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/bluetooth_classic.h
@@ -0,0 +1,235 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_BLUETOOTH_CLASSIC_H_
+#define PLATFORM_PUBLIC_BLUETOOTH_CLASSIC_H_
+
+#include <memory>
+#include <string>
+
+#include "absl/container/flat_hash_map.h"
+#include "internal/platform/implementation/bluetooth_classic.h"
+#include "internal/platform/implementation/platform.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/cancellation_flag.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/input_stream.h"
+#include "internal/platform/listeners.h"
+#include "internal/platform/output_stream.h"
+#include "internal/platform/bluetooth_adapter.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/mutex.h"
+
+namespace location {
+namespace nearby {
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html.
+class BluetoothSocket final {
+ public:
+ BluetoothSocket() = default;
+ BluetoothSocket(const BluetoothSocket&) = default;
+ BluetoothSocket& operator=(const BluetoothSocket&) = default;
+ explicit BluetoothSocket(std::unique_ptr<api::BluetoothSocket> socket)
+ : impl_(socket.release()) {}
+ ~BluetoothSocket() = default;
+
+ // Returns the InputStream of this connected BluetoothSocket.
+ InputStream& GetInputStream() { return impl_->GetInputStream(); }
+
+ // Returns the OutputStream of this connected BluetoothSocket.
+ OutputStream& GetOutputStream() { return impl_->GetOutputStream(); }
+
+ // Closes both input and output streams, marks Socket as closed.
+ // After this call object should be treated as not connected.
+ // Returns Exception::kIo on error, Exception::kSuccess otherwise.
+ Exception Close() { return impl_->Close(); }
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#getRemoteDevice()
+ BluetoothDevice GetRemoteDevice() {
+ return BluetoothDevice(impl_->GetRemoteDevice());
+ }
+
+ // Returns true if a socket is usable. If this method returns false,
+ // it is not safe to call any other method.
+ // NOTE(socket validity):
+ // Socket created by a default public constructor is not valid, because
+ // it is missing platform implementation.
+ // The only way to obtain a valid socket is through connection, such as
+ // an object returned by either BluetoothClassicMedium::ConnectTotService or
+ // BluetoothServerSocket::Accept().
+ // These methods may also return an invalid socket if connection failed for
+ // any reason.
+ bool IsValid() const { return impl_ != nullptr; }
+
+ // Returns reference to platform implementation.
+ // This is used to communicate with platform code, and for debugging purposes.
+ // Returned reference will remain valid for while BluetoothSocket object is
+ // itself valid. Typically BluetoothSocket lifetime matches duration of the
+ // connection, and is controlled by end user, since they hold the instance.
+ api::BluetoothSocket& GetImpl() { return *impl_; }
+
+ private:
+ std::shared_ptr<api::BluetoothSocket> impl_;
+};
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html.
+class BluetoothServerSocket final {
+ public:
+ BluetoothServerSocket() = default;
+ BluetoothServerSocket(const BluetoothServerSocket&) = default;
+ BluetoothServerSocket& operator=(const BluetoothServerSocket&) = default;
+ ~BluetoothServerSocket() = default;
+ explicit BluetoothServerSocket(
+ std::unique_ptr<api::BluetoothServerSocket> socket)
+ : impl_(std::move(socket)) {}
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html#accept()
+ //
+ // Blocks until either:
+ // - at least one incoming connection request is available, or
+ // - ServerSocket is closed.
+ // On success, returns connected socket, ready to exchange data.
+ // Returns nullptr on error.
+ // Once error is reported, it is permanent, and ServerSocket has to be closed.
+ BluetoothSocket Accept() {
+ auto socket = impl_->Accept();
+ if (!socket) {
+ NEARBY_LOGS(INFO) << "Accept() failed on server socket: " << this;
+ }
+ return BluetoothSocket(std::move(socket));
+ }
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html#close()
+ //
+ // Returns Exception::kIo on error, Exception::kSuccess otherwise.
+ Exception Close() {
+ NEARBY_LOGS(INFO) << "Closing server socket: " << this;
+ return impl_->Close();
+ }
+
+ bool IsValid() const { return impl_ != nullptr; }
+ api::BluetoothServerSocket& GetImpl() { return *impl_; }
+
+ private:
+ std::shared_ptr<api::BluetoothServerSocket> impl_;
+};
+
+// Container of operations that can be performed over the Bluetooth Classic
+// medium.
+class BluetoothClassicMedium final {
+ public:
+ using Platform = api::ImplementationPlatform;
+ struct DiscoveryCallback {
+ // BluetoothDevice is a proxy object created as a result of BT discovery.
+ // Its lifetime spans between calls to device_discovered_cb and
+ // device_lost_cb.
+ // It is safe to use BluetoothDevice in device_discovered_cb() callback
+ // and at any time afterwards, until device_lost_cb() is called.
+ // It is not safe to use BluetoothDevice after returning from
+ // device_lost_cb() callback.
+ std::function<void(BluetoothDevice& device)> device_discovered_cb =
+ DefaultCallback<BluetoothDevice&>();
+ std::function<void(BluetoothDevice& device)> device_name_changed_cb =
+ DefaultCallback<BluetoothDevice&>();
+ std::function<void(BluetoothDevice& device)> device_lost_cb =
+ DefaultCallback<BluetoothDevice&>();
+ };
+ struct DeviceDiscoveryInfo {
+ BluetoothDevice device;
+ };
+
+ explicit BluetoothClassicMedium(BluetoothAdapter& adapter)
+ : impl_(Platform::CreateBluetoothClassicMedium(adapter.GetImpl())),
+ adapter_(adapter) {}
+
+ ~BluetoothClassicMedium();
+
+ // NOTE(DiscoveryCallback):
+ // BluetoothDevice is a proxy object created as a result of BT discovery.
+ // Its lifetime spans between calls to device_discovered_cb and
+ // device_lost_cb.
+ // It is safe to use BluetoothDevice in device_discovered_cb() callback
+ // and at any time afterwards, until device_lost_cb() is called.
+ // It is not safe to use BluetoothDevice after returning from
+ // device_lost_cb() callback.
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#startDiscovery()
+ //
+ // Returns true once the process of discovery has been initiated.
+ bool StartDiscovery(DiscoveryCallback callback);
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#cancelDiscovery()
+ //
+ // Returns true once discovery is well and truly stopped; after this returns,
+ // there must be no more invocations of the DiscoveryCallback passed in to
+ // StartDiscovery().
+ bool StopDiscovery();
+
+ // A combination of
+ // https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#createInsecureRfcommSocketToServiceRecord
+ // followed by
+ // https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#connect().
+ //
+ // service_uuid is the canonical textual representation
+ // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format) of a
+ // type 3 name-based
+ // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based))
+ // UUID.
+ //
+ // Returns a new BluetoothSocket. On Success, BluetoothSocket::IsValid()
+ // returns true.
+ BluetoothSocket ConnectToService(BluetoothDevice& remote_device,
+ const std::string& service_uuid,
+ CancellationFlag* cancellation_flag);
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#listenUsingInsecureRfcommWithServiceRecord
+ //
+ // service_uuid is the canonical textual representation
+ // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format) of a
+ // type 3 name-based
+ // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based))
+ // UUID.
+ //
+ // Returns a new BluetoothServerSocket.
+ // On Success, BluetoothServerSocket::IsValid() returns true.
+ BluetoothServerSocket ListenForService(const std::string& service_name,
+ const std::string& service_uuid) {
+ return BluetoothServerSocket(
+ impl_->ListenForService(service_name, service_uuid));
+ }
+
+ bool IsValid() const { return impl_ != nullptr; }
+
+ api::BluetoothClassicMedium& GetImpl() { return *impl_; }
+ BluetoothAdapter& GetAdapter() { return adapter_; }
+ std::string GetMacAddress() const { return adapter_.GetMacAddress(); }
+ BluetoothDevice GetRemoteDevice(const std::string& mac_address) {
+ return BluetoothDevice(impl_->GetRemoteDevice(mac_address));
+ }
+
+ private:
+ Mutex mutex_;
+ std::unique_ptr<api::BluetoothClassicMedium> impl_;
+ BluetoothAdapter& adapter_;
+ absl::flat_hash_map<api::BluetoothDevice*,
+ std::unique_ptr<DeviceDiscoveryInfo>>
+ devices_ ABSL_GUARDED_BY(mutex_);
+ DiscoveryCallback discovery_callback_ ABSL_GUARDED_BY(mutex_);
+ bool discovery_enabled_ ABSL_GUARDED_BY(mutex_) = false;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_BLUETOOTH_CLASSIC_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/bluetooth_classic_test.cc b/chromium/third_party/nearby/src/internal/platform/bluetooth_classic_test.cc
new file mode 100644
index 00000000000..dce7e8f4480
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/bluetooth_classic_test.cc
@@ -0,0 +1,294 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/bluetooth_classic.h"
+
+#include <memory>
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "absl/time/time.h"
+#include "internal/platform/medium_environment.h"
+#include "internal/platform/bluetooth_adapter.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/single_thread_executor.h"
+
+namespace location {
+namespace nearby {
+namespace {
+
+using FeatureFlags = FeatureFlags::Flags;
+
+constexpr FeatureFlags kTestCases[] = {
+ FeatureFlags{
+ .enable_cancellation_flag = true,
+ },
+ FeatureFlags{
+ .enable_cancellation_flag = false,
+ },
+};
+
+class BluetoothClassicMediumTest
+ : public ::testing::TestWithParam<FeatureFlags> {
+ protected:
+ using DiscoveryCallback = BluetoothClassicMedium::DiscoveryCallback;
+ BluetoothClassicMediumTest() {
+ env_.Start();
+ env_.Reset();
+ adapter_a_ = std::make_unique<BluetoothAdapter>();
+ adapter_b_ = std::make_unique<BluetoothAdapter>();
+ bt_a_ = std::make_unique<BluetoothClassicMedium>(*adapter_a_);
+ bt_b_ = std::make_unique<BluetoothClassicMedium>(*adapter_b_);
+ adapter_a_->SetName("Device-A");
+ adapter_b_->SetName("Device-B");
+ adapter_a_->SetStatus(BluetoothAdapter::Status::kEnabled);
+ adapter_b_->SetStatus(BluetoothAdapter::Status::kEnabled);
+ env_.Sync();
+ }
+ ~BluetoothClassicMediumTest() override {
+ env_.Sync(false);
+ adapter_a_->SetStatus(BluetoothAdapter::Status::kDisabled);
+ adapter_b_->SetStatus(BluetoothAdapter::Status::kDisabled);
+ bt_a_.reset();
+ bt_b_.reset();
+ env_.Sync(false);
+ adapter_a_.reset();
+ adapter_b_.reset();
+ env_.Reset();
+ env_.Stop();
+ }
+
+ MediumEnvironment& env_{MediumEnvironment::Instance()};
+
+ std::unique_ptr<BluetoothAdapter> adapter_a_;
+ std::unique_ptr<BluetoothAdapter> adapter_b_;
+ std::unique_ptr<BluetoothClassicMedium> bt_a_;
+ std::unique_ptr<BluetoothClassicMedium> bt_b_;
+};
+
+TEST_P(BluetoothClassicMediumTest, CanConnectToService) {
+ FeatureFlags feature_flags = GetParam();
+ env_.SetFeatureFlags(feature_flags);
+
+ adapter_a_->SetScanMode(BluetoothAdapter::ScanMode::kConnectable);
+ CountDownLatch found_latch(1);
+ BluetoothDevice* discovered_device = nullptr;
+ bt_a_->StartDiscovery(DiscoveryCallback{
+ .device_discovered_cb =
+ [this, &found_latch, &discovered_device](BluetoothDevice& device) {
+ NEARBY_LOG(INFO, "Device discovered: %s", device.GetName().c_str());
+ EXPECT_EQ(device.GetName(), adapter_b_->GetName());
+ discovered_device = &device;
+ found_latch.CountDown();
+ },
+ });
+ adapter_b_->SetScanMode(BluetoothAdapter::ScanMode::kConnectableDiscoverable);
+ EXPECT_EQ(adapter_b_->GetScanMode(),
+ BluetoothAdapter::ScanMode::kConnectableDiscoverable);
+ EXPECT_TRUE(found_latch.Await(absl::Milliseconds(1000)).result());
+ std::string service_name{"service"};
+ std::string service_uuid("service-uuid");
+ BluetoothServerSocket server_socket =
+ bt_b_->ListenForService(service_name, service_uuid);
+ EXPECT_TRUE(server_socket.IsValid());
+ BluetoothSocket socket_a;
+ BluetoothSocket socket_b;
+ EXPECT_FALSE(socket_a.IsValid());
+ EXPECT_FALSE(socket_b.IsValid());
+ {
+ CancellationFlag flag;
+ SingleThreadExecutor server_executor;
+ SingleThreadExecutor client_executor;
+ client_executor.Execute([this, &socket_a, discovered_device, &service_uuid,
+ &server_socket, &flag]() {
+ socket_a =
+ bt_a_->ConnectToService(*discovered_device, service_uuid, &flag);
+ if (!socket_a.IsValid()) server_socket.Close();
+ });
+ server_executor.Execute([&socket_b, &server_socket]() {
+ socket_b = server_socket.Accept();
+ if (!socket_b.IsValid()) server_socket.Close();
+ });
+ }
+ EXPECT_TRUE(socket_a.IsValid());
+ EXPECT_TRUE(socket_b.IsValid());
+ server_socket.Close();
+}
+
+TEST_P(BluetoothClassicMediumTest, CanCancelConnect) {
+ FeatureFlags feature_flags = GetParam();
+ env_.SetFeatureFlags(feature_flags);
+
+ adapter_a_->SetScanMode(BluetoothAdapter::ScanMode::kConnectable);
+ CountDownLatch found_latch(1);
+ BluetoothDevice* discovered_device = nullptr;
+ bt_a_->StartDiscovery(DiscoveryCallback{
+ .device_discovered_cb =
+ [this, &found_latch, &discovered_device](BluetoothDevice& device) {
+ NEARBY_LOG(INFO, "Device discovered: %s", device.GetName().c_str());
+ EXPECT_EQ(device.GetName(), adapter_b_->GetName());
+ discovered_device = &device;
+ found_latch.CountDown();
+ },
+ });
+ adapter_b_->SetScanMode(BluetoothAdapter::ScanMode::kConnectableDiscoverable);
+ EXPECT_EQ(adapter_b_->GetScanMode(),
+ BluetoothAdapter::ScanMode::kConnectableDiscoverable);
+ EXPECT_TRUE(found_latch.Await(absl::Milliseconds(1000)).result());
+ std::string service_name{"service"};
+ std::string service_uuid("service-uuid");
+ BluetoothServerSocket server_socket =
+ bt_b_->ListenForService(service_name, service_uuid);
+ EXPECT_TRUE(server_socket.IsValid());
+ BluetoothSocket socket_a;
+ BluetoothSocket socket_b;
+ EXPECT_FALSE(socket_a.IsValid());
+ EXPECT_FALSE(socket_b.IsValid());
+ {
+ CancellationFlag flag(true);
+ SingleThreadExecutor server_executor;
+ SingleThreadExecutor client_executor;
+ client_executor.Execute([this, &socket_a, discovered_device, &service_uuid,
+ &server_socket, &flag]() {
+ socket_a =
+ bt_a_->ConnectToService(*discovered_device, service_uuid, &flag);
+ if (!socket_a.IsValid()) server_socket.Close();
+ });
+ server_executor.Execute([&socket_b, &server_socket]() {
+ socket_b = server_socket.Accept();
+ if (!socket_b.IsValid()) server_socket.Close();
+ });
+ }
+ // If FeatureFlag is disabled, Cancelled is false as no-op.
+ if (!feature_flags.enable_cancellation_flag) {
+ EXPECT_TRUE(socket_a.IsValid());
+ EXPECT_TRUE(socket_b.IsValid());
+ } else {
+ EXPECT_FALSE(socket_a.IsValid());
+ EXPECT_FALSE(socket_b.IsValid());
+ }
+ server_socket.Close();
+}
+
+INSTANTIATE_TEST_SUITE_P(ParametrisedBluetoothClassicMediumTest,
+ BluetoothClassicMediumTest,
+ ::testing::ValuesIn(kTestCases));
+
+TEST_F(BluetoothClassicMediumTest, ConstructorDestructorWorks) {
+ // Make sure we can create functional adapters.
+ ASSERT_TRUE(adapter_a_->IsValid());
+ ASSERT_TRUE(adapter_b_->IsValid());
+
+ // Make sure we can create 2 distinct adapters.
+ // NOTE: multiple adapters are supported on a test platform, but not
+ // necessarily on every available HW platform.
+ // Often, HW platform supports only one BT adapter.
+ EXPECT_NE(&adapter_a_->GetImpl(), &adapter_b_->GetImpl());
+
+ // Make sure we can create functional mediums.
+ ASSERT_TRUE(bt_a_->IsValid());
+ ASSERT_TRUE(bt_b_->IsValid());
+
+ // Make sure we can create 2 distinct mediums.
+ EXPECT_NE(&bt_a_->GetImpl(), &bt_b_->GetImpl());
+}
+
+TEST_F(BluetoothClassicMediumTest, CanStartDiscovery) {
+ adapter_a_->SetScanMode(BluetoothAdapter::ScanMode::kConnectable);
+ CountDownLatch found_latch(1);
+ CountDownLatch lost_latch(1);
+ bt_a_->StartDiscovery(DiscoveryCallback{
+ .device_discovered_cb =
+ [this, &found_latch](BluetoothDevice& device) {
+ NEARBY_LOG(INFO, "Device discovered: %s", device.GetName().c_str());
+ EXPECT_EQ(device.GetName(), adapter_b_->GetName());
+ found_latch.CountDown();
+ },
+ .device_lost_cb =
+ [this, &lost_latch](BluetoothDevice& device) {
+ NEARBY_LOG(INFO, "Device lost: %s", device.GetName().c_str());
+ EXPECT_EQ(device.GetName(), adapter_b_->GetName());
+ lost_latch.CountDown();
+ },
+ });
+ adapter_b_->SetScanMode(BluetoothAdapter::ScanMode::kConnectableDiscoverable);
+ EXPECT_EQ(adapter_b_->GetScanMode(),
+ BluetoothAdapter::ScanMode::kConnectableDiscoverable);
+ EXPECT_TRUE(found_latch.Await(absl::Milliseconds(1000)).result());
+ adapter_b_->SetStatus(BluetoothAdapter::Status::kDisabled);
+ EXPECT_FALSE(adapter_b_->IsEnabled());
+ EXPECT_TRUE(lost_latch.Await(absl::Milliseconds(1000)).result());
+}
+
+TEST_F(BluetoothClassicMediumTest, CanStopDiscovery) {
+ adapter_a_->SetScanMode(BluetoothAdapter::ScanMode::kConnectable);
+ CountDownLatch found_latch(1);
+ CountDownLatch lost_latch(1);
+ bt_a_->StartDiscovery(DiscoveryCallback{
+ .device_discovered_cb =
+ [this, &found_latch](BluetoothDevice& device) {
+ NEARBY_LOG(INFO, "Device discovered: %s", device.GetName().c_str());
+ EXPECT_EQ(device.GetName(), adapter_b_->GetName());
+ found_latch.CountDown();
+ },
+ .device_lost_cb =
+ [this, &lost_latch](BluetoothDevice& device) {
+ NEARBY_LOG(INFO, "Device lost: %s", device.GetName().c_str());
+ EXPECT_EQ(device.GetName(), adapter_b_->GetName());
+ lost_latch.CountDown();
+ },
+ });
+ adapter_b_->SetScanMode(BluetoothAdapter::ScanMode::kConnectableDiscoverable);
+ EXPECT_EQ(adapter_b_->GetScanMode(),
+ BluetoothAdapter::ScanMode::kConnectableDiscoverable);
+ EXPECT_TRUE(found_latch.Await(absl::Milliseconds(1000)).result());
+ bt_a_->StopDiscovery();
+ adapter_b_->SetStatus(BluetoothAdapter::Status::kDisabled);
+ EXPECT_FALSE(adapter_b_->IsEnabled());
+ EXPECT_FALSE(lost_latch.Await(absl::Milliseconds(1000)).result());
+}
+
+TEST_F(BluetoothClassicMediumTest, CanListenForService) {
+ adapter_a_->SetScanMode(BluetoothAdapter::ScanMode::kConnectable);
+ CountDownLatch found_latch(1);
+ bt_a_->StartDiscovery(DiscoveryCallback{
+ .device_discovered_cb =
+ [this, &found_latch](BluetoothDevice& device) {
+ NEARBY_LOG(INFO, "Device discovered: %s", device.GetName().c_str());
+ EXPECT_EQ(device.GetName(), adapter_b_->GetName());
+ found_latch.CountDown();
+ },
+ });
+ adapter_b_->SetScanMode(BluetoothAdapter::ScanMode::kConnectableDiscoverable);
+ EXPECT_EQ(adapter_b_->GetScanMode(),
+ BluetoothAdapter::ScanMode::kConnectableDiscoverable);
+ EXPECT_TRUE(found_latch.Await(absl::Milliseconds(1000)).result());
+ std::string service_name{"service"};
+ std::string service_uuid("service-uuid");
+ BluetoothServerSocket server_socket =
+ bt_b_->ListenForService(service_name, service_uuid);
+ EXPECT_TRUE(server_socket.IsValid());
+ server_socket.Close();
+}
+
+TEST_F(BluetoothClassicMediumTest, FailIfDiscovering) {
+ EXPECT_TRUE(bt_a_->StartDiscovery({}));
+ EXPECT_FALSE(bt_a_->StartDiscovery({}));
+}
+
+} // namespace
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/bluetooth_utils.cc b/chromium/third_party/nearby/src/internal/platform/bluetooth_utils.cc
new file mode 100644
index 00000000000..91f007bd684
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/bluetooth_utils.cc
@@ -0,0 +1,75 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/bluetooth_utils.h"
+
+#include "absl/strings/escaping.h"
+#include "absl/strings/str_format.h"
+
+namespace location {
+namespace nearby {
+
+std::string BluetoothUtils::ToString(const ByteArray& bluetooth_mac_address) {
+ std::string colon_delimited_string;
+
+ if (bluetooth_mac_address.size() != kBluetoothMacAddressLength)
+ return colon_delimited_string;
+
+ if (IsBluetoothMacAddressUnset(bluetooth_mac_address))
+ return colon_delimited_string;
+
+ for (auto byte : std::string(bluetooth_mac_address)) {
+ if (!colon_delimited_string.empty())
+ absl::StrAppend(&colon_delimited_string, ":");
+ absl::StrAppend(&colon_delimited_string, absl::StrFormat("%02X", byte));
+ }
+ return colon_delimited_string;
+}
+
+ByteArray BluetoothUtils::FromString(absl::string_view bluetooth_mac_address) {
+ std::string bt_mac_address(bluetooth_mac_address);
+
+ // Remove the colon delimiters.
+ bt_mac_address.erase(
+ std::remove(bt_mac_address.begin(), bt_mac_address.end(), ':'),
+ bt_mac_address.end());
+
+ // If the bluetooth mac address is invalid (wrong size), return a null byte
+ // array.
+ if (bt_mac_address.length() != kBluetoothMacAddressLength * 2) {
+ return ByteArray();
+ }
+
+ // Convert to bytes. If MAC Address bytes are unset, return a null byte array.
+ auto bt_mac_address_string(absl::HexStringToBytes(bt_mac_address));
+ auto bt_mac_address_bytes =
+ ByteArray(bt_mac_address_string.data(), bt_mac_address_string.size());
+ if (IsBluetoothMacAddressUnset(bt_mac_address_bytes)) {
+ return ByteArray();
+ }
+ return bt_mac_address_bytes;
+}
+
+bool BluetoothUtils::IsBluetoothMacAddressUnset(
+ const ByteArray& bluetooth_mac_address_bytes) {
+ for (int i = 0; i < bluetooth_mac_address_bytes.size(); i++) {
+ if (bluetooth_mac_address_bytes.data()[i] != 0) {
+ return false;
+ }
+ }
+ return true;
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/bluetooth_utils.h b/chromium/third_party/nearby/src/internal/platform/bluetooth_utils.h
new file mode 100644
index 00000000000..46f23022c92
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/bluetooth_utils.h
@@ -0,0 +1,46 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_BASE_BLUETOOTH_UTILS_H_
+#define PLATFORM_BASE_BLUETOOTH_UTILS_H_
+
+#include "absl/strings/string_view.h"
+#include "internal/platform/byte_array.h"
+
+namespace location {
+namespace nearby {
+
+class BluetoothUtils {
+ public:
+ static constexpr int kBluetoothMacAddressLength = 6;
+
+ // Converts a Bluetooth MAC address from byte array to String format. Returns
+ // empty if input byte array is not of correct format.
+ // e.g. {-84, 55, 67, -68, -87, 40} -> "AC:37:43:BC:A9:28".
+ static std::string ToString(const ByteArray& bluetooth_mac_address);
+
+ // Converts a Bluetooth MAC address from String format to byte array. Returns
+ // empty if input string is not of correct format.
+ // e.g. "AC:37:43:BC:A9:28" -> {-84, 55, 67, -68, -87, 40}.
+ static ByteArray FromString(absl::string_view bluetooth_mac_address);
+
+ // Checks if a Bluetooth MAC address is zero for every byte.
+ static bool IsBluetoothMacAddressUnset(
+ const ByteArray& bluetooth_mac_address);
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_BASE_BLUETOOTH_UTILS_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/bluetooth_utils_test.cc b/chromium/third_party/nearby/src/internal/platform/bluetooth_utils_test.cc
new file mode 100644
index 00000000000..369d121dfe9
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/bluetooth_utils_test.cc
@@ -0,0 +1,89 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/bluetooth_utils.h"
+
+#include "gtest/gtest.h"
+
+namespace location {
+namespace nearby {
+
+constexpr absl::string_view kBluetoothMacAddress{"00:00:E6:88:64:13"};
+constexpr char kBluetoothMacAddressBytes[] = {0x00, 0x00, 0xe6,
+ 0x88, 0x64, 0x13};
+
+TEST(BluetoothUtilsTest, ToStringWorks) {
+ ByteArray bt_mac_address_bytes{kBluetoothMacAddressBytes,
+ sizeof(kBluetoothMacAddressBytes)};
+
+ auto bt_mac_address = BluetoothUtils::ToString(bt_mac_address_bytes);
+
+ EXPECT_EQ(kBluetoothMacAddress, bt_mac_address);
+}
+
+TEST(BluetoothUtilsTest, FromStringWorks) {
+ ByteArray bt_mac_address_bytes{kBluetoothMacAddressBytes,
+ sizeof(kBluetoothMacAddressBytes)};
+
+ auto bt_mac_address_bytes_result =
+ BluetoothUtils::FromString(kBluetoothMacAddress);
+
+ EXPECT_EQ(bt_mac_address_bytes, bt_mac_address_bytes_result);
+}
+
+TEST(BluetoothUtilsTest, InvalidBytesReturnsEmptyString) {
+ std::string string_result;
+
+ char bad_bt_mac_address_1[] = {0x02, 0x20, 0x00};
+ ByteArray bad_bt_mac_address_bytes_1{bad_bt_mac_address_1,
+ sizeof(bad_bt_mac_address_1)};
+ string_result = BluetoothUtils::ToString(bad_bt_mac_address_bytes_1);
+ EXPECT_TRUE(string_result.empty());
+
+ char bad_bt_mac_address_2[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+ ByteArray bad_bt_mac_address_bytes_2{bad_bt_mac_address_2,
+ sizeof(bad_bt_mac_address_2)};
+ string_result = BluetoothUtils::ToString(bad_bt_mac_address_bytes_2);
+ EXPECT_TRUE(string_result.empty());
+
+ char bad_bt_mac_address_3[] = {0x11, 0x22, 0x33, 0x44, 0x55,
+ 0x66, 0x77, 0x88, 0x99};
+ ByteArray bad_bt_mac_address_bytes_3{bad_bt_mac_address_3,
+ sizeof(bad_bt_mac_address_3)};
+ string_result = BluetoothUtils::ToString(bad_bt_mac_address_bytes_3);
+ EXPECT_TRUE(string_result.empty());
+}
+
+TEST(BluetoothUtilsTest, InvalidStringReturnsEmptyByteArray) {
+ ByteArray bytes_result;
+
+ std::string bad_bt_mac_address_1 = "022:00";
+ bytes_result = BluetoothUtils::FromString(bad_bt_mac_address_1);
+ EXPECT_TRUE(bytes_result.Empty());
+
+ std::string bad_bt_mac_address_2 = "22:00:11:33:77:aa::bb::99";
+ bytes_result = BluetoothUtils::FromString(bad_bt_mac_address_2);
+ EXPECT_TRUE(bytes_result.Empty());
+
+ std::string bad_bt_mac_address_3 = "00:00:00:00:00:00";
+ bytes_result = BluetoothUtils::FromString(bad_bt_mac_address_3);
+ EXPECT_TRUE(bytes_result.Empty());
+
+ std::string bad_bt_mac_address_4 = "BLUETOOTHCHIP";
+ bytes_result = BluetoothUtils::FromString(bad_bt_mac_address_4);
+ EXPECT_TRUE(bytes_result.Empty());
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/byte_array.h b/chromium/third_party/nearby/src/internal/platform/byte_array.h
index b9dba2d6b3c..b9dba2d6b3c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/base/byte_array.h
+++ b/chromium/third_party/nearby/src/internal/platform/byte_array.h
diff --git a/chromium/third_party/nearby/src/internal/platform/byte_array_test.cc b/chromium/third_party/nearby/src/internal/platform/byte_array_test.cc
new file mode 100644
index 00000000000..0084f0294ba
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/byte_array_test.cc
@@ -0,0 +1,90 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/byte_array.h"
+
+#include <cstring>
+
+#include "gtest/gtest.h"
+
+namespace {
+
+using location::nearby::ByteArray;
+
+TEST(ByteArrayTest, DefaultSizeIsZero) {
+ ByteArray bytes;
+ EXPECT_EQ(0, bytes.size());
+}
+
+TEST(ByteArrayTest, DefaultIsEmpty) {
+ ByteArray bytes;
+ EXPECT_TRUE(bytes.Empty());
+}
+
+TEST(ByteArrayTest, NullArrayIsEmpty) {
+ ByteArray bytes{nullptr, 5};
+ EXPECT_TRUE(bytes.Empty());
+}
+
+TEST(ByteArrayTest, CopyAtDoesNotExtendArray) {
+ ByteArray v1("12345");
+ ByteArray v2("ABCDEFGH");
+ EXPECT_TRUE(v2.CopyAt(/*offset=*/5, v1));
+ EXPECT_TRUE(v2.CopyAt(/*offset=*/1, v1, /*source_offset=*/3));
+ EXPECT_EQ(v2, ByteArray("A45DE123"));
+}
+
+TEST(ByteArrayTest, CopyAtOutOfBoundsIsIgnored) {
+ ByteArray v1("12345");
+ ByteArray v2("ABCDEFGH");
+ // Try to do an out-of-bounds read.
+ EXPECT_FALSE(v2.CopyAt(/* offset=*/5, v1, /*source_offset=*/10));
+ // Try to do an out-of-bounds write.
+ EXPECT_FALSE(v2.CopyAt(/* offset=*/9, v1));
+ EXPECT_EQ(v2, ByteArray("ABCDEFGH"));
+}
+
+TEST(ByteArrayTest, SetFromString) {
+ std::string setup("setup_test");
+ ByteArray bytes{setup}; // array initialized with a copy of string.
+ EXPECT_EQ(setup.size(), bytes.size());
+ EXPECT_EQ(std::string(bytes), setup);
+}
+
+TEST(ByteArrayTest, SetExplicitSize) {
+ constexpr size_t kArraySize = 10;
+ char reference[kArraySize]{};
+ ByteArray bytes{kArraySize}; // array of size 10, zero-initialized.
+ EXPECT_EQ(kArraySize, bytes.size());
+ EXPECT_EQ(0, memcmp(bytes.data(), reference, kArraySize));
+}
+
+TEST(ByteArrayTest, SetExplicitData) {
+ constexpr static const char message[]{"test_message"};
+ constexpr size_t kMessageSize = sizeof(message);
+ ByteArray bytes{message, kMessageSize};
+ EXPECT_EQ(kMessageSize, bytes.size());
+ EXPECT_NE(message, bytes.data());
+ EXPECT_EQ(0, memcmp(message, bytes.data(), kMessageSize));
+}
+
+TEST(ByteArrayTest, CreateFromNonNullTerminatedStdArray) {
+ constexpr static const std::array data{'a', '\x00', 'b'};
+ ByteArray bytes{data};
+ EXPECT_EQ(bytes.size(), 3);
+ EXPECT_EQ(bytes.size(), std::string(bytes).size());
+ EXPECT_EQ(std::string(bytes), std::string(data.data(), data.size()));
+}
+
+} // namespace
diff --git a/chromium/third_party/nearby/src/internal/platform/byte_utils.cc b/chromium/third_party/nearby/src/internal/platform/byte_utils.cc
new file mode 100644
index 00000000000..f9642794812
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/byte_utils.cc
@@ -0,0 +1,39 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/byte_utils.h"
+
+#include <cstdlib>
+
+#include "absl/strings/str_format.h"
+#include "internal/platform/base_input_stream.h"
+
+namespace location {
+namespace nearby {
+
+std::string ByteUtils::ToFourDigitString(ByteArray& bytes) {
+ int multiplier = 1;
+ int hashCode = 0;
+
+ BaseInputStream base_input_stream{bytes};
+ while (base_input_stream.IsAvailable(1)) {
+ auto byte = static_cast<int>(base_input_stream.ReadUint8());
+ hashCode = (hashCode + byte * multiplier) % kHashBasePrime;
+ multiplier = multiplier * kHashBaseMultiplier % kHashBasePrime;
+ }
+ return absl::StrFormat("%04d", abs(hashCode));
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/byte_utils.h b/chromium/third_party/nearby/src/internal/platform/byte_utils.h
new file mode 100644
index 00000000000..ba81a8fbf1d
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/byte_utils.h
@@ -0,0 +1,38 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_BASE_BYTE_UTILS_H_
+#define PLATFORM_BASE_BYTE_UTILS_H_
+
+#include "internal/platform/byte_array.h"
+
+namespace location {
+namespace nearby {
+
+class ByteUtils {
+ public:
+ static std::string ToFourDigitString(ByteArray& bytes);
+
+ private:
+ // The biggest prime number under 10000, used as a mod base to trim integers
+ // into 4 digits.
+ static constexpr int kHashBasePrime = 9973;
+ // The hash multiplier.
+ static constexpr int kHashBaseMultiplier = 31;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_BASE_BYTE_UTILS_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/byte_utils_test.cc b/chromium/third_party/nearby/src/internal/platform/byte_utils_test.cc
new file mode 100644
index 00000000000..f81cc7fccbd
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/byte_utils_test.cc
@@ -0,0 +1,44 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/byte_utils.h"
+
+#include "gtest/gtest.h"
+#include "internal/platform/byte_array.h"
+
+namespace location {
+namespace nearby {
+
+constexpr absl::string_view kFooBytes{"rawABCDE"};
+constexpr absl::string_view kFooFourDigitsToken{"0392"};
+constexpr absl::string_view kEmptyFourDigitsToken{"0000"};
+
+TEST(ByteUtilsTest, ToFourDigitStringCorrect) {
+ ByteArray bytes{std::string(kFooBytes)};
+
+ auto four_digit_string = ByteUtils::ToFourDigitString(bytes);
+
+ EXPECT_EQ(std::string(kFooFourDigitsToken), four_digit_string);
+}
+
+TEST(ByteUtilsTest, TestEmptyByteArrayCorrect) {
+ ByteArray bytes;
+
+ auto four_digit_string = ByteUtils::ToFourDigitString(bytes);
+
+ EXPECT_EQ(std::string(kEmptyFourDigitsToken), four_digit_string);
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/callable.h b/chromium/third_party/nearby/src/internal/platform/callable.h
new file mode 100644
index 00000000000..d68d31b0a40
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/callable.h
@@ -0,0 +1,37 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_BASE_CALLABLE_H_
+#define PLATFORM_BASE_CALLABLE_H_
+
+#include <functional>
+
+#include "internal/platform/exception.h"
+
+namespace location {
+namespace nearby {
+
+// The Callable is and object intended to be executed by a thread, that is able
+// to return a value of specified type T.
+// It must be invokable without arguments. It must return a value implicitly
+// convertible to ExceptionOr<T>.
+//
+// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Callable.html
+template <typename T>
+using Callable = std::function<ExceptionOr<T>()>;
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_BASE_CALLABLE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/cancelable.h b/chromium/third_party/nearby/src/internal/platform/cancelable.h
new file mode 100644
index 00000000000..a261d80f232
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/cancelable.h
@@ -0,0 +1,60 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_CANCELABLE_H_
+#define PLATFORM_PUBLIC_CANCELABLE_H_
+
+#include <memory>
+#include <utility>
+
+#include "internal/platform/implementation/cancelable.h"
+#include "internal/platform/cancellable_task.h"
+
+namespace location {
+namespace nearby {
+
+// An interface to provide a cancellation mechanism for objects that represent
+// long-running operations.
+class Cancelable final {
+ public:
+ Cancelable() = default;
+ Cancelable(const Cancelable&) = default;
+ Cancelable& operator=(const Cancelable& other) = default;
+
+ ~Cancelable() = default;
+
+ // This constructor is used internally only,
+ // by other classes in "//platform/public/".
+ explicit Cancelable(std::shared_ptr<CancellableTask> task,
+ std::shared_ptr<api::Cancelable> impl)
+ : task_{task}, impl_(std::move(impl)) {}
+
+ bool Cancel() {
+ if (!impl_) return false;
+ bool result = impl_->Cancel();
+ task_->CancelAndWaitIfStarted();
+ return result;
+ }
+
+ bool IsValid() { return impl_ != nullptr; }
+
+ private:
+ std::shared_ptr<CancellableTask> task_;
+ std::shared_ptr<api::Cancelable> impl_;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_CANCELABLE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/cancelable_alarm.h b/chromium/third_party/nearby/src/internal/platform/cancelable_alarm.h
new file mode 100644
index 00000000000..68e0b4405b8
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/cancelable_alarm.h
@@ -0,0 +1,71 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_CANCELABLE_ALARM_H_
+#define PLATFORM_PUBLIC_CANCELABLE_ALARM_H_
+
+#include <cstdint>
+#include <functional>
+#include <memory>
+#include <string>
+
+#include "internal/platform/cancelable.h"
+#include "internal/platform/mutex.h"
+#include "internal/platform/mutex_lock.h"
+#include "internal/platform/scheduled_executor.h"
+
+namespace location {
+namespace nearby {
+
+/**
+ * A cancelable alarm with a name. This is a simple wrapper around the logic
+ * for posting a Runnable on a ScheduledExecutor and (possibly) later
+ * canceling it.
+ */
+class CancelableAlarm {
+ public:
+ CancelableAlarm() = default;
+ CancelableAlarm(absl::string_view name, std::function<void()>&& runnable,
+ absl::Duration delay, ScheduledExecutor* scheduled_executor)
+ : name_(name),
+ cancelable_(scheduled_executor->Schedule(std::move(runnable), delay)) {}
+ ~CancelableAlarm() = default;
+ CancelableAlarm(CancelableAlarm&& other) { *this = std::move(other); }
+ CancelableAlarm& operator=(CancelableAlarm&& other) {
+ MutexLock lock(&mutex_);
+ {
+ MutexLock other_lock(&other.mutex_);
+ name_ = std::move(other.name_);
+ cancelable_ = std::move(other.cancelable_);
+ }
+ return *this;
+ }
+
+ bool Cancel() {
+ MutexLock lock(&mutex_);
+ return cancelable_.Cancel();
+ }
+
+ bool IsValid() { return cancelable_.IsValid(); }
+
+ private:
+ Mutex mutex_;
+ std::string name_;
+ Cancelable cancelable_;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_CANCELABLE_ALARM_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/cancelable_alarm_test.cc b/chromium/third_party/nearby/src/internal/platform/cancelable_alarm_test.cc
new file mode 100644
index 00000000000..73407cd98af
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/cancelable_alarm_test.cc
@@ -0,0 +1,69 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/cancelable_alarm.h"
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "absl/time/time.h"
+#include "internal/platform/atomic_boolean.h"
+#include "internal/platform/scheduled_executor.h"
+
+namespace location {
+namespace nearby {
+namespace {
+
+TEST(CancelableAlarmTest, CanCreateDefault) { CancelableAlarm alarm; }
+
+TEST(CancelableAlarmTest, CancelDefaultFails) {
+ CancelableAlarm alarm;
+ EXPECT_FALSE(alarm.Cancel());
+}
+
+TEST(CancelableAlarmTest, CanCreateAndFireAlarm) {
+ ScheduledExecutor alarm_executor;
+ AtomicBoolean done{false};
+ CancelableAlarm alarm(
+ "test_alarm", [&done]() { done.Set(true); }, absl::Milliseconds(100),
+ &alarm_executor);
+ SystemClock::Sleep(absl::Milliseconds(1000));
+ EXPECT_TRUE(done.Get());
+}
+
+TEST(CancelableAlarmTest, CanCreateAndCancelAlarm) {
+ ScheduledExecutor alarm_executor;
+ AtomicBoolean done{false};
+ CancelableAlarm alarm(
+ "test_alarm", [&done]() { done.Set(true); }, absl::Milliseconds(100),
+ &alarm_executor);
+ EXPECT_TRUE(alarm.Cancel());
+ SystemClock::Sleep(absl::Milliseconds(1000));
+ EXPECT_FALSE(done.Get());
+}
+
+TEST(CancelableAlarmTest, CancelExpiredAlarmFails) {
+ ScheduledExecutor alarm_executor;
+ AtomicBoolean done{false};
+ CancelableAlarm alarm(
+ "test_alarm", [&done]() { done.Set(true); }, absl::Milliseconds(100),
+ &alarm_executor);
+ SystemClock::Sleep(absl::Milliseconds(1000));
+ EXPECT_TRUE(done.Get());
+ EXPECT_FALSE(alarm.Cancel());
+}
+
+} // namespace
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/cancellable_task.h b/chromium/third_party/nearby/src/internal/platform/cancellable_task.h
new file mode 100644
index 00000000000..fbcdf9530ac
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/cancellable_task.h
@@ -0,0 +1,70 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_CANCELLABLE_TASK_H_
+#define PLATFORM_PUBLIC_CANCELLABLE_TASK_H_
+
+#include <utility>
+
+#include "internal/platform/feature_flags.h"
+#include "internal/platform/runnable.h"
+#include "internal/platform/atomic_boolean.h"
+#include "internal/platform/future.h"
+
+namespace location {
+namespace nearby {
+
+/**
+ * Runnable wrapper that allows one to wait for the task
+ * to complete if it is already running.
+ */
+class CancellableTask {
+ public:
+ explicit CancellableTask(Runnable&& runnable)
+ : runnable_{std::move(runnable)} {}
+
+ /**
+ * Try to cancel the task and wait until completion if the task is already
+ * running.
+ */
+ void CancelAndWaitIfStarted() {
+ if (started_or_cancelled_.Set(true)) {
+ if (FeatureFlags::GetInstance()
+ .GetFlags()
+ .cancel_waits_for_running_tasks) {
+ // task could still be running, wait until finish
+ finished_.Get();
+ }
+ } else {
+ // mark as finished to support multiple calls to this method
+ finished_.Set(true);
+ }
+ }
+
+ void operator()() {
+ if (started_or_cancelled_.Set(true)) return;
+ runnable_();
+ finished_.Set(true);
+ }
+
+ private:
+ AtomicBoolean started_or_cancelled_;
+ Future<bool> finished_;
+ Runnable runnable_;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_CANCELLABLE_TASK_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/cancellation_flag.cc b/chromium/third_party/nearby/src/internal/platform/cancellation_flag.cc
new file mode 100644
index 00000000000..2536ff63770
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/cancellation_flag.cc
@@ -0,0 +1,80 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/cancellation_flag.h"
+
+#include "internal/platform/feature_flags.h"
+
+namespace location {
+namespace nearby {
+
+CancellationFlag::CancellationFlag() {
+ mutex_ = std::make_unique<absl::Mutex>();
+}
+
+CancellationFlag::CancellationFlag(bool cancelled) {
+ mutex_ = std::make_unique<absl::Mutex>();
+ cancelled_ = cancelled;
+}
+
+CancellationFlag::~CancellationFlag() { listeners_.clear(); }
+
+void CancellationFlag::Cancel() {
+ // Return immediately as no-op if feature flag is not enabled.
+ if (!FeatureFlags::GetInstance().GetFlags().enable_cancellation_flag) {
+ return;
+ }
+
+ absl::flat_hash_set<CancelListener *> listeners;
+ {
+ absl::MutexLock lock(mutex_.get());
+ if (cancelled_) {
+ // Someone already cancelled. Return immediately.
+ return;
+ }
+ cancelled_ = true;
+
+ listeners = listeners_;
+ }
+
+ for (const auto *listener : listeners) {
+ (*listener)();
+ }
+}
+
+bool CancellationFlag::Cancelled() const {
+ absl::MutexLock lock(mutex_.get());
+
+ // Return false as no-op if feature flag is not enabled.
+ if (!FeatureFlags::GetInstance().GetFlags().enable_cancellation_flag) {
+ return false;
+ }
+
+ return cancelled_;
+}
+
+void CancellationFlag::RegisterOnCancelListener(CancelListener *listener) {
+ absl::MutexLock lock(mutex_.get());
+
+ listeners_.emplace(listener);
+}
+
+void CancellationFlag::UnregisterOnCancelListener(CancelListener *listener) {
+ absl::MutexLock lock(mutex_.get());
+
+ listeners_.erase(listener);
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/cancellation_flag.h b/chromium/third_party/nearby/src/internal/platform/cancellation_flag.h
index e861bfe0ab4..e861bfe0ab4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/base/cancellation_flag.h
+++ b/chromium/third_party/nearby/src/internal/platform/cancellation_flag.h
diff --git a/chromium/third_party/nearby/src/internal/platform/cancellation_flag_listener.h b/chromium/third_party/nearby/src/internal/platform/cancellation_flag_listener.h
new file mode 100644
index 00000000000..06edee58892
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/cancellation_flag_listener.h
@@ -0,0 +1,43 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_BASE_CANCELLATION_FLAG_LISTENER_H_
+#define PLATFORM_BASE_CANCELLATION_FLAG_LISTENER_H_
+
+#include "internal/platform/cancellation_flag.h"
+
+namespace location {
+namespace nearby {
+
+// An RAII mechanism to register CancelListener over a life cycle of medium
+// class.
+class CancellationFlagListener {
+ public:
+ CancellationFlagListener(CancellationFlag* flag,
+ std::function<void()> listener)
+ : flag_(flag), listener_(std::move(listener)) {
+ flag_->RegisterOnCancelListener(&listener_);
+ }
+
+ ~CancellationFlagListener() { flag_->UnregisterOnCancelListener(&listener_); }
+
+ private:
+ CancellationFlag* flag_;
+ std::function<void()> listener_;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_BASE_CANCELLATION_FLAG_LISTENER_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/cancellation_flag_test.cc b/chromium/third_party/nearby/src/internal/platform/cancellation_flag_test.cc
new file mode 100644
index 00000000000..2ab36e820b9
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/cancellation_flag_test.cc
@@ -0,0 +1,213 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/cancellation_flag.h"
+
+#include <memory>
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "internal/platform/cancellation_flag_listener.h"
+#include "internal/platform/feature_flags.h"
+#include "internal/platform/medium_environment.h"
+
+namespace location {
+namespace nearby {
+
+class CancellationFlagPeer {
+ public:
+ explicit CancellationFlagPeer(CancellationFlag* cancellation_flag)
+ : cancellation_flag_(cancellation_flag) {}
+ void RegisterOnCancelListener(CancellationFlag::CancelListener* listener) {
+ cancellation_flag_->RegisterOnCancelListener(listener);
+ }
+ void UnregisterOnCancelListener(CancellationFlag::CancelListener* listener) {
+ cancellation_flag_->UnregisterOnCancelListener(listener);
+ }
+ int CancelListenersSize() const {
+ return cancellation_flag_->CancelListenersSize();
+ }
+
+ private:
+ CancellationFlag* cancellation_flag_; // Not owned by CancellationFlagPeer.
+};
+
+namespace {
+
+using FeatureFlags = FeatureFlags::Flags;
+using ::testing::MockFunction;
+using ::testing::StrictMock;
+
+constexpr FeatureFlags kTestCases[] = {
+ FeatureFlags{
+ .enable_cancellation_flag = true,
+ },
+ FeatureFlags{
+ .enable_cancellation_flag = false,
+ },
+};
+
+class CancellationFlagTest : public ::testing::TestWithParam<FeatureFlags> {
+ protected:
+ void SetUp() override {
+ feature_flags_ = GetParam();
+ env_.SetFeatureFlags(feature_flags_);
+ }
+
+ FeatureFlags feature_flags_;
+ MediumEnvironment& env_{MediumEnvironment::Instance()};
+};
+
+TEST_P(CancellationFlagTest, InitialValueIsFalse) {
+ CancellationFlag flag;
+
+ // No matter FeatureFlag is enabled or not, Cancelled is always false.
+ EXPECT_FALSE(flag.Cancelled());
+}
+
+TEST_P(CancellationFlagTest, InitialValueAsTrue) {
+ CancellationFlag flag{true};
+
+ // If FeatureFlag is disabled, Cancelled is false as no-op.
+ if (!feature_flags_.enable_cancellation_flag) {
+ EXPECT_FALSE(flag.Cancelled());
+ return;
+ }
+
+ EXPECT_TRUE(flag.Cancelled());
+}
+
+TEST_P(CancellationFlagTest, CanCancel) {
+ StrictMock<MockFunction<void()>> mock_cancel_callback;
+ CancellationFlag::CancelListener cancel_callback =
+ mock_cancel_callback.AsStdFunction();
+ EXPECT_CALL(mock_cancel_callback, Call)
+ .Times(feature_flags_.enable_cancellation_flag ? 1 : 0);
+ CancellationFlag flag;
+ CancellationFlagListener cancellation_flag_listener(&flag, cancel_callback);
+ flag.Cancel();
+
+ // If FeatureFlag is disabled, return as no-op immediately and
+ // Cancelled is always false.
+ if (!feature_flags_.enable_cancellation_flag) {
+ EXPECT_FALSE(flag.Cancelled());
+ return;
+ }
+
+ EXPECT_TRUE(flag.Cancelled());
+}
+
+TEST_P(CancellationFlagTest, ShouldOnlyCancelOnce) {
+ StrictMock<MockFunction<void()>> mock_cancel_callback;
+ CancellationFlag::CancelListener cancel_callback =
+ mock_cancel_callback.AsStdFunction();
+ EXPECT_CALL(mock_cancel_callback, Call)
+ .Times(feature_flags_.enable_cancellation_flag ? 1 : 0);
+
+ CancellationFlag flag;
+ CancellationFlagListener cancellation_flag_listener(&flag, cancel_callback);
+ flag.Cancel();
+ flag.Cancel();
+ flag.Cancel();
+
+ // If FeatureFlag is disabled, return as no-op immediately and
+ // Cancelled is always false.
+ if (!feature_flags_.enable_cancellation_flag) {
+ EXPECT_FALSE(flag.Cancelled());
+ return;
+ }
+
+ EXPECT_TRUE(flag.Cancelled());
+}
+
+TEST_P(CancellationFlagTest, CannotCancelAfterUnregister) {
+ StrictMock<MockFunction<void()>> mock_cancel_callback;
+ CancellationFlag::CancelListener cancel_callback =
+ mock_cancel_callback.AsStdFunction();
+ EXPECT_CALL(mock_cancel_callback, Call).Times(0);
+
+ CancellationFlag flag;
+ auto cancellation_flag_listener =
+ std::make_unique<CancellationFlagListener>(&flag, cancel_callback);
+ // Release immediately.
+ cancellation_flag_listener.reset();
+ flag.Cancel();
+}
+
+INSTANTIATE_TEST_SUITE_P(ParametrisedCancellationFlagTest, CancellationFlagTest,
+ ::testing::ValuesIn(kTestCases));
+
+} // namespace
+
+TEST(CancellationFlagTest,
+ CancelMultiplesIfMultiplePointersToTheSameFunctionRegistered) {
+ location::nearby::FeatureFlags::Flags feature_flags_ =
+ location::nearby::FeatureFlags::Flags{
+ .enable_cancellation_flag = true,
+ };
+ MediumEnvironment::Instance().SetFeatureFlags(feature_flags_);
+
+ StrictMock<MockFunction<void()>> mock_cancel_callback;
+ CancellationFlag::CancelListener cancel_callback =
+ mock_cancel_callback.AsStdFunction();
+
+ CancellationFlag::CancelListener* callback_pointer_1 = &cancel_callback;
+ auto callback_pointer_2 =
+ std::make_unique<CancellationFlag::CancelListener>();
+ *callback_pointer_2 = cancel_callback;
+
+ EXPECT_NE(callback_pointer_1, callback_pointer_2.get());
+ EXPECT_CALL(mock_cancel_callback, Call).Times(2);
+
+ CancellationFlag flag;
+ CancellationFlagPeer flag_peer(&flag);
+ flag_peer.RegisterOnCancelListener(callback_pointer_1);
+ flag_peer.RegisterOnCancelListener(callback_pointer_2.get());
+
+ flag.Cancel();
+
+ flag_peer.UnregisterOnCancelListener(callback_pointer_2.get());
+ EXPECT_EQ(1, flag_peer.CancelListenersSize());
+ flag_peer.UnregisterOnCancelListener(callback_pointer_1);
+ EXPECT_EQ(0, flag_peer.CancelListenersSize());
+}
+
+TEST(CancellationFlagTest, RegisteredMultuipleTimesOnlyCancelOnce) {
+ location::nearby::FeatureFlags::Flags feature_flags_ =
+ location::nearby::FeatureFlags::Flags{
+ .enable_cancellation_flag = true,
+ };
+ MediumEnvironment::Instance().SetFeatureFlags(feature_flags_);
+
+ StrictMock<MockFunction<void()>> mock_cancel_callback;
+ CancellationFlag::CancelListener cancel_callback =
+ mock_cancel_callback.AsStdFunction();
+ EXPECT_CALL(mock_cancel_callback, Call).Times(1);
+
+ CancellationFlag flag;
+ CancellationFlagPeer flag_peer(&flag);
+ flag_peer.RegisterOnCancelListener(&cancel_callback);
+ flag_peer.RegisterOnCancelListener(&cancel_callback);
+ EXPECT_EQ(1, flag_peer.CancelListenersSize());
+
+ flag.Cancel();
+
+ flag_peer.UnregisterOnCancelListener(&cancel_callback);
+ EXPECT_EQ(0, flag_peer.CancelListenersSize());
+ flag_peer.UnregisterOnCancelListener(&cancel_callback);
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/condition_variable.h b/chromium/third_party/nearby/src/internal/platform/condition_variable.h
new file mode 100644
index 00000000000..26898be4b6d
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/condition_variable.h
@@ -0,0 +1,49 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_CONDITION_VARIABLE_H_
+#define PLATFORM_PUBLIC_CONDITION_VARIABLE_H_
+
+#include "internal/platform/implementation/condition_variable.h"
+#include "internal/platform/implementation/platform.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/mutex.h"
+
+namespace location {
+namespace nearby {
+
+// The ConditionVariable class is a synchronization primitive that can be used
+// to block a thread, or multiple threads at the same time, until another thread
+// both modifies a shared variable (the condition), and notifies the
+// ConditionVariable.
+class ConditionVariable final {
+ public:
+ using Platform = api::ImplementationPlatform;
+ explicit ConditionVariable(Mutex* mutex)
+ : impl_(Platform::CreateConditionVariable(mutex->impl_.get())) {}
+ ConditionVariable(ConditionVariable&&) = default;
+ ConditionVariable& operator=(ConditionVariable&&) = default;
+
+ void Notify() { impl_->Notify(); }
+ Exception Wait() { return impl_->Wait(); }
+ Exception Wait(absl::Duration timeout) { return impl_->Wait(timeout); }
+
+ private:
+ std::unique_ptr<api::ConditionVariable> impl_;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_CONDITION_VARIABLE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/condition_variable_test.cc b/chromium/third_party/nearby/src/internal/platform/condition_variable_test.cc
new file mode 100644
index 00000000000..f11ee2f13cb
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/condition_variable_test.cc
@@ -0,0 +1,83 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/condition_variable.h"
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "absl/time/time.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/mutex.h"
+#include "internal/platform/single_thread_executor.h"
+#include "internal/platform/system_clock.h"
+
+namespace location {
+namespace nearby {
+namespace {
+
+TEST(ConditionVariableTest, CanCreate) {
+ Mutex mutex;
+ ConditionVariable cond{&mutex};
+}
+
+TEST(ConditionVariableTest, CanWakeupWaiter) {
+ Mutex mutex;
+ ConditionVariable cond{&mutex};
+ bool done = false;
+ bool waiting = false;
+ NEARBY_LOG(INFO, "At start; done=%d", done);
+ {
+ SingleThreadExecutor executor;
+ executor.Execute([&cond, &mutex, &done, &waiting]() {
+ MutexLock lock(&mutex);
+ NEARBY_LOG(INFO, "Before cond.Wait(); done=%d", done);
+ waiting = true;
+ cond.Wait();
+ waiting = false;
+ done = true;
+ NEARBY_LOG(INFO, "After cond.Wait(); done=%d", done);
+ });
+ while (true) {
+ {
+ MutexLock lock(&mutex);
+ if (waiting) break;
+ }
+ SystemClock::Sleep(absl::Milliseconds(100));
+ }
+ {
+ MutexLock lock(&mutex);
+ cond.Notify();
+ EXPECT_FALSE(done);
+ }
+ }
+ NEARBY_LOG(INFO, "After executor shutdown: done=%d", done);
+ EXPECT_TRUE(done);
+}
+
+TEST(ConditionVariableTest, WaitTerminatesOnTimeoutWithoutNotify) {
+ Mutex mutex;
+ ConditionVariable cond{&mutex};
+ MutexLock lock(&mutex);
+
+ const absl::Duration kWaitTime = absl::Milliseconds(100);
+ absl::Time start = SystemClock::ElapsedRealtime();
+ cond.Wait(kWaitTime);
+ absl::Duration duration = SystemClock::ElapsedRealtime() - start;
+ EXPECT_GE(duration, kWaitTime);
+}
+
+} // namespace
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/core_config.h b/chromium/third_party/nearby/src/internal/platform/core_config.h
index 9ccfa519921..9ccfa519921 100644
--- a/chromium/third_party/nearby/src/cpp/platform/public/core_config.h
+++ b/chromium/third_party/nearby/src/internal/platform/core_config.h
diff --git a/chromium/third_party/nearby/src/internal/platform/count_down_latch.h b/chromium/third_party/nearby/src/internal/platform/count_down_latch.h
new file mode 100644
index 00000000000..5d10c54e081
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/count_down_latch.h
@@ -0,0 +1,54 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_COUNT_DOWN_LATCH_H_
+#define PLATFORM_PUBLIC_COUNT_DOWN_LATCH_H_
+
+#include <cstdint>
+
+#include "absl/time/time.h"
+#include "internal/platform/implementation/count_down_latch.h"
+#include "internal/platform/implementation/platform.h"
+#include "internal/platform/exception.h"
+
+namespace location {
+namespace nearby {
+
+// A synchronization aid that allows one or more threads to wait until a set of
+// operations being performed in other threads completes.
+//
+// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html
+class CountDownLatch final {
+ public:
+ using Platform = api::ImplementationPlatform;
+ explicit CountDownLatch(int count)
+ : impl_(Platform::CreateCountDownLatch(count)) {}
+ CountDownLatch(const CountDownLatch&) = default;
+ CountDownLatch& operator=(const CountDownLatch&) = default;
+ ~CountDownLatch() = default;
+
+ Exception Await() { return impl_->Await(); }
+ ExceptionOr<bool> Await(absl::Duration timeout) {
+ return impl_->Await(timeout);
+ }
+ void CountDown() { impl_->CountDown(); }
+
+ private:
+ std::shared_ptr<api::CountDownLatch> impl_;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_COUNT_DOWN_LATCH_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/count_down_latch_test.cc b/chromium/third_party/nearby/src/internal/platform/count_down_latch_test.cc
new file mode 100644
index 00000000000..260317a7f9f
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/count_down_latch_test.cc
@@ -0,0 +1,70 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/count_down_latch.h"
+
+#include "gtest/gtest.h"
+#include "internal/platform/single_thread_executor.h"
+
+namespace location {
+namespace nearby {
+namespace {
+
+TEST(CountDownLatch, ConstructorDestructorWorks) { CountDownLatch latch(1); }
+
+TEST(CountDownLatch, LatchAwaitCanWait) {
+ CountDownLatch latch(1);
+ SingleThreadExecutor executor;
+ std::atomic_bool done = false;
+ executor.Execute([&done, &latch]() {
+ done = true;
+ latch.CountDown();
+ });
+ latch.Await();
+ EXPECT_TRUE(done);
+}
+
+TEST(CountDownLatch, LatchExtraCountDownIgnored) {
+ CountDownLatch latch(1);
+ SingleThreadExecutor executor;
+ std::atomic_bool done = false;
+ executor.Execute([&done, &latch]() {
+ done = true;
+ latch.CountDown();
+ latch.CountDown();
+ latch.CountDown();
+ });
+ latch.Await();
+ EXPECT_TRUE(done);
+}
+
+TEST(CountDownLatch, LatchAwaitWithTimeoutCanExpire) {
+ CountDownLatch latch(1);
+ SingleThreadExecutor executor;
+ auto response = latch.Await(absl::Milliseconds(100));
+ EXPECT_TRUE(response.ok());
+ EXPECT_FALSE(response.result());
+}
+
+TEST(CountDownLatch, InitialCountZero_AwaitDoesNotBlock) {
+ CountDownLatch latch(0);
+
+ auto response = latch.Await();
+
+ EXPECT_TRUE(response.Ok());
+}
+
+} // namespace
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/crypto.h b/chromium/third_party/nearby/src/internal/platform/crypto.h
new file mode 100644
index 00000000000..0b0bc6aa69f
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/crypto.h
@@ -0,0 +1,20 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_CRYPTO_H_
+#define PLATFORM_PUBLIC_CRYPTO_H_
+
+#include "internal/platform/implementation/crypto.h"
+
+#endif // PLATFORM_PUBLIC_CRYPTO_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/crypto_test.cc b/chromium/third_party/nearby/src/internal/platform/crypto_test.cc
new file mode 100644
index 00000000000..bfa3a39c75a
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/crypto_test.cc
@@ -0,0 +1,49 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/crypto.h"
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "internal/platform/byte_array.h"
+
+namespace location {
+namespace nearby {
+
+TEST(CryptoTest, Md5GeneratesHash) {
+ const ByteArray expected_md5(
+ "\xb4\x5c\xff\xe0\x84\xdd\x3d\x20\xd9\x28\xbe\xe8\x5e\x7b\x0f\x21");
+ ByteArray md5_hash = Crypto::Md5("string");
+ EXPECT_EQ(md5_hash, expected_md5);
+}
+
+TEST(CryptoTest, Md5ReturnsEmptyOnError) {
+ EXPECT_EQ(Crypto::Md5(""), ByteArray{});
+}
+
+TEST(CryptoTest, Sha256GeneratesHash) {
+ const ByteArray expected_sha256(
+ "\x47\x32\x87\xf8\x29\x8d\xba\x71\x63\xa8\x97\x90\x89\x58\xf7\xc0"
+ "\xea\xe7\x33\xe2\x5d\x2e\x02\x79\x92\xea\x2e\xdc\x9b\xed\x2f\xa8");
+ ByteArray sha256_hash = Crypto::Sha256("string");
+ EXPECT_EQ(sha256_hash, expected_sha256);
+}
+
+TEST(CryptoTest, Sha256ReturnsEmptyOnError) {
+ EXPECT_EQ(Crypto::Sha256(""), ByteArray{});
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/error_code_params.h b/chromium/third_party/nearby/src/internal/platform/error_code_params.h
new file mode 100644
index 00000000000..ad380b63999
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/error_code_params.h
@@ -0,0 +1,64 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_BASE_ERROR_CORE_PARAMS_H_
+#define PLATFORM_BASE_ERROR_CORE_PARAMS_H_
+
+#include "proto/connections_enums.pb.h"
+#include "proto/errorcode/error_code_enums.pb.h"
+
+namespace location {
+namespace nearby {
+
+// A struct to construct error code parameters for the analytics recorder.
+struct ErrorCodeParams {
+ location::nearby::proto::connections::Medium medium =
+ location::nearby::proto::connections::UNKNOWN_MEDIUM;
+ location::nearby::errorcode::proto::Event event =
+ location::nearby::errorcode::proto::UNKNOWN_EVENT;
+ location::nearby::errorcode::proto::Description description =
+ location::nearby::errorcode::proto::UNKNOWN;
+ std::string pii_message = {};
+ bool is_common_error = false;
+ location::nearby::errorcode::proto::CommonError common_error =
+ location::nearby::errorcode::proto::UNKNOWN_ERROR;
+ location::nearby::errorcode::proto::ConnectError connect_error =
+ location::nearby::errorcode::proto::UNKNOWN_CONNECT_ERROR;
+ location::nearby::errorcode::proto::DisconnectError disconnect_error =
+ location::nearby::errorcode::proto::UNKNOWN_DISCONNECT_ERROR;
+ location::nearby::errorcode::proto::StartAdvertisingError
+ start_advertising_error =
+ location::nearby::errorcode::proto::UNKNOWN_START_ADVERTISING_ERROR;
+ location::nearby::errorcode::proto::StopAdvertisingError
+ stop_advertising_error =
+ location::nearby::errorcode::proto::UNKNOWN_STOP_ADVERTISING_ERROR;
+ location::nearby::errorcode::proto::StartDiscoveringError
+ start_discovering_error =
+ location::nearby::errorcode::proto::UNKNOWN_START_DISCOVERING_ERROR;
+ location::nearby::errorcode::proto::StopDiscoveringError
+ stop_discovering_error =
+ location::nearby::errorcode::proto::UNKNOWN_STOP_DISCOVERING_ERROR;
+ location::nearby::errorcode::proto::StartListeningIncomingConnectionError
+ start_listening_incoming_connection_error = location::nearby::errorcode::
+ proto::UNKNOWN_START_LISTENING_INCOMING_CONNECTION_ERROR;
+ location::nearby::errorcode::proto::StopListeningIncomingConnectionError
+ stop_listening_incoming_connection_error = location::nearby::errorcode::
+ proto::UNKNOWN_STOP_LISTENING_INCOMING_CONNECTION_ERROR;
+ std::string connection_token = {};
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_BASE_ERROR_CORE_PARAMS_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/error_code_recorder.cc b/chromium/third_party/nearby/src/internal/platform/error_code_recorder.cc
new file mode 100644
index 00000000000..82e1d83f11c
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/error_code_recorder.cc
@@ -0,0 +1,116 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/error_code_recorder.h"
+
+#include "internal/platform/logging.h"
+#include "proto/errorcode/error_code_enums.pb.h"
+
+namespace location {
+namespace nearby {
+
+using ::location::nearby::errorcode::proto::CommonError;
+using ::location::nearby::errorcode::proto::CONNECT;
+using ::location::nearby::errorcode::proto::ConnectError;
+using ::location::nearby::errorcode::proto::Description;
+using ::location::nearby::errorcode::proto::DISCONNECT;
+using ::location::nearby::errorcode::proto::DisconnectError;
+using ::location::nearby::errorcode::proto::Event;
+using ::location::nearby::errorcode::proto::START_ADVERTISING;
+using ::location::nearby::errorcode::proto::START_DISCOVERING;
+using ::location::nearby::errorcode::proto::START_LISTENING_INCOMING_CONNECTION;
+using ::location::nearby::errorcode::proto::StartAdvertisingError;
+using ::location::nearby::errorcode::proto::StartDiscoveringError;
+using ::location::nearby::errorcode::proto::
+ StartListeningIncomingConnectionError;
+using ::location::nearby::errorcode::proto::STOP_ADVERTISING;
+using ::location::nearby::errorcode::proto::STOP_DISCOVERING;
+using ::location::nearby::errorcode::proto::STOP_LISTENING_INCOMING_CONNECTION;
+using ::location::nearby::errorcode::proto::StopAdvertisingError;
+using ::location::nearby::errorcode::proto::StopDiscoveringError;
+using ::location::nearby::errorcode::proto::
+ StopListeningIncomingConnectionError;
+using ::location::nearby::proto::connections::Medium;
+
+// Default static no-op listener
+ErrorCodeRecorder::ErrorCodeListener ErrorCodeRecorder::listener_ =
+ [](const ErrorCodeParams&) {};
+
+void ErrorCodeRecorder::LogErrorCode(Medium medium, Event event, int error,
+ Description description,
+ const std::string& pii_message,
+ const std::string& connection_token) {
+ NEARBY_LOGS(INFO) << "ErrorCodeRecorder LogErrorCode";
+ ErrorCodeParams params = BuildErrorCodeParams(
+ medium, event, error, description, pii_message, connection_token);
+ listener_(params);
+}
+
+ErrorCodeParams ErrorCodeRecorder::BuildErrorCodeParams(
+ Medium medium, Event event, int error, Description description,
+ const std::string& pii_message, const std::string& connection_token) {
+ ErrorCodeParams params = {.medium = medium,
+ .event = event,
+ .description = description,
+ .pii_message = pii_message,
+ .connection_token = connection_token};
+
+ if (errorcode::proto::CommonError_IsValid(error)) {
+ params.common_error = static_cast<CommonError>(error);
+ params.is_common_error = true;
+ } else {
+ params.is_common_error = false;
+ switch (event) {
+ case START_ADVERTISING:
+ params.start_advertising_error =
+ static_cast<StartAdvertisingError>(error);
+ break;
+ case STOP_ADVERTISING:
+ params.stop_advertising_error =
+ static_cast<StopAdvertisingError>(error);
+ break;
+ case START_LISTENING_INCOMING_CONNECTION:
+ params.start_listening_incoming_connection_error =
+ static_cast<StartListeningIncomingConnectionError>(error);
+ break;
+ case STOP_LISTENING_INCOMING_CONNECTION:
+ params.stop_listening_incoming_connection_error =
+ static_cast<StopListeningIncomingConnectionError>(error);
+ break;
+ case START_DISCOVERING:
+ params.start_discovering_error =
+ static_cast<StartDiscoveringError>(error);
+ break;
+ case STOP_DISCOVERING:
+ params.stop_discovering_error =
+ static_cast<StopDiscoveringError>(error);
+ break;
+ case CONNECT:
+ params.connect_error = static_cast<ConnectError>(error);
+ break;
+ case DISCONNECT:
+ params.disconnect_error = static_cast<DisconnectError>(error);
+ break;
+ // Set the error as unknown if undefined event passed in.
+ default:
+ params.common_error = errorcode::proto::UNKNOWN_ERROR;
+ params.is_common_error = true;
+ break;
+ }
+ }
+ return params;
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/error_code_recorder.h b/chromium/third_party/nearby/src/internal/platform/error_code_recorder.h
new file mode 100644
index 00000000000..d603a5422dd
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/error_code_recorder.h
@@ -0,0 +1,86 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_BASE_ERROR_CODE_RECORDER_H_
+#define PLATFORM_BASE_ERROR_CODE_RECORDER_H_
+
+#include <functional>
+
+#include "internal/platform/error_code_params.h"
+
+namespace location {
+namespace nearby {
+
+// Deploys the error code of the platform medium to the analytics recorder.
+//
+// The usage is to call static method ErrorCode::LogErrorCode(...) in each
+// medium platform supported whenever error occurred.
+class ErrorCodeRecorder {
+ public:
+ using ErrorCodeListener = std::function<void(const ErrorCodeParams&)>;
+
+ explicit ErrorCodeRecorder(ErrorCodeListener listener) {
+ listener_ = std::move(listener);
+ }
+ ErrorCodeRecorder(const ErrorCodeRecorder&) = delete;
+ ErrorCodeRecorder& operator=(const ErrorCodeRecorder&) = delete;
+
+ // Logs error code when medium error occurred.
+ //
+ // Caller should pass the exact matched event and error enum value except
+ // the common error.
+ // e.g.
+ // - START_ADVERTISING_FAILED(43) in StartAdvertisingError =>
+ // START_ADVERTISING event.
+ // - DISCONNECT_NETWORK_FAILED(31) in Disconnect_error => DISCONNECT event.
+ // - INVALID_PARAMETER(1) for Common_error, and the event will be kept as it
+ // is passed in.
+ //
+ // medium - An enum defined in proto::connections::Medium.
+ // event - An enum defined in errorcode::proto::Event.
+ // error - An enum integer value in the range from 0..30 defined
+ // in errorcode::proto::CommonError and the range from 31..
+ // nn defined among
+ // errorcode::proto::StartAdvertisingError to
+ // errorcode::proto::DisconnectError.
+ // description - A description defiend in errorcode::proto::description.
+ // pii_message - A pii info defiend in errorcode::proto::pii_message. An
+ // empty string won't be recorded.
+ // connection_token - connection token string.
+ static void LogErrorCode(
+ location::nearby::proto::connections::Medium medium,
+ location::nearby::errorcode::proto::Event event, int error,
+ location::nearby::errorcode::proto::Description description,
+ const std::string& pii_message, const std::string& connection_token);
+
+ // An auxiliary funciton for LogError() to assemble the ErrorCodeParams
+ // struct.
+ //
+ // See `LogErrorCode` for reference on the parameters.
+ static ErrorCodeParams BuildErrorCodeParams(
+ location::nearby::proto::connections::Medium medium,
+ location::nearby::errorcode::proto::Event event, int error,
+ location::nearby::errorcode::proto::Description description,
+ const std::string& pii_message, const std::string& connection_token);
+
+ private:
+ // A listener to call back to AnlayticsRecorder.OnErrorCode() by building
+ // error_code_params.
+ static ErrorCodeListener listener_;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_BASE_ERROR_CODE_RECORDER_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/error_code_recorder_test.cc b/chromium/third_party/nearby/src/internal/platform/error_code_recorder_test.cc
new file mode 100644
index 00000000000..a45b8db788f
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/error_code_recorder_test.cc
@@ -0,0 +1,137 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/error_code_recorder.h"
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+
+namespace location {
+namespace nearby {
+
+using ::testing::Field;
+using ::testing::MockFunction;
+using ::testing::StrictMock;
+
+TEST(ErrorCodeRecorderTest, TestListenerWork) {
+ StrictMock<MockFunction<void(const ErrorCodeParams& params)>> mock_listener;
+ ErrorCodeRecorder::ErrorCodeListener listener = mock_listener.AsStdFunction();
+ EXPECT_CALL(mock_listener, Call).Times(1);
+ ErrorCodeRecorder error_code_recorder(listener);
+
+ ErrorCodeRecorder::LogErrorCode(
+ proto::connections::BLE, errorcode::proto::START_ADVERTISING,
+ errorcode::proto::MULTIPLE_FAST_ADVERTISEMENT_NOT_ALLOWED,
+ errorcode::proto::FEATURE_BLUETOOTH_NOT_SUPPORTED, "pii_message",
+ "connection_token");
+}
+
+TEST(ErrorCodeRecorderTest, TestBuildErrorCodeParamsWork) {
+ std::string pii_message = "pii_message";
+ std::string connection_token = "connection_token";
+
+ ErrorCodeParams error_code_params;
+ ErrorCodeRecorder error_recorder(
+ [&error_code_params](const ErrorCodeParams& params) {
+ error_code_params = std::move(params);
+ });
+
+ ErrorCodeRecorder::LogErrorCode(
+ proto::connections::BLE, errorcode::proto::START_ADVERTISING,
+ errorcode::proto::MULTIPLE_FAST_ADVERTISEMENT_NOT_ALLOWED,
+ errorcode::proto::FEATURE_BLUETOOTH_NOT_SUPPORTED, pii_message,
+ connection_token);
+
+ EXPECT_THAT(
+ error_code_params,
+ AllOf(Field("medium", &ErrorCodeParams::medium, proto::connections::BLE),
+ Field("event", &ErrorCodeParams::event,
+ errorcode::proto::START_ADVERTISING),
+ Field("description", &ErrorCodeParams::description,
+ errorcode::proto::FEATURE_BLUETOOTH_NOT_SUPPORTED),
+ Field("pii_message", &ErrorCodeParams::pii_message, pii_message),
+ Field("is_common_error", &ErrorCodeParams::is_common_error, false),
+ Field("start_advertising_error",
+ &ErrorCodeParams::start_advertising_error,
+ errorcode::proto::MULTIPLE_FAST_ADVERTISEMENT_NOT_ALLOWED),
+ Field("connection_token", &ErrorCodeParams::connection_token,
+ connection_token)));
+}
+
+TEST(ErrorCodeRecorderTest, TestBuildErrorCodeParamsWorkForCommonError) {
+ std::string pii_message = "pii_message";
+ std::string connection_token = "connection_token";
+
+ ErrorCodeParams error_code_params;
+ ErrorCodeRecorder error_recorder(
+ [&error_code_params](const ErrorCodeParams& params) {
+ error_code_params = std::move(params);
+ });
+
+ ErrorCodeRecorder::LogErrorCode(
+ proto::connections::BLE, errorcode::proto::START_ADVERTISING,
+ errorcode::proto::INVALID_PARAMETER, errorcode::proto::NULL_SERVICE_ID,
+ pii_message, connection_token);
+
+ EXPECT_THAT(
+ error_code_params,
+ AllOf(Field("medium", &ErrorCodeParams::medium, proto::connections::BLE),
+ Field("event", &ErrorCodeParams::event,
+ errorcode::proto::START_ADVERTISING),
+ Field("description", &ErrorCodeParams::description,
+ errorcode::proto::NULL_SERVICE_ID),
+ Field("pii_message", &ErrorCodeParams::pii_message, pii_message),
+ Field("is_common_error", &ErrorCodeParams::is_common_error, true),
+ Field("common_error", &ErrorCodeParams::common_error,
+ errorcode::proto::INVALID_PARAMETER),
+ Field("connection_token", &ErrorCodeParams::connection_token,
+ connection_token)));
+}
+
+TEST(ErrorCodeRecorderTest, TestBuildErrorCodeParamsWorkForUnknownEvent) {
+ std::string pii_message = "pii_message";
+ std::string connection_token = "connection_token";
+
+ ErrorCodeParams error_code_params;
+ ErrorCodeRecorder error_recorder(
+ [&error_code_params](const ErrorCodeParams& params) {
+ error_code_params = std::move(params);
+ });
+
+ // If event is UNKNOWN_EVENT and the error is not Common_Error then the error
+ // will be set to UNKNOWN_ERROR.
+ ErrorCodeRecorder::LogErrorCode(
+ proto::connections::BLE, errorcode::proto::UNKNOWN_EVENT,
+ errorcode::proto::MULTIPLE_FAST_ADVERTISEMENT_NOT_ALLOWED,
+ errorcode::proto::FEATURE_BLUETOOTH_NOT_SUPPORTED, pii_message,
+ connection_token);
+
+ EXPECT_THAT(
+ error_code_params,
+ AllOf(Field("medium", &ErrorCodeParams::medium, proto::connections::BLE),
+ Field("event", &ErrorCodeParams::event,
+ errorcode::proto::UNKNOWN_EVENT),
+ Field("description", &ErrorCodeParams::description,
+ errorcode::proto::FEATURE_BLUETOOTH_NOT_SUPPORTED),
+ Field("pii_message", &ErrorCodeParams::pii_message, pii_message),
+ Field("is_common_error", &ErrorCodeParams::is_common_error, true),
+ Field("common_error", &ErrorCodeParams::common_error,
+ errorcode::proto::UNKNOWN_ERROR),
+ Field("connection_token", &ErrorCodeParams::connection_token,
+ connection_token)));
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/exception.h b/chromium/third_party/nearby/src/internal/platform/exception.h
index e8bcd8c4ae3..e8bcd8c4ae3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/base/exception.h
+++ b/chromium/third_party/nearby/src/internal/platform/exception.h
diff --git a/chromium/third_party/nearby/src/internal/platform/exception_test.cc b/chromium/third_party/nearby/src/internal/platform/exception_test.cc
new file mode 100644
index 00000000000..63aed3d6861
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/exception_test.cc
@@ -0,0 +1,121 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/exception.h"
+
+#include <vector>
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "internal/platform/exception_test.nc.h"
+
+namespace location::nearby {
+
+TEST(ExceptionOr, Result_Copy_NonConst) {
+ ExceptionOr<std::vector<int>> exception_or_vector({1, 2, 3});
+ EXPECT_FALSE(exception_or_vector.result().empty());
+
+ // Expect a copy when not explicitly moving the result.
+ std::vector<int> copy = exception_or_vector.result();
+ EXPECT_FALSE(copy.empty());
+ EXPECT_FALSE(exception_or_vector.result().empty());
+
+ // Modifying |exception_or_vector| should not affect the copy.
+ exception_or_vector.result().clear();
+ EXPECT_FALSE(copy.empty());
+}
+
+TEST(ExceptionOr, Result_Copy_Const) {
+ const ExceptionOr<std::vector<int>> exception_or_vector({1, 2, 3});
+ EXPECT_FALSE(exception_or_vector.result().empty());
+
+ // Expect a copy when not explicitly moving the result.
+ const std::vector<int>& copy = exception_or_vector.result();
+ EXPECT_FALSE(copy.empty());
+ EXPECT_FALSE(exception_or_vector.result().empty());
+}
+
+TEST(ExceptionOr, Result_Reference_NonConst) {
+ ExceptionOr<std::vector<int>> exception_or_vector({1, 2, 3});
+ EXPECT_FALSE(exception_or_vector.result().empty());
+
+ // Getting a reference should not modify the source.
+ std::vector<int>& reference = exception_or_vector.result();
+ EXPECT_FALSE(reference.empty());
+ EXPECT_FALSE(exception_or_vector.result().empty());
+
+ // Modifying |exception_or_vector| should reflect in the reference.
+ exception_or_vector.result().clear();
+ EXPECT_TRUE(reference.empty());
+}
+
+TEST(ExceptionOr, Result_Reference_Const) {
+ const ExceptionOr<std::vector<int>> exception_or_vector({1, 2, 3});
+ EXPECT_FALSE(exception_or_vector.result().empty());
+
+ // Getting a reference should not modify the source.
+ const std::vector<int>& reference = exception_or_vector.result();
+ EXPECT_FALSE(reference.empty());
+ EXPECT_FALSE(exception_or_vector.result().empty());
+}
+
+TEST(ExceptionOr, Result_Move_NonConst) {
+ ExceptionOr<std::vector<int>> exception_or_vector({1, 2, 3});
+ EXPECT_FALSE(exception_or_vector.result().empty());
+
+ // Moving the result should clear the source.
+ std::vector<int> moved = std::move(exception_or_vector).result();
+ EXPECT_FALSE(moved.empty());
+}
+
+TEST(ExceptionOr, Result_Move_Const) {
+ const ExceptionOr<std::vector<int>> exception_or_vector({1, 2, 3});
+ EXPECT_FALSE(exception_or_vector.result().empty());
+
+ // Moving const rvalue reference will result in a copy.
+ std::vector<int> moved = std::move(exception_or_vector).result();
+ EXPECT_FALSE(moved.empty());
+}
+
+TEST(ExceptionOr, ExplicitConversionWorks) {
+ class A {
+ public:
+ A() = default;
+ };
+ class B {
+ public:
+ B() = default;
+ explicit B(A) {}
+ };
+ ExceptionOr<A> a(A{});
+ ExceptionOr<B> b(a);
+ EXPECT_TRUE(a.ok());
+ EXPECT_TRUE(b.ok());
+}
+
+TEST(ExceptionOr, ExplicitConversionFailsToCompile) {
+ class A {
+ public:
+ A() = default;
+ };
+ class B {
+ public:
+ B() = default;
+ };
+ ExceptionOr<A> a(A{});
+ EXPECT_NON_COMPILE("no matching constructor", { ExceptionOr<B> b(a); });
+}
+
+} // namespace location::nearby
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/feature_flags.h b/chromium/third_party/nearby/src/internal/platform/feature_flags.h
index a0b2e19bef5..a0b2e19bef5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/base/feature_flags.h
+++ b/chromium/third_party/nearby/src/internal/platform/feature_flags.h
diff --git a/chromium/third_party/nearby/src/internal/platform/feature_flags_test.cc b/chromium/third_party/nearby/src/internal/platform/feature_flags_test.cc
new file mode 100644
index 00000000000..21e7405d25c
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/feature_flags_test.cc
@@ -0,0 +1,46 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/feature_flags.h"
+
+#include "gtest/gtest.h"
+#include "internal/platform/medium_environment.h"
+
+namespace location {
+namespace nearby {
+namespace {
+
+constexpr FeatureFlags::Flags kTestFeatureFlags{
+ .enable_cancellation_flag = true,
+ .keep_alive_interval_millis = 5000,
+ .keep_alive_timeout_millis = 30000};
+
+TEST(FeatureFlagsTest, ToSetFeatureWorks) {
+ const FeatureFlags& features = FeatureFlags::GetInstance();
+ EXPECT_FALSE(features.GetFlags().enable_cancellation_flag);
+
+ EXPECT_EQ(5000, features.GetFlags().keep_alive_interval_millis);
+ EXPECT_EQ(30000, features.GetFlags().keep_alive_timeout_millis);
+
+ MediumEnvironment& medium_environment = MediumEnvironment::Instance();
+ medium_environment.SetFeatureFlags(kTestFeatureFlags);
+ EXPECT_TRUE(features.GetFlags().enable_cancellation_flag);
+
+ const FeatureFlags& another_features_ref = FeatureFlags::GetInstance();
+ EXPECT_TRUE(another_features_ref.GetFlags().enable_cancellation_flag);
+}
+
+} // namespace
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/file.cc b/chromium/third_party/nearby/src/internal/platform/file.cc
new file mode 100644
index 00000000000..6deaec2553f
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/file.cc
@@ -0,0 +1,92 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/file.h"
+
+namespace location {
+namespace nearby {
+
+InputFile::InputFile(PayloadId payload_id, std::int64_t size)
+ : impl_(Platform::CreateInputFile(payload_id, size)), id_(payload_id) {}
+InputFile::~InputFile() = default;
+InputFile::InputFile(InputFile&&) noexcept = default;
+InputFile& InputFile::operator=(InputFile&&) noexcept = default;
+
+// Reads up to size bytes and returns as a ByteArray object wrapped by
+// ExceptionOr.
+// Returns Exception::kIo on error, or end of file.
+ExceptionOr<ByteArray> InputFile::Read(std::int64_t size) {
+ return impl_->Read(size);
+}
+
+// Returns a string that uniqely identifies this file.
+std::string InputFile::GetFilePath() const { return impl_->GetFilePath(); }
+
+// Returns total size of this file in bytes.
+std::int64_t InputFile::GetTotalSize() const { return impl_->GetTotalSize(); }
+
+ExceptionOr<size_t> InputFile::Skip(size_t offset) {
+ return impl_->Skip(offset);
+}
+
+// Disallows further reads from the file and frees system resources,
+// associated with it.
+Exception InputFile::Close() { return impl_->Close(); }
+
+// Returns a handle to the underlying input stream.
+//
+// Returned handle will remain valid even if InputFile is moved, for as long
+// as original InputFile lifetime continues.
+// Side effects of any non-const operation invoked for InputFile (such as
+// Read, or Close will be observable through InputStream& handle, and vice
+// versa.
+InputStream& InputFile::GetInputStream() { return *impl_; }
+
+// Returns payload id of this file. The closest "file" equivalent is inode.
+PayloadId InputFile::GetPayloadId() const { return id_; }
+
+OutputFile::OutputFile(PayloadId payload_id)
+ : impl_(Platform::CreateOutputFile(payload_id)), id_(payload_id) {}
+OutputFile::~OutputFile() = default;
+OutputFile::OutputFile(OutputFile&&) noexcept = default;
+OutputFile& OutputFile::operator=(OutputFile&&) noexcept = default;
+
+// Writes all data from ByteArray object to the underlying stream.
+// Returns Exception::kIo on error, Exception::kSuccess otherwise.
+Exception OutputFile::Write(const ByteArray& data) {
+ return impl_->Write(data);
+}
+
+// Ensures that all data written by previous calls to Write() is passed
+// down to the applicable transport layer.
+Exception OutputFile::Flush() { return impl_->Flush(); }
+
+// Disallows further writes to the file and frees system resources,
+// associated with it.
+Exception OutputFile::Close() { return impl_->Close(); }
+
+// Returns a handle to the underlying output stream.
+//
+// Returned handle will remain valid even if OutputFile is moved, for as long
+// as original OutputFile lifetime continues.
+// Side effects of any non-const operation invoked for OutputFile (such as
+// Write, or Close will be observable through OutputStream& handle, and vice
+// versa.
+OutputStream& OutputFile::GetOutputStream() { return *impl_; }
+
+// Returns payload id of this file. The closest "file" equivalent is inode.
+PayloadId OutputFile::GetPayloadId() const { return id_; }
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/file.h b/chromium/third_party/nearby/src/internal/platform/file.h
new file mode 100644
index 00000000000..718d5414c2e
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/file.h
@@ -0,0 +1,116 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_FILE_H_
+#define PLATFORM_PUBLIC_FILE_H_
+
+#include <cstdint>
+#include <memory>
+#include <string>
+
+#include "internal/platform/implementation/input_file.h"
+#include "internal/platform/implementation/output_file.h"
+#include "internal/platform/implementation/platform.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/input_stream.h"
+#include "internal/platform/output_stream.h"
+#include "internal/platform/core_config.h"
+
+namespace location {
+namespace nearby {
+
+class DLL_API InputFile final {
+ public:
+ using Platform = api::ImplementationPlatform;
+ InputFile(PayloadId payload_id, std::int64_t size);
+ ~InputFile();
+ InputFile(InputFile&&) noexcept;
+ InputFile& operator=(InputFile&&) noexcept;
+
+ // Reads up to size bytes and returns as a ByteArray object wrapped by
+ // ExceptionOr.
+ // Returns Exception::kIo on error, or end of file.
+ ExceptionOr<ByteArray> Read(std::int64_t size);
+
+ // Returns a string that uniqely identifies this file.
+ std::string GetFilePath() const;
+
+ // Returns total size of this file in bytes.
+ std::int64_t GetTotalSize() const;
+
+ ExceptionOr<size_t> Skip(size_t offset);
+
+ // Disallows further reads from the file and frees system resources,
+ // associated with it.
+ Exception Close();
+
+ // Returns a handle to the underlying input stream.
+ //
+ // Returned handle will remain valid even if InputFile is moved, for as long
+ // as original InputFile lifetime continues.
+ // Side effects of any non-const operation invoked for InputFile (such as
+ // Read, or Close will be observable through InputStream& handle, and vice
+ // versa.
+ InputStream& GetInputStream();
+
+ // Returns payload id of this file. The closest "file" equivalent is inode.
+ PayloadId GetPayloadId() const;
+
+ private:
+ std::unique_ptr<api::InputFile> impl_;
+ PayloadId id_;
+};
+
+class DLL_API OutputFile final {
+ public:
+ using Platform = api::ImplementationPlatform;
+ explicit OutputFile(PayloadId payload_id);
+ ~OutputFile();
+ OutputFile(OutputFile&&) noexcept;
+ OutputFile& operator=(OutputFile&&) noexcept;
+
+ // Writes all data from ByteArray object to the underlying stream.
+ // Returns Exception::kIo on error, Exception::kSuccess otherwise.
+ Exception Write(const ByteArray& data);
+
+ // Ensures that all data written by previous calls to Write() is passed
+ // down to the applicable transport layer.
+ Exception Flush();
+
+ // Disallows further writes to the file and frees system resources,
+ // associated with it.
+ Exception Close();
+
+ // Returns a handle to the underlying output stream.
+ //
+ // Returned handle will remain valid even if OutputFile is moved, for as long
+ // as original OutputFile lifetime continues.
+ // Side effects of any non-const operation invoked for OutputFile (such as
+ // Write, or Close will be observable through OutputStream& handle, and vice
+ // versa.
+ OutputStream& GetOutputStream();
+
+ // Returns payload id of this file. The closest "file" equivalent is inode.
+ PayloadId GetPayloadId() const;
+
+ private:
+ std::unique_ptr<api::OutputFile> impl_;
+ PayloadId id_;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_FILE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/future.h b/chromium/third_party/nearby/src/internal/platform/future.h
new file mode 100644
index 00000000000..88286b84518
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/future.h
@@ -0,0 +1,56 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_FUTURE_H_
+#define PLATFORM_PUBLIC_FUTURE_H_
+
+#include "internal/platform/settable_future.h"
+
+namespace location {
+namespace nearby {
+
+template <typename T>
+class Future final {
+ public:
+ virtual bool Set(T value) { return impl_->Set(std::move(value)); }
+ virtual bool SetException(Exception exception) {
+ return impl_->SetException(exception);
+ }
+ virtual ExceptionOr<T> Get() { return impl_->Get(); }
+ virtual ExceptionOr<T> Get(absl::Duration timeout) {
+ return impl_->Get(timeout);
+ }
+ void AddListener(Runnable runnable, api::Executor* executor) {
+ impl_->AddListener(std::move(runnable), executor);
+ }
+ bool IsSet() const { return impl_->IsSet(); }
+
+ private:
+ // Instance of future implementation is wrapped in shared_ptr<> to make
+ // it possible to pass Future by value and share the implementation.
+ // This allows for the following constructions:
+ // 1)
+ // Future<bool> future;
+ // RunOnXyzThread([future]() { future.Set(DoTheJobAndReport()); });
+ // if (future.Get().Ok()) { /*...*/ }
+ // 2)
+ // Future<bool> future = DoSomeAsyncWork(); // Returns future, but keeps copy.
+ // if (future.Get().Ok()) { /*...*/ }
+ std::shared_ptr<SettableFuture<T>> impl_{new SettableFuture<T>()};
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_FUTURE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/future_test.cc b/chromium/third_party/nearby/src/internal/platform/future_test.cc
new file mode 100644
index 00000000000..d1ece61001f
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/future_test.cc
@@ -0,0 +1,116 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/future.h"
+
+#include "gtest/gtest.h"
+#include "absl/time/clock.h"
+#include "absl/time/time.h"
+#include "internal/platform/single_thread_executor.h"
+
+namespace location {
+namespace nearby {
+
+namespace {
+
+enum TestEnum {
+ kValue1 = 1,
+ kValue2 = 2,
+};
+
+enum class ScopedTestEnum {
+ kValue1 = 1,
+ kValue2 = 2,
+};
+
+struct BigSizedStruct {
+ int data[100]{};
+};
+
+bool operator==(const BigSizedStruct& a, const BigSizedStruct& b) {
+ return memcmp(a.data, b.data, sizeof(BigSizedStruct::data)) == 0;
+}
+
+bool operator!=(const BigSizedStruct& a, const BigSizedStruct& b) {
+ return !(a == b);
+}
+
+} // namespace
+
+TEST(FutureTest, SupportIntegralTypes) {
+ Future<int> future;
+ future.Set(5);
+ EXPECT_EQ(future.Get().exception(), Exception::kSuccess);
+ EXPECT_EQ(future.Get().result(), 5);
+}
+
+TEST(FutureTest, SetExceptionIsPropagated) {
+ Future<int> future;
+ future.SetException({Exception::kIo});
+ EXPECT_EQ(future.Get().exception(), Exception::kIo);
+}
+
+TEST(FutureTest, SupportEnum) {
+ Future<TestEnum> future;
+ future.Set(TestEnum::kValue1);
+ EXPECT_EQ(future.Get().exception(), Exception::kSuccess);
+ EXPECT_EQ(future.Get().result(), TestEnum::kValue1);
+}
+
+TEST(FutureTest, SupportScopedEnum) {
+ Future<ScopedTestEnum> future;
+ future.Set(ScopedTestEnum::kValue1);
+ EXPECT_EQ(future.Get().exception(), Exception::kSuccess);
+ EXPECT_EQ(future.Get().result(), ScopedTestEnum::kValue1);
+}
+
+TEST(FutureTest, SetTakesCopyOfValue) {
+ // Default constructor is zero-initalizing all data in BigSizedStruct.
+ BigSizedStruct v1;
+ Future<BigSizedStruct> future;
+ v1.data[0] = 5; // Changing value before calling Set() will affect stored
+ v1.data[7] = 3; // value.
+ future.Set(v1);
+ v1.data[1] = 6; // Changing value after calling Set() will not affect stored
+ v1.data[5] = 4; // value.
+ EXPECT_EQ(future.Get().exception(), Exception::kSuccess);
+ BigSizedStruct v2 = future.Get().result();
+ EXPECT_NE(v1, v2);
+ v1.data[1] = 0;
+ v1.data[5] = 0;
+ EXPECT_EQ(v2, v1);
+}
+
+TEST(FutureTest, SetsExceptionOnTimeout) {
+ Future<int> future;
+ EXPECT_EQ(future.Get(absl::Milliseconds(100)).exception(),
+ Exception::kTimeout);
+}
+
+TEST(FutureTest, GetBlocksWhenNotReady) {
+ Future<int> future;
+ SingleThreadExecutor executor;
+ absl::Time start = absl::Now();
+ executor.Execute([&future]() {
+ absl::SleepFor(absl::Milliseconds(500));
+ future.Set(10);
+ });
+ auto response = future.Get();
+ absl::Duration blocked_duration = absl::Now() - start;
+ EXPECT_EQ(response.result(), 10);
+ EXPECT_GE(blocked_duration, absl::Milliseconds(500));
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/BUILD b/chromium/third_party/nearby/src/internal/platform/implementation/BUILD
new file mode 100644
index 00000000000..d8b24814915
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/BUILD
@@ -0,0 +1,94 @@
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+licenses(["notice"])
+
+cc_library(
+ name = "types",
+ hdrs = [
+ "atomic_boolean.h",
+ "atomic_reference.h",
+ "bluetooth_adapter.h",
+ "cancelable.h",
+ "condition_variable.h",
+ "count_down_latch.h",
+ "crypto.h",
+ "executor.h",
+ "future.h",
+ "input_file.h",
+ "listenable_future.h",
+ "log_message.h",
+ "mutex.h",
+ "output_file.h",
+ "scheduled_executor.h",
+ "settable_future.h",
+ "submittable_executor.h",
+ "system_clock.h",
+ ],
+ defines = ["NO_WEBRTC"],
+ visibility = [
+ "//internal/platform:__pkg__",
+ "//internal/platform/implementation:__subpackages__",
+ ],
+ deps = [
+ "//internal/platform:base",
+ "@com_google_absl//absl/base:core_headers",
+ "@com_google_absl//absl/strings",
+ "@com_google_absl//absl/time",
+ ],
+)
+
+cc_library(
+ name = "comm",
+ hdrs = [
+ "ble.h",
+ "ble_v2.h",
+ "bluetooth_adapter.h",
+ "bluetooth_classic.h",
+ "server_sync.h",
+ "wifi.h",
+ "wifi_lan.h",
+ ],
+ defines = ["NO_WEBRTC"],
+ visibility = [
+ "//connections/implementation:__subpackages__",
+ "//internal/platform:__pkg__",
+ "//internal/platform/implementation:__subpackages__",
+ ],
+ deps = [
+ "//connections/implementation/proto:offline_wire_formats_cc_proto",
+ "//internal/platform:base",
+ "//internal/platform:cancellation_flag",
+ "@com_google_absl//absl/strings",
+ "@com_google_absl//absl/types:optional",
+ ],
+)
+
+cc_library(
+ name = "platform",
+ hdrs = [
+ "platform.h",
+ ],
+ defines = ["NO_WEBRTC"],
+ visibility = [
+ "//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
+ "//internal/platform:__pkg__",
+ "//internal/platform/implementation:__subpackages__",
+ ],
+ deps = [
+ ":comm",
+ ":types",
+ "//internal/platform:base",
+ "@com_google_absl//absl/strings",
+ ],
+)
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/atomic_boolean.h b/chromium/third_party/nearby/src/internal/platform/implementation/atomic_boolean.h
index e00179243d0..e00179243d0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/api/atomic_boolean.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/atomic_boolean.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/atomic_reference.h b/chromium/third_party/nearby/src/internal/platform/implementation/atomic_reference.h
index a6f4c93dc15..a6f4c93dc15 100644
--- a/chromium/third_party/nearby/src/cpp/platform/api/atomic_reference.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/atomic_reference.h
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ble.h b/chromium/third_party/nearby/src/internal/platform/implementation/ble.h
new file mode 100644
index 00000000000..fdc1e85d664
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ble.h
@@ -0,0 +1,125 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_API_BLE_H_
+#define PLATFORM_API_BLE_H_
+
+#include "internal/platform/implementation/bluetooth_classic.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/cancellation_flag.h"
+#include "internal/platform/input_stream.h"
+#include "internal/platform/output_stream.h"
+
+namespace location {
+namespace nearby {
+namespace api {
+
+// Opaque wrapper over a BLE peripheral. Must contain enough data about a
+// particular BLE device to connect to its GATT server.
+class BlePeripheral {
+ public:
+ virtual ~BlePeripheral() = default;
+
+ virtual std::string GetName() const = 0;
+
+ virtual ByteArray GetAdvertisementBytes(
+ const std::string& service_id) const = 0;
+};
+
+class BleSocket {
+ public:
+ virtual ~BleSocket() = default;
+
+ // Returns the InputStream of the BleSocket.
+ // On error, returned stream will report Exception::kIo on any operation.
+ //
+ // The returned object is not owned by the caller, and can be invalidated once
+ // the BleSocket object is destroyed.
+ virtual InputStream& GetInputStream() = 0;
+
+ // Returns the OutputStream of the BleSocket.
+ // On error, returned stream will report Exception::kIo on any operation.
+ //
+ // The returned object is not owned by the caller, and can be invalidated once
+ // the BleSocket object is destroyed.
+ virtual OutputStream& GetOutputStream() = 0;
+
+ // Conforms to the same contract as
+ // https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#close().
+ //
+ // Returns Exception::kIo on error, Exception::kSuccess otherwise.
+ virtual Exception Close() = 0;
+
+ // Returns valid BlePeripheral pointer if there is a connection, and
+ // nullptr otherwise.
+ virtual BlePeripheral* GetRemotePeripheral() = 0;
+};
+
+// Container of operations that can be performed over the BLE medium.
+class BleMedium {
+ public:
+ virtual ~BleMedium() = default;
+
+ virtual bool StartAdvertising(
+ const std::string& service_id, const ByteArray& advertisement_bytes,
+ const std::string& fast_advertisement_service_uuid) = 0;
+ virtual bool StopAdvertising(const std::string& service_id) = 0;
+
+ // Callback that is invoked when a discovered peripheral is found or lost.
+ struct DiscoveredPeripheralCallback {
+ std::function<void(BlePeripheral& peripheral, const std::string& service_id,
+ bool fast_advertisement)>
+ peripheral_discovered_cb =
+ DefaultCallback<BlePeripheral&, const std::string&, bool>();
+ std::function<void(BlePeripheral& peripheral,
+ const std::string& service_id)>
+ peripheral_lost_cb =
+ DefaultCallback<BlePeripheral&, const std::string&>();
+ };
+
+ // Returns true once the BLE scan has been initiated.
+ virtual bool StartScanning(const std::string& service_id,
+ const std::string& fast_advertisement_service_uuid,
+ DiscoveredPeripheralCallback callback) = 0;
+
+ // Returns true once BLE scanning for service_id is well and truly stopped;
+ // after this returns, there must be no more invocations of the
+ // DiscoveredPeripheralCallback passed in to StartScanning() for service_id.
+ virtual bool StopScanning(const std::string& service_id) = 0;
+
+ // Callback that is invoked when a new connection is accepted.
+ struct AcceptedConnectionCallback {
+ std::function<void(BleSocket& socket, const std::string& service_id)>
+ accepted_cb = DefaultCallback<BleSocket&, const std::string&>();
+ };
+
+ // Returns true once BLE socket connection requests to service_id can be
+ // accepted.
+ virtual bool StartAcceptingConnections(
+ const std::string& service_id, AcceptedConnectionCallback callback) = 0;
+ virtual bool StopAcceptingConnections(const std::string& service_id) = 0;
+
+ // Connects to a BLE peripheral.
+ // On success, returns a new BleSocket.
+ // On error, returns nullptr.
+ virtual std::unique_ptr<BleSocket> Connect(
+ BlePeripheral& peripheral, const std::string& service_id,
+ CancellationFlag* cancellation_flag) = 0;
+};
+
+} // namespace api
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_API_BLE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ble_v2.h b/chromium/third_party/nearby/src/internal/platform/implementation/ble_v2.h
new file mode 100644
index 00000000000..8a20d0b7bed
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ble_v2.h
@@ -0,0 +1,406 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_API_BLE_V2_H_
+#define PLATFORM_API_BLE_V2_H_
+
+#include <cstdint>
+#include <limits>
+#include <map>
+#include <memory>
+#include <set>
+#include <string>
+
+#include "absl/strings/string_view.h"
+#include "absl/types/optional.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/exception.h"
+
+namespace location {
+namespace nearby {
+namespace api {
+namespace ble_v2 {
+
+// https://developer.android.com/reference/android/bluetooth/le/AdvertiseData
+//
+// Bundle of data found in a BLE advertisement.
+//
+// All service UUIDs will conform to the 16-bit Bluetooth base UUID,
+// 0000xxxx-0000-1000-8000-00805F9B34FB. This makes it possible to store two
+// byte service UUIDs in the advertisement.
+struct BleAdvertisementData {
+ using TxPowerLevel = int8_t;
+
+ static const TxPowerLevel kUnspecifiedTxPowerLevel =
+ std::numeric_limits<TxPowerLevel>::min();
+
+ bool is_connectable;
+ // When set to kUnspecifiedTxPowerLevel, TX power should not be included in
+ // the advertisement data.
+ TxPowerLevel tx_power_level;
+ // When set to an empty string, local name should not be included in the
+ // advertisement data.
+ std::string local_name;
+ // When set to an empty vector, the set of 16-bit service class UUIDs should
+ // not be included in the advertisement data.
+ std::set<std::string> service_uuids;
+ // Maps service UUIDs to their service data.
+ std::map<std::string, ByteArray> service_data;
+};
+
+// Opaque wrapper over a BLE peripheral. Must be able to uniquely identify a
+// peripheral so that we can connect to its GATT server.
+class BlePeripheral {
+ public:
+ virtual ~BlePeripheral() {}
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothDevice#getAddress()
+ //
+ // This should be the MAC address when possible. If the implementation is
+ // unable to retrieve that, any unique identifier should suffice.
+ virtual std::string GetId() const = 0;
+};
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic
+//
+// Representation of a GATT characteristic.
+class GattCharacteristic {
+ public:
+ virtual ~GattCharacteristic() {}
+
+ // Possible permissions of a GATT characteristic.
+ enum class Permission {
+ kUnknown = 0,
+ kRead = 1,
+ kWrite = 2,
+ kLast,
+ };
+
+ // Possible properties of a GATT characteristic.
+ enum class Property {
+ kUnknown = 0,
+ kRead = 1,
+ kWrite = 2,
+ kIndicate = 3,
+ kLast,
+ };
+
+ // Returns the UUID of this characteristic.
+ virtual std::string GetUuid() = 0;
+
+ // Returns the UUID of the containing GATT service.
+ virtual std::string GetServiceUuid() = 0;
+};
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothGatt
+//
+// Representation of a client GATT connection to a remote GATT server.
+class ClientGattConnection {
+ public:
+ virtual ~ClientGattConnection() {}
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#getDevice()
+ //
+ // Retrieves the BLE peripheral that this connection is tied to.
+ virtual BlePeripheral& GetPeripheral() = 0;
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#discoverServices()
+ //
+ // Discovers all available services and characteristics on this connection.
+ // Returns whether or not discovery finished successfully.
+ //
+ // This function should block until discovery has finished.
+ virtual bool DiscoverServices() = 0;
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#getService(java.util.UUID)
+ // https://developer.android.com/reference/android/bluetooth/BluetoothGattService.html#getCharacteristic(java.util.UUID)
+ //
+ // Retrieves a GATT characteristic. On error, does not return a value.
+ //
+ // DiscoverServices() should be called before this method to fetch all
+ // available services and characteristics first.
+ //
+ // It is okay for duplicate services to exist, as long as the specified
+ // characteristic UUID is unique among all services of the same UUID.
+ virtual absl::optional<GattCharacteristic> GetCharacteristic(
+ absl::string_view service_uuid,
+ absl::string_view characteristic_uuid) = 0;
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#readCharacteristic(android.bluetooth.BluetoothGattCharacteristic)
+ // https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html#getValue()
+ //
+ // Reads a GATT characteristic. No value is returned upon error.
+ virtual absl::optional<ByteArray> ReadCharacteristic(
+ const GattCharacteristic& characteristic) = 0;
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html#setValue(byte[])
+ // https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#writeCharacteristic(android.bluetooth.BluetoothGattCharacteristic)
+ //
+ // Sends a remote characteristic write request to the server and returns
+ // whether or not it was successful.
+ virtual bool WriteCharacteristic(const GattCharacteristic& characteristic,
+ const ByteArray& value) = 0;
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#disconnect()
+ //
+ // Disconnects a GATT connection.
+ virtual void Disconnect() = 0;
+};
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothGattServer
+//
+// Representation of a server GATT connection to a remote GATT client.
+class ServerGattConnection {
+ public:
+ virtual ~ServerGattConnection() {}
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html#setValue(byte[])
+ // https://developer.android.com/reference/android/bluetooth/BluetoothGattServer.html#notifyCharacteristicChanged(android.bluetooth.BluetoothDevice,%20android.bluetooth.BluetoothGattCharacteristic,%20boolean)
+ //
+ // Sends a notification (via indication) to the client that a characteristic
+ // has changed with the given value. Returns whether or not it was successful.
+ //
+ // The value sent does not have to reflect the locally stored characteristic
+ // value. To update the local value, call GattServer::UpdateCharacteristic.
+ virtual bool SendCharacteristic(const GattCharacteristic& characteristic,
+ const ByteArray& value) = 0;
+};
+
+// Callback for asynchronous events on the client side of a GATT connection.
+class ClientGattConnectionLifeCycleCallback {
+ public:
+ virtual ~ClientGattConnectionLifeCycleCallback() {}
+
+ // Called when the client is disconnected from the GATT server.
+ virtual void OnDisconnected(ClientGattConnection* connection) = 0;
+};
+
+// Callback for asynchronous events on the server side of a GATT connection.
+class ServerGattConnectionLifeCycleCallback {
+ public:
+ virtual ~ServerGattConnectionLifeCycleCallback() {}
+
+ // Called when a remote peripheral connected to us and subscribed to one of
+ // our characteristics.
+ virtual void OnCharacteristicSubscription(
+ ServerGattConnection* connection,
+ const GattCharacteristic& characteristic) = 0;
+
+ // Called when a remote peripheral unsubscribed from one of our
+ // characteristics.
+ virtual void OnCharacteristicUnsubscription(
+ ServerGattConnection* connection,
+ const GattCharacteristic& characteristic) = 0;
+};
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothGattServer
+//
+// Representation of a BLE GATT server.
+class GattServer {
+ public:
+ virtual ~GattServer() {}
+
+ // Creates a characteristic and adds it to the GATT server under the given
+ // characteristic and service UUIDs. Returns no value upon error.
+ //
+ // Characteristics of the same service UUID should be put under one
+ // service rather than many services with the same UUID.
+ //
+ // If the INDICATE property is included, the characteristic should include the
+ // official Bluetooth Client Characteristic Configuration descriptor with UUID
+ // 0x2902 and a WRITE permission. This allows remote clients to write to this
+ // descriptor and subscribe for characteristic changes. For more information
+ // about this descriptor, please go to:
+ // https://www.bluetooth.com/specifications/Gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.Gatt.client_characteristic_configuration.xml
+ virtual absl::optional<GattCharacteristic> CreateCharacteristic(
+ absl::string_view service_uuid, absl::string_view characteristic_uuid,
+ const std::set<GattCharacteristic::Permission>& permissions,
+ const std::set<GattCharacteristic::Property>& properties) = 0;
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html#setValue(byte[])
+ //
+ // Locally updates the value of a characteristic and returns whether or not it
+ // was successful.
+ // Takes ownership of (and is responsible for destroying) the passed-in
+ // 'value'.
+ virtual bool UpdateCharacteristic(const GattCharacteristic& characteristic,
+ const ByteArray& value) = 0;
+
+ // Stops a GATT server.
+ virtual void Stop() = 0;
+};
+
+// A BLE socket representation.
+class BleSocket {
+ public:
+ virtual ~BleSocket() {}
+
+ // Returns the remote BLE peripheral tied to this socket.
+ virtual BlePeripheral& GetRemotePeripheral() = 0;
+
+ // Writes a message on the socket and blocks until finished. Returns
+ // Exception::kIo upon error, and Exception::kSuccess otherwise.
+ virtual Exception Write(const ByteArray& message) = 0;
+
+ // Closes the socket and blocks until finished. Returns Exception::kIo upon
+ // error, and Exception::kSuccess otherwise.
+ virtual Exception Close() = 0;
+};
+
+// Callback for asynchronous events on a BleSocket object.
+class BleSocketLifeCycleCallback {
+ public:
+ virtual ~BleSocketLifeCycleCallback() {}
+
+ // Called when a message arrives on a socket.
+ virtual void OnMessageReceived(BleSocket* socket,
+ const ByteArray& message) = 0;
+
+ // Called when a socket gets disconnected.
+ virtual void OnDisconnected(BleSocket* socket) = 0;
+};
+
+// Callback for asynchronous events on the server side of a BleSocket object.
+class ServerBleSocketLifeCycleCallback : public BleSocketLifeCycleCallback {
+ public:
+ ~ServerBleSocketLifeCycleCallback() override {}
+
+ // Called when a new incoming socket has been established.
+ virtual void OnSocketEstablished(BleSocket* socket) = 0;
+};
+
+// The main BLE medium used inside of Nearby. This serves as the entry point for
+// all BLE and GATT related operations.
+class BleMedium {
+ public:
+ using Mtu = uint32_t;
+
+ virtual ~BleMedium() {}
+
+ // Coarse representation of power settings throughout all BLE operations.
+ enum class PowerMode {
+ kUnknown = 0,
+ kLow = 1,
+ kHigh = 2,
+ kLast,
+ };
+
+ // https://developer.android.com/reference/android/bluetooth/le/BluetoothLeAdvertiser.html#startAdvertising(android.bluetooth.le.AdvertiseSettings,%20android.bluetooth.le.AdvertiseData,%20android.bluetooth.le.AdvertiseData,%20android.bluetooth.le.AdvertiseCallback)
+ //
+ // Starts BLE advertising and returns whether or not it was successful.
+ //
+ // Power mode should be interpreted in the following way:
+ // LOW:
+ // - Advertising interval = ~1000ms
+ // - TX power = low
+ // HIGH:
+ // - Advertising interval = ~100ms
+ // - TX power = high
+ virtual bool StartAdvertising(const BleAdvertisementData& advertisement_data,
+ const BleAdvertisementData& scan_response,
+ PowerMode power_mode) = 0;
+
+ // https://developer.android.com/reference/android/bluetooth/le/BluetoothLeAdvertiser.html#stopAdvertising(android.bluetooth.le.AdvertiseCallback)
+ //
+ // Stops advertising.
+ virtual void StopAdvertising() = 0;
+
+ // https://developer.android.com/reference/android/bluetooth/le/ScanCallback
+ //
+ // Callback for BLE scan results.
+ class ScanCallback {
+ public:
+ virtual ~ScanCallback() {}
+
+ // https://developer.android.com/reference/android/bluetooth/le/ScanCallback.html#onScanResult(int,%20android.bluetooth.le.ScanResult)
+ //
+ // Called when a BLE advertisement is discovered.
+ //
+ // The passed in advertisement_data is the merged combination of both
+ // advertisement data and scan response.
+ //
+ // Every discovery of an advertisement should be reported, even if the
+ // advertisement was discovered before.
+ //
+ // Ownership of the BleAdvertisementData transfers to the caller at this
+ // point.
+ virtual void OnAdvertisementFound(
+ BlePeripheral* peripheral,
+ const BleAdvertisementData& advertisement_data) = 0;
+ };
+
+ // https://developer.android.com/reference/android/bluetooth/le/BluetoothLeScanner.html#startScan(java.util.List%3Candroid.bluetooth.le.ScanFilter%3E,%20android.bluetooth.le.ScanSettings,%20android.bluetooth.le.ScanCallback)
+ //
+ // Starts scanning and returns whether or not it was successful.
+ //
+ // Power mode should be interpreted in the following way:
+ // LOW:
+ // - Scan window = ~512ms
+ // - Scan interval = ~5120ms
+ // HIGH:
+ // - Scan window = ~4096ms
+ // - Scan interval = ~4096ms
+ virtual bool StartScanning(const std::set<std::string>& service_uuids,
+ PowerMode power_mode,
+ const ScanCallback& scan_callback) = 0;
+
+ // https://developer.android.com/reference/android/bluetooth/le/BluetoothLeScanner.html#stopScan(android.bluetooth.le.ScanCallback)
+ //
+ // Stops scanning.
+ virtual void StopScanning() = 0;
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothManager#openGattServer(android.content.Context,%20android.bluetooth.BluetoothGattServerCallback)
+ //
+ // Starts a GATT server. Returns a nullptr upon error.
+ virtual std::unique_ptr<GattServer> StartGattServer(
+ const ServerGattConnectionLifeCycleCallback& callback) = 0;
+
+ // Starts listening for incoming BLE sockets and returns false upon error.
+ virtual bool StartListeningForIncomingBleSockets(
+ const ServerBleSocketLifeCycleCallback& callback) = 0;
+
+ // Stops listening for incoming BLE sockets.
+ virtual void StopListeningForIncomingBleSockets() = 0;
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#connectGatt(android.content.Context,%20boolean,%20android.bluetooth.BluetoothGattCallback)
+ // https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#requestConnectionPriority(int)
+ // https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#requestMtu(int)
+ //
+ // Connects to a GATT server and negotiates the specified connection
+ // parameters. Returns nullptr upon error.
+ //
+ // Both connection interval and MTU can be negotiated on a best-effort basis.
+ //
+ // Power mode should be interpreted in the following way:
+ // LOW:
+ // - Connection interval = ~11.25ms - 15ms
+ // HIGH:
+ // - Connection interval = ~100ms - 125ms
+ virtual std::unique_ptr<ClientGattConnection> ConnectToGattServer(
+ BlePeripheral* peripheral, Mtu mtu, PowerMode power_mode,
+ const ClientGattConnectionLifeCycleCallback& callback) = 0;
+
+ // Establishes a BLE socket to the specified remote peripheral. Returns
+ // nullptr on error.
+ virtual std::unique_ptr<BleSocket> EstablishBleSocket(
+ BlePeripheral* peripheral,
+ const BleSocketLifeCycleCallback& callback) = 0;
+};
+
+} // namespace ble_v2
+} // namespace api
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_API_BLE_V2_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/bluetooth_adapter.h b/chromium/third_party/nearby/src/internal/platform/implementation/bluetooth_adapter.h
index 4ca4022b0d8..4ca4022b0d8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/api/bluetooth_adapter.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/bluetooth_adapter.h
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/bluetooth_classic.h b/chromium/third_party/nearby/src/internal/platform/implementation/bluetooth_classic.h
new file mode 100644
index 00000000000..a1685c750af
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/bluetooth_classic.h
@@ -0,0 +1,162 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_API_BLUETOOTH_CLASSIC_H_
+#define PLATFORM_API_BLUETOOTH_CLASSIC_H_
+
+#include <memory>
+#include <string>
+
+#include "internal/platform/byte_array.h"
+#include "internal/platform/cancellation_flag.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/input_stream.h"
+#include "internal/platform/listeners.h"
+#include "internal/platform/output_stream.h"
+
+namespace location {
+namespace nearby {
+namespace api {
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html.
+class BluetoothDevice {
+ public:
+ virtual ~BluetoothDevice() = default;
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#getName()
+ virtual std::string GetName() const = 0;
+
+ // Returns BT MAC address assigned to this device.
+ virtual std::string GetMacAddress() const = 0;
+};
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html.
+class BluetoothSocket {
+ public:
+ virtual ~BluetoothSocket() = default;
+
+ // NOTE:
+ // It is an undefined behavior if GetInputStream() or GetOutputStream() is
+ // called for a not-connected BluetoothSocket, i.e. any object that is not
+ // returned by BluetoothClassicMedium::ConnectToService() for client side or
+ // BluetoothServerSocket::Accept() for server side of connection.
+
+ // Returns the InputStream of this connected BluetoothSocket.
+ virtual InputStream& GetInputStream() = 0;
+
+ // Returns the OutputStream of this connected BluetoothSocket.
+ virtual OutputStream& GetOutputStream() = 0;
+
+ // Closes both input and output streams, marks Socket as closed.
+ // After this call object should be treated as not connected.
+ // Returns Exception::kIo on error, Exception::kSuccess otherwise.
+ virtual Exception Close() = 0;
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#getRemoteDevice()
+ // Returns valid BluetoothDevice pointer if there is a connection, and
+ // nullptr otherwise.
+ virtual BluetoothDevice* GetRemoteDevice() = 0;
+};
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html.
+class BluetoothServerSocket {
+ public:
+ virtual ~BluetoothServerSocket() = default;
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html#accept()
+ //
+ // Blocks until either:
+ // - at least one incoming connection request is available, or
+ // - ServerSocket is closed.
+ // On success, returns connected socket, ready to exchange data.
+ // Returns nullptr on error.
+ // Once error is reported, it is permanent, and ServerSocket has to be closed.
+ virtual std::unique_ptr<BluetoothSocket> Accept() = 0;
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html#close()
+ //
+ // Returns Exception::kIo on error, Exception::kSuccess otherwise.
+ virtual Exception Close() = 0;
+};
+
+// Container of operations that can be performed over the Bluetooth Classic
+// medium.
+class BluetoothClassicMedium {
+ public:
+ virtual ~BluetoothClassicMedium() = default;
+
+ struct DiscoveryCallback {
+ // BluetoothDevice is a proxy object created as a result of BT discovery.
+ // Its lifetime spans between calls to device_discovered_cb and
+ // device_lost_cb.
+ // It is safe to use BluetoothDevice in device_discovered_cb() callback
+ // and at any time afterwards, until device_lost_cb() is called.
+ // It is not safe to use BluetoothDevice after returning from
+ // device_lost_cb() callback.
+ std::function<void(BluetoothDevice& device)> device_discovered_cb =
+ DefaultCallback<BluetoothDevice&>();
+ std::function<void(BluetoothDevice& device)> device_name_changed_cb =
+ DefaultCallback<BluetoothDevice&>();
+ std::function<void(BluetoothDevice& device)> device_lost_cb =
+ DefaultCallback<BluetoothDevice&>();
+ };
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#startDiscovery()
+ //
+ // Returns true once the process of discovery has been initiated.
+ virtual bool StartDiscovery(DiscoveryCallback discovery_callback) = 0;
+ // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#cancelDiscovery()
+ //
+ // Returns true once discovery is well and truly stopped; after this returns,
+ // there must be no more invocations of the DiscoveryCallback passed in to
+ // StartDiscovery().
+ virtual bool StopDiscovery() = 0;
+
+ // A combination of
+ // https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#createInsecureRfcommSocketToServiceRecord
+ // followed by
+ // https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#connect().
+ //
+ // service_uuid is the canonical textual representation
+ // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format) of a
+ // type 3 name-based
+ // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based))
+ // UUID.
+ //
+ // On success, returns a new BluetoothSocket.
+ // On error, returns nullptr.
+ virtual std::unique_ptr<BluetoothSocket> ConnectToService(
+ BluetoothDevice& remote_device, const std::string& service_uuid,
+ CancellationFlag* cancellation_flag) = 0;
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#listenUsingInsecureRfcommWithServiceRecord
+ //
+ // service_uuid is the canonical textual representation
+ // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format) of a
+ // type 3 name-based
+ // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based))
+ // UUID.
+ //
+ // Returns nullptr error.
+ virtual std::unique_ptr<BluetoothServerSocket> ListenForService(
+ const std::string& service_name, const std::string& service_uuid) = 0;
+
+ virtual BluetoothDevice* GetRemoteDevice(const std::string& mac_address) = 0;
+};
+
+} // namespace api
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_API_BLUETOOTH_CLASSIC_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/cancelable.h b/chromium/third_party/nearby/src/internal/platform/implementation/cancelable.h
index c90faf0cbe2..c90faf0cbe2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/api/cancelable.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/cancelable.h
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/condition_variable.h b/chromium/third_party/nearby/src/internal/platform/implementation/condition_variable.h
new file mode 100644
index 00000000000..a607b61ba02
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/condition_variable.h
@@ -0,0 +1,51 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_API_CONDITION_VARIABLE_H_
+#define PLATFORM_API_CONDITION_VARIABLE_H_
+
+#include "absl/time/clock.h"
+#include "internal/platform/exception.h"
+
+namespace location {
+namespace nearby {
+namespace api {
+
+// The ConditionVariable class is a synchronization primitive that can be used
+// to block a thread, or multiple threads at the same time, until another thread
+// both modifies a shared variable (the condition), and notifies the
+// ConditionVariable.
+class ConditionVariable {
+ public:
+ virtual ~ConditionVariable() {}
+
+ // Notifies all the waiters that condition state has changed.
+ virtual void Notify() = 0;
+
+ // Waits indefinitely for Notify to be called.
+ // May return prematurely in case of interrupt, if supported by platform.
+ // Returns kSuccess, or kInterrupted on interrupt.
+ virtual Exception Wait() = 0;
+
+ // Waits while timeout has not expired for Notify to be called.
+ // May return prematurely in case of interrupt, if supported by platform.
+ // Returns kSuccess, or kInterrupted on interrupt.
+ virtual Exception Wait(absl::Duration timeout) = 0;
+};
+
+} // namespace api
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_API_CONDITION_VARIABLE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/count_down_latch.h b/chromium/third_party/nearby/src/internal/platform/implementation/count_down_latch.h
new file mode 100644
index 00000000000..1ac4f0107e6
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/count_down_latch.h
@@ -0,0 +1,45 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_API_COUNT_DOWN_LATCH_H_
+#define PLATFORM_API_COUNT_DOWN_LATCH_H_
+
+#include <cstdint>
+
+#include "absl/time/time.h"
+#include "internal/platform/exception.h"
+
+namespace location {
+namespace nearby {
+namespace api {
+
+// A synchronization aid that allows one or more threads to wait until a set of
+// operations being performed in other threads completes.
+//
+// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html
+class CountDownLatch {
+ public:
+ virtual ~CountDownLatch() = default;
+
+ virtual Exception Await() = 0; // throws Exception::kInterrupted
+ virtual ExceptionOr<bool> Await(
+ absl::Duration timeout) = 0; // throws Exception::kInterrupted
+ virtual void CountDown() = 0;
+};
+
+} // namespace api
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_API_COUNT_DOWN_LATCH_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/crypto.h b/chromium/third_party/nearby/src/internal/platform/implementation/crypto.h
new file mode 100644
index 00000000000..e0bc4aa99db
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/crypto.h
@@ -0,0 +1,38 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_API_CRYPTO_H_
+#define PLATFORM_API_CRYPTO_H_
+
+#include "absl/strings/string_view.h"
+#include "internal/platform/byte_array.h"
+
+namespace location {
+namespace nearby {
+
+// A provider of standard hashing algorithms.
+class Crypto {
+ public:
+ // Initialize global crypto state.
+ static void Init();
+ // Return MD5 hash of input.
+ static ByteArray Md5(absl::string_view input);
+ // Return SHA256 hash of input.
+ static ByteArray Sha256(absl::string_view input);
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_API_CRYPTO_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/executor.h b/chromium/third_party/nearby/src/internal/platform/implementation/executor.h
new file mode 100644
index 00000000000..c41bc313f75
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/executor.h
@@ -0,0 +1,44 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_API_EXECUTOR_H_
+#define PLATFORM_API_EXECUTOR_H_
+
+#include "internal/platform/runnable.h"
+
+namespace location {
+namespace nearby {
+namespace api {
+
+int GetCurrentTid();
+
+// This abstract class is the superclass of all classes representing an
+// Executor.
+class Executor {
+ public:
+ // Before returning from destructor, executor must wait for all pending
+ // jobs to finish.
+ virtual ~Executor() = default;
+ // https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-
+ virtual void Execute(Runnable&& runnable) = 0;
+
+ // https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#shutdown--
+ virtual void Shutdown() = 0;
+};
+
+} // namespace api
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_API_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/future.h b/chromium/third_party/nearby/src/internal/platform/implementation/future.h
new file mode 100644
index 00000000000..0fbc99c7cc7
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/future.h
@@ -0,0 +1,46 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_API_FUTURE_H_
+#define PLATFORM_API_FUTURE_H_
+
+#include "absl/time/clock.h"
+#include "internal/platform/exception.h"
+
+namespace location {
+namespace nearby {
+namespace api {
+
+// A Future represents the result of an asynchronous computation.
+//
+// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html
+template <typename T>
+class Future {
+ public:
+ virtual ~Future() = default;
+
+ // throws Exception::kInterrupted, Exception::kExecution
+ virtual ExceptionOr<T> Get() = 0;
+
+ // throws Exception::kInterrupted, Exception::kExecution
+ // throws Exception::kTimeout if timeout is exceeded while waiting for
+ // result.
+ virtual ExceptionOr<T> Get(absl::Duration timeout) = 0;
+};
+
+} // namespace api
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_API_FUTURE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/g3/BUILD b/chromium/third_party/nearby/src/internal/platform/implementation/g3/BUILD
new file mode 100644
index 00000000000..1ddd110b1be
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/g3/BUILD
@@ -0,0 +1,128 @@
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+licenses(["notice"])
+
+cc_library(
+ name = "types",
+ testonly = True,
+ srcs = [
+ "log_message.cc",
+ "scheduled_executor.cc",
+ "system_clock.cc",
+ ],
+ hdrs = [
+ "atomic_boolean.h",
+ "atomic_reference.h",
+ "condition_variable.h",
+ "log_message.h",
+ "multi_thread_executor.h",
+ "mutex.h",
+ "pipe.h",
+ "scheduled_executor.h",
+ "single_thread_executor.h",
+ ],
+ defines = ["NO_WEBRTC"],
+ visibility = ["//visibility:private"],
+ deps = [
+ "//internal/platform:base",
+ "//internal/platform:util",
+ "//internal/platform/implementation:types",
+ "//internal/platform/implementation/shared:count_down_latch",
+ "//internal/platform/implementation/shared:posix_mutex",
+ "@com_google_absl//absl/synchronization",
+ "@com_google_absl//absl/time",
+ "@com_google_glog//:glog",
+ "@com_google_nisaba//nisaba/port:thread_pool",
+ ],
+)
+
+cc_library(
+ name = "comm",
+ testonly = True,
+ srcs = [
+ "ble.cc",
+ "bluetooth_adapter.cc",
+ "bluetooth_classic.cc",
+ "wifi_lan.cc",
+ ],
+ hdrs = [
+ "ble.h",
+ "bluetooth_adapter.h",
+ "bluetooth_classic.h",
+ "wifi_lan.h",
+ ],
+ defines = ["NO_WEBRTC"],
+ visibility = ["//visibility:private"],
+ deps = [
+ ":types",
+ "//internal/platform:base",
+ "//internal/platform:cancellation_flag",
+ "//internal/platform:logging",
+ "//internal/platform:test_util",
+ "//internal/platform/implementation:comm",
+ "//internal/platform/implementation/shared:count_down_latch",
+ "@com_google_absl//absl/base:core_headers",
+ "@com_google_absl//absl/container:flat_hash_map",
+ "@com_google_absl//absl/container:flat_hash_set",
+ "@com_google_absl//absl/strings",
+ "@com_google_absl//absl/strings:str_format",
+ "@com_google_absl//absl/synchronization",
+ ],
+)
+
+cc_library(
+ name = "crypto",
+ testonly = True,
+ srcs = [
+ "crypto.cc",
+ ],
+ defines = ["NO_WEBRTC"],
+ visibility = ["//visibility:private"],
+ deps = [
+ "//internal/platform:base",
+ "//internal/platform/implementation:types",
+ "@boringssl//:crypto",
+ "@com_google_absl//absl/strings",
+ ],
+)
+
+cc_library(
+ name = "g3",
+ testonly = True,
+ srcs = [
+ "platform.cc",
+ ],
+ defines = ["NO_WEBRTC"],
+ visibility = [
+ "//connections:__subpackages__",
+ "//internal/analytics:__subpackages__",
+ "//internal/platform:__subpackages__",
+ "//internal/proto/analytics:__subpackages__",
+ ],
+ deps = [
+ ":comm",
+ ":crypto", # build_cleaner: keep
+ ":types",
+ "//internal/platform:test_util",
+ "//internal/platform/implementation:comm",
+ "//internal/platform/implementation:platform",
+ "//internal/platform/implementation:types",
+ "//internal/platform/implementation/shared:count_down_latch",
+ "//internal/platform/implementation/shared:file",
+ "@com_google_absl//absl/base:core_headers",
+ "@com_google_absl//absl/memory",
+ "@com_google_absl//absl/strings",
+ "@com_google_absl//absl/time",
+ ],
+)
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/g3/atomic_boolean.h b/chromium/third_party/nearby/src/internal/platform/implementation/g3/atomic_boolean.h
new file mode 100644
index 00000000000..14b88104515
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/g3/atomic_boolean.h
@@ -0,0 +1,44 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_G3_ATOMIC_BOOLEAN_H_
+#define PLATFORM_IMPL_G3_ATOMIC_BOOLEAN_H_
+
+#include <atomic>
+
+#include "internal/platform/implementation/atomic_boolean.h"
+
+namespace location {
+namespace nearby {
+namespace g3 {
+
+// See documentation in
+// cpp/platform/api/atomic_boolean.h
+class AtomicBoolean : public api::AtomicBoolean {
+ public:
+ explicit AtomicBoolean(bool initial_value) : value_(initial_value) {}
+ ~AtomicBoolean() override = default;
+
+ bool Get() const override { return value_.load(); }
+ bool Set(bool value) override { return value_.exchange(value); }
+
+ private:
+ std::atomic_bool value_;
+};
+
+} // namespace g3
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_G3_ATOMIC_BOOLEAN_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/g3/atomic_reference.h b/chromium/third_party/nearby/src/internal/platform/implementation/g3/atomic_reference.h
new file mode 100644
index 00000000000..85d89bb943d
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/g3/atomic_reference.h
@@ -0,0 +1,43 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_G3_ATOMIC_REFERENCE_H_
+#define PLATFORM_IMPL_G3_ATOMIC_REFERENCE_H_
+
+#include <atomic>
+#include <cstdint>
+
+#include "internal/platform/implementation/atomic_reference.h"
+
+namespace location {
+namespace nearby {
+namespace g3 {
+
+class AtomicUint32 : public api::AtomicUint32 {
+ public:
+ explicit AtomicUint32(std::int32_t value) : value_(value) {}
+ ~AtomicUint32() override = default;
+
+ std::uint32_t Get() const override { return value_; }
+ void Set(std::uint32_t value) override { value_ = value; }
+
+ private:
+ std::atomic<std::uint32_t> value_;
+};
+
+} // namespace g3
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_G3_ATOMIC_REFERENCE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/g3/ble.cc b/chromium/third_party/nearby/src/internal/platform/implementation/g3/ble.cc
new file mode 100644
index 00000000000..8de0d3903b5
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/g3/ble.cc
@@ -0,0 +1,378 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/g3/ble.h"
+
+#include <iostream>
+#include <memory>
+#include <string>
+
+#include "absl/synchronization/mutex.h"
+#include "internal/platform/implementation/ble.h"
+#include "internal/platform/cancellation_flag_listener.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/medium_environment.h"
+#include "internal/platform/implementation/shared/count_down_latch.h"
+
+namespace location {
+namespace nearby {
+namespace g3 {
+
+BleSocket::~BleSocket() {
+ absl::MutexLock lock(&mutex_);
+ DoClose();
+}
+
+void BleSocket::Connect(BleSocket& other) {
+ absl::MutexLock lock(&mutex_);
+ remote_socket_ = &other;
+ input_ = other.output_;
+}
+
+InputStream& BleSocket::GetInputStream() {
+ auto* remote_socket = GetRemoteSocket();
+ CHECK(remote_socket != nullptr);
+ return remote_socket->GetLocalInputStream();
+}
+
+OutputStream& BleSocket::GetOutputStream() { return GetLocalOutputStream(); }
+
+BleSocket* BleSocket::GetRemoteSocket() {
+ absl::MutexLock lock(&mutex_);
+ return remote_socket_;
+}
+
+bool BleSocket::IsConnected() const {
+ absl::MutexLock lock(&mutex_);
+ return IsConnectedLocked();
+}
+
+bool BleSocket::IsClosed() const {
+ absl::MutexLock lock(&mutex_);
+ return closed_;
+}
+
+Exception BleSocket::Close() {
+ absl::MutexLock lock(&mutex_);
+ DoClose();
+ return {Exception::kSuccess};
+}
+
+BlePeripheral* BleSocket::GetRemotePeripheral() {
+ absl::MutexLock lock(&mutex_);
+ return peripheral_;
+}
+
+void BleSocket::DoClose() {
+ if (!closed_) {
+ remote_socket_ = nullptr;
+ output_->GetOutputStream().Close();
+ output_->GetInputStream().Close();
+ if (IsConnectedLocked()) {
+ input_->GetOutputStream().Close();
+ input_->GetInputStream().Close();
+ }
+ closed_ = true;
+ }
+}
+
+bool BleSocket::IsConnectedLocked() const { return input_ != nullptr; }
+
+InputStream& BleSocket::GetLocalInputStream() {
+ absl::MutexLock lock(&mutex_);
+ return output_->GetInputStream();
+}
+
+OutputStream& BleSocket::GetLocalOutputStream() {
+ absl::MutexLock lock(&mutex_);
+ return output_->GetOutputStream();
+}
+
+std::unique_ptr<api::BleSocket> BleServerSocket::Accept(
+ BlePeripheral* peripheral) {
+ absl::MutexLock lock(&mutex_);
+ if (closed_) return {};
+ while (pending_sockets_.empty()) {
+ cond_.Wait(&mutex_);
+ if (closed_) break;
+ }
+ if (closed_) return {};
+ auto* remote_socket =
+ pending_sockets_.extract(pending_sockets_.begin()).value();
+ CHECK(remote_socket);
+ auto local_socket = std::make_unique<BleSocket>(peripheral);
+ local_socket->Connect(*remote_socket);
+ remote_socket->Connect(*local_socket);
+ cond_.SignalAll();
+ return local_socket;
+}
+
+bool BleServerSocket::Connect(BleSocket& socket) {
+ absl::MutexLock lock(&mutex_);
+ if (closed_) return false;
+ if (socket.IsConnected()) {
+ NEARBY_LOG(ERROR,
+ "Failed to connect to Ble server socket: already connected");
+ return true; // already connected.
+ }
+ // add client socket to the pending list
+ pending_sockets_.emplace(&socket);
+ cond_.SignalAll();
+ while (!socket.IsConnected()) {
+ cond_.Wait(&mutex_);
+ if (closed_) return false;
+ }
+ return true;
+}
+
+void BleServerSocket::SetCloseNotifier(std::function<void()> notifier) {
+ absl::MutexLock lock(&mutex_);
+ close_notifier_ = std::move(notifier);
+}
+
+BleServerSocket::~BleServerSocket() {
+ absl::MutexLock lock(&mutex_);
+ DoClose();
+}
+
+Exception BleServerSocket::Close() {
+ absl::MutexLock lock(&mutex_);
+ return DoClose();
+}
+
+Exception BleServerSocket::DoClose() {
+ bool should_notify = !closed_;
+ closed_ = true;
+ if (should_notify) {
+ cond_.SignalAll();
+ if (close_notifier_) {
+ auto notifier = std::move(close_notifier_);
+ mutex_.Unlock();
+ // Notifier may contain calls to public API, and may cause deadlock, if
+ // mutex_ is held during the call.
+ notifier();
+ mutex_.Lock();
+ }
+ }
+ return {Exception::kSuccess};
+}
+
+BleMedium::BleMedium(api::BluetoothAdapter& adapter)
+ : adapter_(static_cast<BluetoothAdapter*>(&adapter)) {
+ adapter_->SetBleMedium(this);
+ auto& env = MediumEnvironment::Instance();
+ env.RegisterBleMedium(*this);
+}
+
+BleMedium::~BleMedium() {
+ adapter_->SetBleMedium(nullptr);
+ auto& env = MediumEnvironment::Instance();
+ env.UnregisterBleMedium(*this);
+
+ StopAdvertising(advertising_info_.service_id);
+ StopScanning(scanning_info_.service_id);
+
+ accept_loops_runner_.Shutdown();
+ NEARBY_LOG(INFO, "BleMedium dtor advertising_accept_thread_running_ = %d",
+ acceptance_thread_running_.load());
+ // If acceptance thread is still running, wait to finish.
+ if (acceptance_thread_running_) {
+ while (acceptance_thread_running_) {
+ shared::CountDownLatch latch(1);
+ close_accept_loops_runner_.Execute([&latch]() { latch.CountDown(); });
+ latch.Await();
+ }
+ }
+}
+
+bool BleMedium::StartAdvertising(
+ const std::string& service_id, const ByteArray& advertisement_bytes,
+ const std::string& fast_advertisement_service_uuid) {
+ NEARBY_LOGS(INFO) << "G3 Ble StartAdvertising: service_id=" << service_id
+ << ", advertisement bytes=" << advertisement_bytes.data()
+ << "(" << advertisement_bytes.size() << "),"
+ << " fast advertisement service uuid="
+ << fast_advertisement_service_uuid;
+ auto& env = MediumEnvironment::Instance();
+ auto& peripheral = adapter_->GetPeripheral();
+ peripheral.SetAdvertisementBytes(service_id, advertisement_bytes);
+ bool fast_advertisement = !fast_advertisement_service_uuid.empty();
+ env.UpdateBleMediumForAdvertising(*this, peripheral, service_id,
+ fast_advertisement, true);
+
+ absl::MutexLock lock(&mutex_);
+ if (server_socket_ != nullptr) server_socket_.release();
+ server_socket_ = std::make_unique<BleServerSocket>();
+
+ acceptance_thread_running_.exchange(true);
+ accept_loops_runner_.Execute([&env, this, service_id]() mutable {
+ if (!accept_loops_runner_.InShutdown()) {
+ while (true) {
+ auto client_socket =
+ server_socket_->Accept(&(this->adapter_->GetPeripheral()));
+ if (client_socket == nullptr) break;
+ env.CallBleAcceptedConnectionCallback(*this, *(client_socket.release()),
+ service_id);
+ }
+ }
+ acceptance_thread_running_.exchange(false);
+ });
+ advertising_info_.service_id = service_id;
+ return true;
+}
+
+bool BleMedium::StopAdvertising(const std::string& service_id) {
+ NEARBY_LOGS(INFO) << "G3 Ble StopAdvertising: service_id=" << service_id;
+ {
+ absl::MutexLock lock(&mutex_);
+ if (advertising_info_.Empty()) {
+ NEARBY_LOGS(INFO) << "G3 Ble StopAdvertising: Can't stop advertising "
+ "because we never started advertising.";
+ return false;
+ }
+ advertising_info_.Clear();
+ }
+
+ auto& env = MediumEnvironment::Instance();
+ env.UpdateBleMediumForAdvertising(*this, adapter_->GetPeripheral(),
+ service_id, /*fast_advertisement=*/false,
+ /*enabled=*/false);
+ accept_loops_runner_.Shutdown();
+ if (server_socket_ == nullptr) {
+ NEARBY_LOGS(ERROR) << "G3 Ble StopAdvertising: Failed to find Ble Server "
+ "socket: service_id="
+ << service_id;
+ // Fall through for server socket not found.
+ return true;
+ }
+
+ if (!server_socket_->Close().Ok()) {
+ NEARBY_LOGS(INFO)
+ << "G3 Ble StopAdvertising: Failed to close Ble server socket for "
+ << service_id;
+ return false;
+ }
+ return true;
+}
+
+bool BleMedium::StartScanning(
+ const std::string& service_id,
+ const std::string& fast_advertisement_service_uuid,
+ DiscoveredPeripheralCallback callback) {
+ NEARBY_LOGS(INFO) << "G3 Ble StartScanning: service_id=" << service_id;
+ auto& env = MediumEnvironment::Instance();
+ env.UpdateBleMediumForScanning(*this, service_id,
+ fast_advertisement_service_uuid,
+ std::move(callback), true);
+ {
+ absl::MutexLock lock(&mutex_);
+ scanning_info_.service_id = service_id;
+ }
+ return true;
+}
+
+bool BleMedium::StopScanning(const std::string& service_id) {
+ NEARBY_LOGS(INFO) << "G3 Ble StopScanning: service_id=" << service_id;
+ {
+ absl::MutexLock lock(&mutex_);
+ if (scanning_info_.Empty()) {
+ NEARBY_LOGS(INFO) << "G3 Ble StopDiscovery: Can't stop scanning because "
+ "we never started scanning.";
+ return false;
+ }
+ scanning_info_.Clear();
+ }
+
+ auto& env = MediumEnvironment::Instance();
+ env.UpdateBleMediumForScanning(*this, service_id, {}, {}, false);
+ return true;
+}
+
+bool BleMedium::StartAcceptingConnections(const std::string& service_id,
+ AcceptedConnectionCallback callback) {
+ NEARBY_LOGS(INFO) << "G3 Ble StartAcceptingConnections: service_id="
+ << service_id;
+ auto& env = MediumEnvironment::Instance();
+ env.UpdateBleMediumForAcceptedConnection(*this, service_id, callback);
+ return true;
+}
+
+bool BleMedium::StopAcceptingConnections(const std::string& service_id) {
+ NEARBY_LOGS(INFO) << "G3 Ble StopAcceptingConnections: service_id="
+ << service_id;
+ auto& env = MediumEnvironment::Instance();
+ env.UpdateBleMediumForAcceptedConnection(*this, service_id, {});
+ return true;
+}
+
+std::unique_ptr<api::BleSocket> BleMedium::Connect(
+ api::BlePeripheral& remote_peripheral, const std::string& service_id,
+ CancellationFlag* cancellation_flag) {
+ NEARBY_LOG(INFO,
+ "G3 Ble Connect [self]: medium=%p, adapter=%p, peripheral=%p, "
+ "service_id=%s",
+ this, &GetAdapter(), &GetAdapter().GetPeripheral(),
+ service_id.c_str());
+ // First, find an instance of remote medium, that exposed this peripheral.
+ auto& adapter = static_cast<BlePeripheral&>(remote_peripheral).GetAdapter();
+ auto* medium = static_cast<BleMedium*>(adapter.GetBleMedium());
+
+ if (!medium) return {}; // Can't find medium. Bail out.
+
+ BleServerSocket* remote_server_socket = nullptr;
+ NEARBY_LOG(INFO,
+ "G3 Ble Connect [peer]: medium=%p, adapter=%p, peripheral=%p, "
+ "service_id=%s",
+ medium, &adapter, &remote_peripheral, service_id.c_str());
+ // Then, find our server socket context in this medium.
+ {
+ absl::MutexLock medium_lock(&medium->mutex_);
+ remote_server_socket = medium->server_socket_.get();
+ if (remote_server_socket == nullptr) {
+ NEARBY_LOGS(ERROR)
+ << "G3 Ble Connect: Failed to find Ble Server socket: service_id="
+ << service_id;
+ return {};
+ }
+ }
+
+ if (cancellation_flag->Cancelled()) {
+ NEARBY_LOGS(ERROR) << "G3 BLE Connect: Has been cancelled: "
+ "service_id="
+ << service_id;
+ return {};
+ }
+
+ CancellationFlagListener listener(cancellation_flag, [this]() {
+ NEARBY_LOGS(INFO) << "G3 BLE Cancel Connect.";
+ if (server_socket_ != nullptr) server_socket_->Close();
+ });
+
+ BlePeripheral peripheral = static_cast<BlePeripheral&>(remote_peripheral);
+ auto socket = std::make_unique<BleSocket>(&peripheral);
+ // Finally, Request to connect to this socket.
+ if (!remote_server_socket->Connect(*socket)) {
+ NEARBY_LOGS(ERROR) << "G3 Ble Connect: Failed to connect to existing Ble "
+ "Server socket: service_id="
+ << service_id;
+ return {};
+ }
+
+ NEARBY_LOG(INFO, "G3 Ble Connect: connected: socket=%p", socket.get());
+ return socket;
+}
+
+} // namespace g3
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/g3/ble.h b/chromium/third_party/nearby/src/internal/platform/implementation/g3/ble.h
new file mode 100644
index 00000000000..412635e9ca3
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/g3/ble.h
@@ -0,0 +1,228 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_G3_BLE_H_
+#define PLATFORM_IMPL_G3_BLE_H_
+
+#include <memory>
+#include <string>
+
+#include "absl/container/flat_hash_map.h"
+#include "absl/container/flat_hash_set.h"
+#include "absl/strings/escaping.h"
+#include "absl/synchronization/mutex.h"
+#include "internal/platform/implementation/ble.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/input_stream.h"
+#include "internal/platform/output_stream.h"
+#include "internal/platform/implementation/g3/bluetooth_adapter.h"
+#include "internal/platform/implementation/g3/bluetooth_classic.h"
+#include "internal/platform/implementation/g3/multi_thread_executor.h"
+#include "internal/platform/implementation/g3/pipe.h"
+
+namespace location {
+namespace nearby {
+namespace g3 {
+
+class BleMedium;
+
+class BleSocket : public api::BleSocket {
+ public:
+ BleSocket() = default;
+ explicit BleSocket(BlePeripheral* peripheral) : peripheral_(peripheral) {}
+ ~BleSocket() override;
+
+ // Connect to another BleSocket, to form a functional low-level channel.
+ // from this point on, and until Close is called, connection exists.
+ void Connect(BleSocket& other) ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns the InputStream of this connected BleSocket.
+ InputStream& GetInputStream() override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns the OutputStream of this connected BleSocket.
+ // This stream is for local side to write.
+ OutputStream& GetOutputStream() override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns address of a remote BleSocket or nullptr.
+ BleSocket* GetRemoteSocket() ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns true if connection exists to the (possibly closed) remote socket.
+ bool IsConnected() const ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns true if socket is closed.
+ bool IsClosed() const ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns Exception::kIo on error, Exception::kSuccess otherwise.
+ Exception Close() override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns valid BlePeripheral pointer if there is a connection, and
+ // nullptr otherwise.
+ BlePeripheral* GetRemotePeripheral() override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ private:
+ void DoClose() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Returns true if connection exists to the (possibly closed) remote socket.
+ bool IsConnectedLocked() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Returns InputStream of our side of a connection.
+ // This is what the remote side is supposed to read from.
+ // This is a helper for GetInputStream() method.
+ InputStream& GetLocalInputStream() ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns OutputStream of our side of a connection.
+ // This is what the local size is supposed to write to.
+ // This is a helper for GetOutputStream() method.
+ OutputStream& GetLocalOutputStream() ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Output pipe is initialized by constructor, it remains always valid, until
+ // it is closed. it represents output part of a local socket. Input part of a
+ // local socket comes from the peer socket, after connection.
+ std::shared_ptr<Pipe> output_{new Pipe};
+ std::shared_ptr<Pipe> input_;
+ mutable absl::Mutex mutex_;
+ BlePeripheral* peripheral_;
+ BleSocket* remote_socket_ ABSL_GUARDED_BY(mutex_) = nullptr;
+ bool closed_ ABSL_GUARDED_BY(mutex_) = false;
+};
+
+class BleServerSocket {
+ public:
+ ~BleServerSocket();
+
+ // Blocks until either:
+ // - at least one incoming connection request is available, or
+ // - ServerSocket is closed.
+ // On success, returns connected socket, ready to exchange data.
+ // Returns nullptr on error.
+ // Once error is reported, it is permanent, and ServerSocket has to be closed.
+ //
+ // Called by the server side of a connection.
+ // Returns BleSocket to the server side.
+ // If not null, returned socket is connected to its remote (client-side) peer.
+ std::unique_ptr<api::BleSocket> Accept(BlePeripheral* peripheral)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Blocks until either:
+ // - connection is available, or
+ // - server socket is closed, or
+ // - error happens.
+ //
+ // Called by the client side of a connection.
+ // Returns true, if socket is successfully connected.
+ bool Connect(BleSocket& socket) ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Called by the server side of a connection before passing ownership of
+ // BleServerSocker to user, to track validity of a pointer to this
+ // server socket,
+ void SetCloseNotifier(std::function<void()> notifier)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns Exception::kIo on error, Exception::kSuccess otherwise.
+ // Calls close_notifier if it was previously set, and marks socket as closed.
+ Exception Close() ABSL_LOCKS_EXCLUDED(mutex_);
+
+ private:
+ Exception DoClose() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ absl::Mutex mutex_;
+ absl::CondVar cond_;
+ absl::flat_hash_set<BleSocket*> pending_sockets_ ABSL_GUARDED_BY(mutex_);
+ std::function<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
+ bool closed_ ABSL_GUARDED_BY(mutex_) = false;
+};
+
+// Container of operations that can be performed over the BLE medium.
+class BleMedium : public api::BleMedium {
+ public:
+ explicit BleMedium(api::BluetoothAdapter& adapter);
+ ~BleMedium() override;
+
+ // Returns true once the Ble advertising has been initiated.
+ bool StartAdvertising(
+ const std::string& service_id, const ByteArray& advertisement_bytes,
+ const std::string& fast_advertisement_service_uuid) override
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ bool StopAdvertising(const std::string& service_id) override
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns true once the Ble scanning has been initiated.
+ bool StartScanning(const std::string& service_id,
+ const std::string& fast_advertisement_service_uuid,
+ DiscoveredPeripheralCallback callback) override
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns true once Ble scanning for service_id is well and truly
+ // stopped; after this returns, there must be no more invocations of the
+ // DiscoveredPeripheralCallback passed in to StartScanning() for service_id.
+ bool StopScanning(const std::string& service_id) override
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns true once Ble socket connection requests to service_id can be
+ // accepted.
+ bool StartAcceptingConnections(const std::string& service_id,
+ AcceptedConnectionCallback callback) override
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ bool StopAcceptingConnections(const std::string& service_id) override
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Connects to existing remote Ble peripheral.
+ //
+ // On success, returns a new BleSocket.
+ // On error, returns nullptr.
+ std::unique_ptr<api::BleSocket> Connect(
+ api::BlePeripheral& remote_peripheral, const std::string& service_id,
+ CancellationFlag* cancellation_flag) override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ BluetoothAdapter& GetAdapter() { return *adapter_; }
+
+ private:
+ static constexpr int kMaxConcurrentAcceptLoops = 5;
+
+ struct AdvertisingInfo {
+ bool Empty() const { return service_id.empty(); }
+ void Clear() { service_id.clear(); }
+
+ std::string service_id;
+ };
+
+ struct ScanningInfo {
+ bool Empty() const { return service_id.empty(); }
+ void Clear() { service_id.clear(); }
+
+ std::string service_id;
+ };
+
+ absl::Mutex mutex_;
+ BluetoothAdapter* adapter_; // Our device adapter; read-only.
+
+ // A thread pool dedicated to running all the accept loops from
+ // StartAdvertising().
+ MultiThreadExecutor accept_loops_runner_{kMaxConcurrentAcceptLoops};
+ std::atomic_bool acceptance_thread_running_ = false;
+
+ // A thread pool dedicated to wait to complete the accept_loops_runner_.
+ MultiThreadExecutor close_accept_loops_runner_{kMaxConcurrentAcceptLoops};
+
+ // A server socket is established when start advertising.
+ std::unique_ptr<BleServerSocket> server_socket_;
+ AdvertisingInfo advertising_info_ ABSL_GUARDED_BY(mutex_);
+ ScanningInfo scanning_info_ ABSL_GUARDED_BY(mutex_);
+};
+
+} // namespace g3
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_G3_BLE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/g3/bluetooth_adapter.cc b/chromium/third_party/nearby/src/internal/platform/implementation/g3/bluetooth_adapter.cc
new file mode 100644
index 00000000000..bfa4b86bda8
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/g3/bluetooth_adapter.cc
@@ -0,0 +1,135 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/g3/bluetooth_adapter.h"
+
+#include <string>
+
+#include "internal/platform/medium_environment.h"
+#include "internal/platform/prng.h"
+#include "internal/platform/implementation/g3/bluetooth_classic.h"
+
+namespace location {
+namespace nearby {
+namespace g3 {
+
+BlePeripheral::BlePeripheral(BluetoothAdapter* adapter) : adapter_(*adapter) {}
+
+std::string BlePeripheral::GetName() const { return adapter_.GetName(); }
+
+ByteArray BlePeripheral::GetAdvertisementBytes(
+ const std::string& service_id) const {
+ return advertisement_bytes_;
+}
+
+void BlePeripheral::SetAdvertisementBytes(
+ const std::string& service_id, const ByteArray& advertisement_bytes) {
+ advertisement_bytes_ = advertisement_bytes;
+}
+
+BluetoothDevice::BluetoothDevice(BluetoothAdapter* adapter)
+ : adapter_(*adapter) {}
+
+std::string BluetoothDevice::GetName() const { return adapter_.GetName(); }
+std::string BluetoothDevice::GetMacAddress() const {
+ return adapter_.GetMacAddress();
+}
+
+BluetoothAdapter::BluetoothAdapter() {
+ std::string mac_address;
+ mac_address.resize(6);
+ int64_t raw_mac_addr = Prng().NextInt64();
+ mac_address[0] = static_cast<char>(raw_mac_addr >> 40);
+ mac_address[1] = static_cast<char>(raw_mac_addr >> 32);
+ mac_address[2] = static_cast<char>(raw_mac_addr >> 24);
+ mac_address[3] = static_cast<char>(raw_mac_addr >> 16);
+ mac_address[4] = static_cast<char>(raw_mac_addr >> 8);
+ mac_address[5] = static_cast<char>(raw_mac_addr >> 0);
+ SetMacAddress(mac_address);
+}
+
+BluetoothAdapter::~BluetoothAdapter() { SetStatus(Status::kDisabled); }
+
+void BluetoothAdapter::SetBluetoothClassicMedium(
+ api::BluetoothClassicMedium* medium) {
+ bluetooth_classic_medium_ = medium;
+}
+
+void BluetoothAdapter::SetBleMedium(api::BleMedium* medium) {
+ ble_medium_ = medium;
+}
+
+bool BluetoothAdapter::SetStatus(Status status) {
+ BluetoothAdapter::ScanMode mode;
+ bool enabled = status == Status::kEnabled;
+ std::string name;
+ {
+ absl::MutexLock lock(&mutex_);
+ enabled_ = enabled;
+ name = name_;
+ mode = mode_;
+ }
+ auto& env = MediumEnvironment::Instance();
+ env.OnBluetoothAdapterChangedState(*this, device_, name, enabled, mode);
+ return true;
+}
+
+bool BluetoothAdapter::IsEnabled() const {
+ absl::MutexLock lock(&mutex_);
+ return enabled_;
+}
+
+BluetoothAdapter::ScanMode BluetoothAdapter::GetScanMode() const {
+ absl::MutexLock lock(&mutex_);
+ return mode_;
+}
+
+bool BluetoothAdapter::SetScanMode(BluetoothAdapter::ScanMode mode) {
+ bool enabled;
+ std::string name;
+ {
+ absl::MutexLock lock(&mutex_);
+ mode_ = mode;
+ name = name_;
+ enabled = enabled_;
+ }
+ auto& env = MediumEnvironment::Instance();
+ env.OnBluetoothAdapterChangedState(*this, device_, std::move(name), enabled,
+ mode);
+ return true;
+}
+
+std::string BluetoothAdapter::GetName() const {
+ absl::MutexLock lock(&mutex_);
+ return name_;
+}
+
+bool BluetoothAdapter::SetName(absl::string_view name) {
+ BluetoothAdapter::ScanMode mode;
+ bool enabled;
+ {
+ absl::MutexLock lock(&mutex_);
+ name_ = name;
+ enabled = enabled_;
+ mode = mode_;
+ }
+ auto& env = MediumEnvironment::Instance();
+ env.OnBluetoothAdapterChangedState(*this, device_, std::string(name), enabled,
+ mode);
+ return true;
+}
+
+} // namespace g3
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/g3/bluetooth_adapter.h b/chromium/third_party/nearby/src/internal/platform/implementation/g3/bluetooth_adapter.h
new file mode 100644
index 00000000000..b1e80ed1e10
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/g3/bluetooth_adapter.h
@@ -0,0 +1,142 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_G3_BLUETOOTH_ADAPTER_H_
+#define PLATFORM_IMPL_G3_BLUETOOTH_ADAPTER_H_
+
+#include <string>
+
+#include "absl/base/thread_annotations.h"
+#include "absl/strings/string_view.h"
+#include "absl/synchronization/mutex.h"
+#include "internal/platform/implementation/ble.h"
+#include "internal/platform/implementation/bluetooth_adapter.h"
+#include "internal/platform/implementation/bluetooth_classic.h"
+#include "internal/platform/implementation/g3/single_thread_executor.h"
+
+namespace location {
+namespace nearby {
+namespace g3 {
+
+// BluetoothDevice and BluetoothAdapter have a mutual dependency.
+class BluetoothAdapter;
+
+// Opaque wrapper over a Ble peripheral. Must contain enough data about a
+// particular Ble device to connect to its GATT server.
+class BlePeripheral : public api::BlePeripheral {
+ public:
+ ~BlePeripheral() override = default;
+
+ std::string GetName() const override;
+ ByteArray GetAdvertisementBytes(const std::string& service_id) const override;
+ void SetAdvertisementBytes(const std::string& service_id,
+ const ByteArray& advertisement_bytes);
+ BluetoothAdapter& GetAdapter() { return adapter_; }
+
+ private:
+ // Only BluetoothAdapter may instantiate BlePeripheral.
+ friend class BluetoothAdapter;
+
+ explicit BlePeripheral(BluetoothAdapter* adapter);
+
+ BluetoothAdapter& adapter_;
+ ByteArray advertisement_bytes_;
+};
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html.
+class BluetoothDevice : public api::BluetoothDevice {
+ public:
+ ~BluetoothDevice() override = default;
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#getName()
+ std::string GetName() const override;
+ std::string GetMacAddress() const override;
+ BluetoothAdapter& GetAdapter() { return adapter_; }
+
+ private:
+ // Only BluetoothAdapter may instantiate BluetoothDevice.
+ friend class BluetoothAdapter;
+
+ explicit BluetoothDevice(BluetoothAdapter* adapter);
+
+ BluetoothAdapter& adapter_;
+};
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html
+class BluetoothAdapter : public api::BluetoothAdapter {
+ public:
+ using Status = api::BluetoothAdapter::Status;
+ using ScanMode = api::BluetoothAdapter::ScanMode;
+
+ BluetoothAdapter();
+ ~BluetoothAdapter() override;
+
+ // Synchronously sets the status of the BluetoothAdapter to 'status', and
+ // returns true if the operation was a success.
+ bool SetStatus(Status status) override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns true if the BluetoothAdapter's current status is
+ // Status::Value::kEnabled.
+ bool IsEnabled() const override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getScanMode()
+ //
+ // Returns ScanMode::kUnknown on error.
+ ScanMode GetScanMode() const override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Synchronously sets the scan mode of the adapter, and returns true if the
+ // operation was a success.
+ bool SetScanMode(ScanMode mode) override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getName()
+ // Returns an empty string on error
+ std::string GetName() const override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#setName(java.lang.String)
+ bool SetName(absl::string_view name) override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns BT MAC address assigned to this adapter.
+ std::string GetMacAddress() const override { return mac_address_; }
+
+ BluetoothDevice& GetDevice() { return device_; }
+
+ void SetBluetoothClassicMedium(api::BluetoothClassicMedium* medium);
+ api::BluetoothClassicMedium* GetBluetoothClassicMedium() {
+ return bluetooth_classic_medium_;
+ }
+
+ BlePeripheral& GetPeripheral() { return peripheral_; }
+
+ void SetBleMedium(api::BleMedium* medium);
+ api::BleMedium* GetBleMedium() { return ble_medium_; }
+
+ void SetMacAddress(std::string& mac_address) { mac_address_ = mac_address; }
+
+ private:
+ mutable absl::Mutex mutex_;
+ BluetoothDevice device_{this};
+ BlePeripheral peripheral_{this};
+ api::BluetoothClassicMedium* bluetooth_classic_medium_ = nullptr;
+ api::BleMedium* ble_medium_ = nullptr;
+ std::string mac_address_;
+ ScanMode mode_ ABSL_GUARDED_BY(mutex_) = ScanMode::kNone;
+ std::string name_ ABSL_GUARDED_BY(mutex_) = "unknown G3 BT device";
+ bool enabled_ ABSL_GUARDED_BY(mutex_) = false;
+};
+
+} // namespace g3
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_G3_BLUETOOTH_ADAPTER_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/g3/bluetooth_classic.cc b/chromium/third_party/nearby/src/internal/platform/implementation/g3/bluetooth_classic.cc
new file mode 100644
index 00000000000..8034778749d
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/g3/bluetooth_classic.cc
@@ -0,0 +1,278 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/g3/bluetooth_classic.h"
+
+#include <memory>
+#include <string>
+
+#include "absl/synchronization/mutex.h"
+#include "internal/platform/implementation/bluetooth_classic.h"
+#include "internal/platform/cancellation_flag_listener.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/medium_environment.h"
+#include "internal/platform/implementation/g3/bluetooth_adapter.h"
+
+namespace location {
+namespace nearby {
+namespace g3 {
+
+BluetoothSocket::~BluetoothSocket() {
+ absl::MutexLock lock(&mutex_);
+ DoClose();
+}
+
+void BluetoothSocket::Connect(BluetoothSocket& other) {
+ absl::MutexLock lock(&mutex_);
+ remote_socket_ = &other;
+ input_ = other.output_;
+}
+
+bool BluetoothSocket::IsConnected() const {
+ absl::MutexLock lock(&mutex_);
+ return IsConnectedLocked();
+}
+
+bool BluetoothSocket::IsClosed() const {
+ absl::MutexLock lock(&mutex_);
+ return closed_;
+}
+
+bool BluetoothSocket::IsConnectedLocked() const { return input_ != nullptr; }
+
+InputStream& BluetoothSocket::GetInputStream() {
+ auto* remote_socket = GetRemoteSocket();
+ CHECK(remote_socket != nullptr);
+ return remote_socket->GetLocalInputStream();
+}
+
+OutputStream& BluetoothSocket::GetOutputStream() {
+ return GetLocalOutputStream();
+}
+
+InputStream& BluetoothSocket::GetLocalInputStream() {
+ absl::MutexLock lock(&mutex_);
+ return output_->GetInputStream();
+}
+
+OutputStream& BluetoothSocket::GetLocalOutputStream() {
+ absl::MutexLock lock(&mutex_);
+ return output_->GetOutputStream();
+}
+
+Exception BluetoothSocket::Close() {
+ absl::MutexLock lock(&mutex_);
+ DoClose();
+ return {Exception::kSuccess};
+}
+
+void BluetoothSocket::DoClose() {
+ if (!closed_) {
+ remote_socket_ = nullptr;
+ output_->GetOutputStream().Close();
+ output_->GetInputStream().Close();
+ input_->GetOutputStream().Close();
+ input_->GetInputStream().Close();
+ closed_ = true;
+ }
+}
+
+BluetoothSocket* BluetoothSocket::GetRemoteSocket() {
+ absl::MutexLock lock(&mutex_);
+ return remote_socket_;
+}
+
+BluetoothDevice* BluetoothSocket::GetRemoteDevice() {
+ BluetoothAdapter* remote_adapter = nullptr;
+ {
+ absl::MutexLock lock(&mutex_);
+ if (remote_socket_ == nullptr || remote_socket_->adapter_ == nullptr) {
+ return nullptr;
+ }
+ remote_adapter = remote_socket_->adapter_;
+ }
+ return remote_adapter ? &remote_adapter->GetDevice() : nullptr;
+}
+
+std::unique_ptr<api::BluetoothSocket> BluetoothServerSocket::Accept() {
+ absl::MutexLock lock(&mutex_);
+ while (!closed_ && pending_sockets_.empty()) {
+ cond_.Wait(&mutex_);
+ }
+ // whether or not we were running in the wait loop, return early if closed.
+ if (closed_) return {};
+ auto* remote_socket =
+ pending_sockets_.extract(pending_sockets_.begin()).value();
+ CHECK(remote_socket);
+ auto local_socket = std::make_unique<BluetoothSocket>(adapter_);
+ local_socket->Connect(*remote_socket);
+ remote_socket->Connect(*local_socket);
+ cond_.SignalAll();
+ return local_socket;
+}
+
+bool BluetoothServerSocket::Connect(BluetoothSocket& socket) {
+ absl::MutexLock lock(&mutex_);
+ if (closed_) return false;
+ if (socket.IsConnected()) {
+ NEARBY_LOGS(ERROR)
+ << "Failed to connect to BT server socket: already connected";
+ return true; // already connected.
+ }
+ // add client socket to the pending list
+ pending_sockets_.emplace(&socket);
+ cond_.SignalAll();
+ while (!socket.IsConnected()) {
+ cond_.Wait(&mutex_);
+ if (closed_) return false;
+ }
+ return true;
+}
+
+void BluetoothServerSocket::SetCloseNotifier(std::function<void()> notifier) {
+ absl::MutexLock lock(&mutex_);
+ close_notifier_ = std::move(notifier);
+}
+
+BluetoothServerSocket::~BluetoothServerSocket() {
+ absl::MutexLock lock(&mutex_);
+ DoClose();
+}
+
+Exception BluetoothServerSocket::Close() {
+ absl::MutexLock lock(&mutex_);
+ return DoClose();
+}
+
+Exception BluetoothServerSocket::DoClose() {
+ bool should_notify = !closed_;
+ closed_ = true;
+ if (should_notify) {
+ cond_.SignalAll();
+ if (close_notifier_) {
+ auto notifier = std::move(close_notifier_);
+ mutex_.Unlock();
+ // Notifier may contain calls to public API, and may cause deadlock, if
+ // mutex_ is held during the call.
+ notifier();
+ mutex_.Lock();
+ }
+ }
+ return {Exception::kSuccess};
+}
+
+BluetoothClassicMedium::BluetoothClassicMedium(api::BluetoothAdapter& adapter)
+ // TODO(apolyudov): implement and use downcast<> with static assertions.
+ : adapter_(static_cast<BluetoothAdapter*>(&adapter)) {
+ adapter_->SetBluetoothClassicMedium(this);
+ auto& env = MediumEnvironment::Instance();
+ env.RegisterBluetoothMedium(*this, GetAdapter());
+}
+
+BluetoothClassicMedium::~BluetoothClassicMedium() {
+ adapter_->SetBluetoothClassicMedium(nullptr);
+ auto& env = MediumEnvironment::Instance();
+ env.UnregisterBluetoothMedium(*this);
+}
+
+bool BluetoothClassicMedium::StartDiscovery(DiscoveryCallback callback) {
+ auto& env = MediumEnvironment::Instance();
+ env.UpdateBluetoothMedium(*this, std::move(callback));
+ return true;
+}
+
+bool BluetoothClassicMedium::StopDiscovery() {
+ auto& env = MediumEnvironment::Instance();
+ env.UpdateBluetoothMedium(*this, {});
+ return true;
+}
+
+std::unique_ptr<api::BluetoothSocket> BluetoothClassicMedium::ConnectToService(
+ api::BluetoothDevice& remote_device, const std::string& service_uuid,
+ CancellationFlag* cancellation_flag) {
+ NEARBY_LOGS(INFO) << "G3 ConnectToService [self]: medium=" << this
+ << ", adapter=" << &GetAdapter()
+ << ", device=" << &GetAdapter().GetDevice();
+ // First, find an instance of remote medium, that exposed this device.
+ auto& adapter = static_cast<BluetoothDevice&>(remote_device).GetAdapter();
+ auto* medium =
+ static_cast<BluetoothClassicMedium*>(adapter.GetBluetoothClassicMedium());
+
+ if (!medium) return {}; // Adapter is not bound to medium. Bail out.
+
+ BluetoothServerSocket* server_socket = nullptr;
+ NEARBY_LOGS(INFO) << "G3 ConnectToService [peer]: medium=" << medium
+ << ", adapter=" << &adapter << ", device=" << &remote_device
+ << ", uuid=" << service_uuid.c_str();
+ // Then, find our server socket context in this medium.
+ {
+ absl::MutexLock medium_lock(&medium->mutex_);
+ auto item = medium->sockets_.find(service_uuid);
+ server_socket = item != sockets_.end() ? item->second : nullptr;
+ if (server_socket == nullptr) {
+ NEARBY_LOGS(ERROR) << "Failed to find BT Server socket: uuid="
+ << service_uuid;
+ return {};
+ }
+ }
+
+ if (cancellation_flag->Cancelled()) {
+ NEARBY_LOGS(ERROR) << "G3 Bluetooth Connect: Has been cancelled: "
+ "service_uuid="
+ << service_uuid;
+ return {};
+ }
+
+ CancellationFlagListener listener(cancellation_flag, [&server_socket]() {
+ NEARBY_LOGS(INFO) << "G3 Bluetooth Cancel Connect.";
+ if (server_socket != nullptr) server_socket->Close();
+ });
+
+ auto socket = std::make_unique<BluetoothSocket>(&GetAdapter());
+ // Finally, Request to connect to this socket.
+ if (!server_socket->Connect(*socket)) {
+ NEARBY_LOGS(ERROR)
+ << "Failed to connect to existing BT Server socket: uuid="
+ << service_uuid;
+ return {};
+ }
+ NEARBY_LOGS(INFO) << "G3 ConnectToService: connected: socket="
+ << socket.get();
+ return socket;
+}
+
+std::unique_ptr<api::BluetoothServerSocket>
+BluetoothClassicMedium::ListenForService(const std::string& service_name,
+ const std::string& service_uuid) {
+ auto socket = std::make_unique<BluetoothServerSocket>(GetAdapter());
+ socket->SetCloseNotifier([this, uuid = service_uuid]() {
+ absl::MutexLock lock(&mutex_);
+ sockets_.erase(uuid);
+ });
+ NEARBY_LOGS(INFO) << "Adding service: medium=" << this
+ << ", uuid=" << service_uuid;
+ absl::MutexLock lock(&mutex_);
+ sockets_.emplace(service_uuid, socket.get());
+ return socket;
+}
+
+api::BluetoothDevice* BluetoothClassicMedium::GetRemoteDevice(
+ const std::string& mac_address) {
+ auto& env = MediumEnvironment::Instance();
+ return env.FindBluetoothDevice(mac_address);
+}
+
+} // namespace g3
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/g3/bluetooth_classic.h b/chromium/third_party/nearby/src/internal/platform/implementation/g3/bluetooth_classic.h
new file mode 100644
index 00000000000..93c82c4f119
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/g3/bluetooth_classic.h
@@ -0,0 +1,238 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_G3_BLUETOOTH_CLASSIC_H_
+#define PLATFORM_IMPL_G3_BLUETOOTH_CLASSIC_H_
+
+#include <memory>
+#include <string>
+
+#include "absl/container/flat_hash_map.h"
+#include "absl/container/flat_hash_set.h"
+#include "absl/synchronization/mutex.h"
+#include "internal/platform/implementation/bluetooth_classic.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/input_stream.h"
+#include "internal/platform/listeners.h"
+#include "internal/platform/output_stream.h"
+#include "internal/platform/implementation/g3/bluetooth_adapter.h"
+#include "internal/platform/implementation/g3/pipe.h"
+
+namespace location {
+namespace nearby {
+namespace g3 {
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html.
+class BluetoothSocket : public api::BluetoothSocket {
+ public:
+ BluetoothSocket() = default;
+ explicit BluetoothSocket(BluetoothAdapter* adapter) : adapter_(adapter) {}
+ ~BluetoothSocket() override;
+
+ // Connects to another BluetoothSocket, to form a functional low-level
+ // channel. From this point on, and until Close is called, connection exists.
+ void Connect(BluetoothSocket& other);
+
+ // NOTE:
+ // It is an undefined behavior if GetInputStream() or GetOutputStream() is
+ // called for a not-connected BluetoothSocket, i.e. any object that is not
+ // returned by BluetoothClassicMedium::ConnectToService() for client side or
+ // BluetoothServerSocket::Accept() for server side of connection.
+
+ // Returns the InputStream of this connected BluetoothSocket.
+ InputStream& GetInputStream() override;
+
+ // Returns the OutputStream of this connected BluetoothSocket.
+ // This stream is for local side to write.
+ OutputStream& GetOutputStream() override;
+
+ // Returns address of a remote BluetoothSocket or nullptr.
+ BluetoothSocket* GetRemoteSocket() ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns true if connection exists to the (possibly closed) remote socket.
+ bool IsConnected() const ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns true if socket is closed.
+ bool IsClosed() const ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Closes both input and output streams, marks Socket as closed.
+ // After this call object should be treated as not connected.
+ // Returns Exception::kIo on error, Exception::kSuccess otherwise.
+ Exception Close() override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#getRemoteDevice()
+ // Returns valid BluetoothDevice pointer if there is a connection, and
+ // nullptr otherwise.
+ BluetoothDevice* GetRemoteDevice() override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ private:
+ void DoClose() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Returns true if connection exists to the (possibly closed) remote socket.
+ bool IsConnectedLocked() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Returns InputStream of our side of a connection.
+ // This is what the remote side is supposed to read from.
+ // This is a helper for GetInputStream() method.
+ InputStream& GetLocalInputStream() ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns OutputStream of our side of a connection.
+ // This is what the local size is supposed to write to.
+ // This is a helper for GetOutputStream() method.
+ OutputStream& GetLocalOutputStream() ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Output pipe is initialized by constructor, it remains always valid, until
+ // it is closed. it represents output part of a local socket. Input part of a
+ // local socket comes from the peer socket, after connection.
+ std::shared_ptr<Pipe> output_{new Pipe};
+ std::shared_ptr<Pipe> input_;
+ mutable absl::Mutex mutex_;
+ BluetoothAdapter* adapter_ = nullptr; // Our Adapter. Read only.
+ BluetoothSocket* remote_socket_ ABSL_GUARDED_BY(mutex_) = nullptr;
+ bool closed_ ABSL_GUARDED_BY(mutex_) = false;
+};
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html.
+class BluetoothServerSocket : public api::BluetoothServerSocket {
+ public:
+ explicit BluetoothServerSocket(BluetoothAdapter& adapter)
+ : adapter_(&adapter) {}
+ ~BluetoothServerSocket() override;
+
+ // Blocks until either:
+ // - at least one incoming connection request is available, or
+ // - ServerSocket is closed.
+ // On success, returns connected socket, ready to exchange data.
+ // Returns nullptr on error.
+ // Once error is reported, it is permanent, and ServerSocket has to be closed.
+ //
+ // Called by the server side of a connection.
+ // Returns BluetoothSocket to the server side.
+ // If not null, returned socket is connected to its remote (client-side) peer.
+ std::unique_ptr<api::BluetoothSocket> Accept() override
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Blocks until either:
+ // - connection is available, or
+ // - server socket is closed, or
+ // - error happens.
+ //
+ // Called by the client side of a connection.
+ // socket is an initialized BluetoothSocket, associated with a client
+ // BluetoothAdapter.
+ // Returns true, if socket is successfully connected.
+ bool Connect(BluetoothSocket& socket) ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Called by the server side of a connection before passing ownership of
+ // BluetoothServerSocker to user, to track validity of a pointer to this
+ // server socket,
+ void SetCloseNotifier(std::function<void()> notifier)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns Exception::kIo on error, Exception::kSuccess otherwise.
+ // Calls close_notifier if it was previously set, and marks socket as closed.
+ Exception Close() override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ private:
+ Exception DoClose() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ absl::Mutex mutex_;
+ absl::CondVar cond_;
+ BluetoothAdapter* adapter_ = nullptr; // Our Adapter. Read only.
+ absl::flat_hash_set<BluetoothSocket*> pending_sockets_
+ ABSL_GUARDED_BY(mutex_);
+ std::function<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
+ bool closed_ ABSL_GUARDED_BY(mutex_) = false;
+};
+
+// Container of operations that can be performed over the Bluetooth Classic
+// medium.
+class BluetoothClassicMedium : public api::BluetoothClassicMedium {
+ public:
+ explicit BluetoothClassicMedium(api::BluetoothAdapter& adapter);
+ ~BluetoothClassicMedium() override;
+
+ // NOTE(DiscoveryCallback):
+ // BluetoothDevice is a proxy object created as a result of BT discovery.
+ // Its lifetime spans between calls to device_discovered_cb and
+ // device_lost_cb.
+ // It is safe to use BluetoothDevice in device_discovered_cb() callback
+ // and at any time afterwards, until device_lost_cb() is called.
+ // It is not safe to use BluetoothDevice after returning from
+ // device_lost_cb() callback.
+ // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#startDiscovery()
+ //
+ // Returns true once the process of discovery has been initiated.
+ bool StartDiscovery(DiscoveryCallback callback) override
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#cancelDiscovery()
+ //
+ // Returns true once discovery is well and truly stopped; after this returns,
+ // there must be no more invocations of the DiscoveryCallback passed in to
+ // StartDiscovery().
+ bool StopDiscovery() override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Connects to existing remote BT service.
+ //
+ // A combination of
+ // https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#createInsecureRfcommSocketToServiceRecord
+ // followed by
+ // https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#connect().
+ //
+ // service_uuid is the canonical textual representation
+ // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format) of a
+ // type 3 name-based
+ // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based))
+ // UUID.
+ //
+ // On success, returns a new BluetoothSocket.
+ // On error, returns nullptr.
+ std::unique_ptr<api::BluetoothSocket> ConnectToService(
+ api::BluetoothDevice& remote_device, const std::string& service_uuid,
+ CancellationFlag* cancellation_flag) override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ BluetoothAdapter& GetAdapter() { return *adapter_; }
+
+ // Creates BT service, and begins listening for remote attempts to connect.
+ //
+ // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#listenUsingInsecureRfcommWithServiceRecord
+ //
+ // service_uuid is the canonical textual representation
+ // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format) of a
+ // type 3 name-based
+ // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based))
+ // UUID.
+ //
+ // Returns nullptr on error.
+ std::unique_ptr<api::BluetoothServerSocket> ListenForService(
+ const std::string& service_name, const std::string& service_uuid) override
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ api::BluetoothDevice* GetRemoteDevice(
+ const std::string& mac_address) override;
+
+ private:
+ absl::Mutex mutex_;
+ BluetoothAdapter* adapter_; // Our device adapter; read-only.
+ absl::flat_hash_map<std::string, BluetoothServerSocket*> sockets_
+ ABSL_GUARDED_BY(mutex_);
+};
+
+} // namespace g3
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_G3_BLUETOOTH_CLASSIC_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/g3/condition_variable.h b/chromium/third_party/nearby/src/internal/platform/implementation/g3/condition_variable.h
new file mode 100644
index 00000000000..ae513d269b6
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/g3/condition_variable.h
@@ -0,0 +1,51 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_G3_CONDITION_VARIABLE_H_
+#define PLATFORM_IMPL_G3_CONDITION_VARIABLE_H_
+
+#include "absl/synchronization/mutex.h"
+#include "internal/platform/implementation/condition_variable.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/implementation/g3/mutex.h"
+
+namespace location {
+namespace nearby {
+namespace g3 {
+
+class ConditionVariable : public api::ConditionVariable {
+ public:
+ explicit ConditionVariable(g3::Mutex* mutex) : mutex_(&mutex->mutex_) {}
+ ~ConditionVariable() override = default;
+
+ Exception Wait() override {
+ cond_var_.Wait(mutex_);
+ return {Exception::kSuccess};
+ }
+ Exception Wait(absl::Duration timeout) override {
+ cond_var_.WaitWithTimeout(mutex_, timeout);
+ return {Exception::kSuccess};
+ }
+ void Notify() override { cond_var_.SignalAll(); }
+
+ private:
+ absl::Mutex* mutex_;
+ absl::CondVar cond_var_;
+};
+
+} // namespace g3
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_G3_CONDITION_VARIABLE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/g3/crypto.cc b/chromium/third_party/nearby/src/internal/platform/implementation/g3/crypto.cc
new file mode 100644
index 00000000000..fdad337ea53
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/g3/crypto.cc
@@ -0,0 +1,53 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/crypto.h"
+
+#include <cstdint>
+#include <string>
+
+#include "absl/strings/string_view.h"
+#include "internal/platform/byte_array.h"
+#include "src/include/openssl/digest.h"
+
+namespace location {
+namespace nearby {
+
+// Initialize global crypto state.
+void Crypto::Init() {}
+
+static ByteArray Hash(absl::string_view input, const EVP_MD* algo) {
+ unsigned int md_out_size = EVP_MAX_MD_SIZE;
+ uint8_t digest_buffer[EVP_MAX_MD_SIZE];
+ if (input.empty()) return {};
+
+ if (!EVP_Digest(input.data(), input.size(), digest_buffer, &md_out_size, algo,
+ nullptr))
+ return {};
+
+ return ByteArray{reinterpret_cast<char*>(digest_buffer), md_out_size};
+}
+
+// Return MD5 hash of input.
+ByteArray Crypto::Md5(absl::string_view input) {
+ return Hash(input, EVP_md5());
+}
+
+// Return SHA256 hash of input.
+ByteArray Crypto::Sha256(absl::string_view input) {
+ return Hash(input, EVP_sha256());
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/g3/log_message.cc b/chromium/third_party/nearby/src/internal/platform/implementation/g3/log_message.cc
new file mode 100644
index 00000000000..045e1649a21
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/g3/log_message.cc
@@ -0,0 +1,86 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/g3/log_message.h"
+
+#include <algorithm>
+#include <cstdio>
+
+namespace location {
+namespace nearby {
+namespace g3 {
+
+namespace {
+
+// This is a partial copy of base::StringAppendV for OSS compilation.
+void NearbyStringAppendV(std::string* dst, const char* format, va_list ap) {
+ // Fixed size buffer 1024 should be big enough.
+ static const int kSpaceLength = 1024;
+ char space[kSpaceLength];
+ int result = vsnprintf(space, kSpaceLength, format, ap);
+ va_end(ap);
+ dst->append(space, result);
+}
+} // namespace
+
+api::LogMessage::Severity g_min_log_severity = api::LogMessage::Severity::kInfo;
+
+inline absl::LogSeverity ConvertSeverity(api::LogMessage::Severity severity) {
+ switch (severity) {
+ // api::LogMessage::Severity kVerbose and kInfo is mapped to
+ // absl::LogSeverity kInfo since absl::LogSeverity doesn't have kVerbose
+ // level.
+ case api::LogMessage::Severity::kVerbose:
+ case api::LogMessage::Severity::kInfo:
+ return absl::LogSeverity::kInfo;
+ case api::LogMessage::Severity::kWarning:
+ return absl::LogSeverity::kWarning;
+ case api::LogMessage::Severity::kError:
+ return absl::LogSeverity::kError;
+ case api::LogMessage::Severity::kFatal:
+ return absl::LogSeverity::kFatal;
+ }
+}
+
+LogMessage::LogMessage(const char* file, int line, Severity severity)
+ : log_streamer_(ConvertSeverity(severity), file, line) {}
+
+LogMessage::~LogMessage() = default;
+
+void LogMessage::Print(const char* format, ...) {
+ va_list ap;
+ va_start(ap, format);
+ std::string result;
+ NearbyStringAppendV(&result, format, ap);
+ log_streamer_.stream() << result;
+ va_end(ap);
+}
+
+std::ostream& LogMessage::Stream() { return log_streamer_.stream(); }
+
+} // namespace g3
+
+namespace api {
+
+void LogMessage::SetMinLogSeverity(Severity severity) {
+ g3::g_min_log_severity = severity;
+}
+
+bool LogMessage::ShouldCreateLogMessage(Severity severity) {
+ return severity >= g3::g_min_log_severity;
+}
+
+} // namespace api
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/g3/log_message.h b/chromium/third_party/nearby/src/internal/platform/implementation/g3/log_message.h
new file mode 100644
index 00000000000..4c5c8a4c35d
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/g3/log_message.h
@@ -0,0 +1,44 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_G3_LOG_MESSAGE_H_
+#define PLATFORM_IMPL_G3_LOG_MESSAGE_H_
+
+#include "glog/logging.h"
+#include "internal/platform/implementation/log_message.h"
+
+namespace location {
+namespace nearby {
+namespace g3 {
+
+// See documentation in
+// cpp/platform/api/log_message.h
+class LogMessage : public api::LogMessage {
+ public:
+ LogMessage(const char* file, int line, Severity severity);
+ ~LogMessage() override;
+
+ void Print(const char* format, ...) override;
+
+ std::ostream& Stream() override;
+
+ private:
+ google::LogMessage log_streamer_;
+};
+
+} // namespace g3
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_G3_LOG_MESSAGE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/g3/multi_thread_executor.h b/chromium/third_party/nearby/src/internal/platform/implementation/g3/multi_thread_executor.h
new file mode 100644
index 00000000000..106fb8eeae0
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/g3/multi_thread_executor.h
@@ -0,0 +1,66 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_G3_MULTI_THREAD_EXECUTOR_H_
+#define PLATFORM_IMPL_G3_MULTI_THREAD_EXECUTOR_H_
+
+#include <atomic>
+
+#include "absl/time/clock.h"
+#include "internal/platform/implementation/submittable_executor.h"
+#include "internal/platform/implementation/shared/count_down_latch.h"
+#include "nisaba/port/thread_pool.h"
+
+namespace location {
+namespace nearby {
+namespace g3 {
+
+// An Executor that reuses a fixed number of threads operating off a shared
+// unbounded queue.
+class MultiThreadExecutor : public api::SubmittableExecutor {
+ public:
+ explicit MultiThreadExecutor(int max_parallelism)
+ : thread_pool_(max_parallelism) {
+ thread_pool_.StartWorkers();
+ }
+ void Execute(Runnable&& runnable) override {
+ if (!shutdown_) {
+ thread_pool_.Schedule(std::move(runnable));
+ }
+ }
+ bool DoSubmit(Runnable&& runnable) override {
+ if (shutdown_) return false;
+ thread_pool_.Schedule(std::move(runnable));
+ return true;
+ }
+ void Shutdown() override { DoShutdown(); }
+ ~MultiThreadExecutor() override { DoShutdown(); }
+
+ void ScheduleAfter(absl::Duration delay, Runnable&& runnable) {
+ if (shutdown_) return;
+ thread_pool_.ScheduleAt(absl::Now() + delay, std::move(runnable));
+ }
+ bool InShutdown() const { return shutdown_; }
+
+ private:
+ void DoShutdown() { shutdown_ = true; }
+ std::atomic_bool shutdown_ = false;
+ ThreadPool thread_pool_;
+};
+
+} // namespace g3
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_G3_MULTI_THREAD_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/g3/mutex.h b/chromium/third_party/nearby/src/internal/platform/implementation/g3/mutex.h
new file mode 100644
index 00000000000..962c506d0d7
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/g3/mutex.h
@@ -0,0 +1,61 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_G3_MUTEX_H_
+#define PLATFORM_IMPL_G3_MUTEX_H_
+
+#include "absl/synchronization/mutex.h"
+#include "internal/platform/implementation/mutex.h"
+#include "internal/platform/implementation/shared/posix_mutex.h"
+
+namespace location {
+namespace nearby {
+namespace g3 {
+
+class ABSL_LOCKABLE Mutex : public api::Mutex {
+ public:
+ explicit Mutex(bool check) : check_(check) {}
+ ~Mutex() override = default;
+ Mutex(Mutex&&) = delete;
+ Mutex& operator=(Mutex&&) = delete;
+ Mutex(const Mutex&) = delete;
+ Mutex& operator=(const Mutex&) = delete;
+
+ void Lock() ABSL_EXCLUSIVE_LOCK_FUNCTION() override {
+ mutex_.Lock();
+ if (!check_) mutex_.ForgetDeadlockInfo();
+ }
+ void Unlock() ABSL_UNLOCK_FUNCTION() override { mutex_.Unlock(); }
+
+ private:
+ friend class ConditionVariable;
+ absl::Mutex mutex_;
+ bool check_;
+};
+
+class ABSL_LOCKABLE RecursiveMutex : public posix::Mutex {
+ public:
+ ~RecursiveMutex() override = default;
+ RecursiveMutex() = default;
+ RecursiveMutex(RecursiveMutex&&) = delete;
+ RecursiveMutex& operator=(RecursiveMutex&&) = delete;
+ RecursiveMutex(const RecursiveMutex&) = delete;
+ RecursiveMutex& operator=(const RecursiveMutex&) = delete;
+};
+
+} // namespace g3
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_G3_MUTEX_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/g3/pipe.h b/chromium/third_party/nearby/src/internal/platform/implementation/g3/pipe.h
new file mode 100644
index 00000000000..842cf7d6a30
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/g3/pipe.h
@@ -0,0 +1,44 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_G3_PIPE_H_
+#define PLATFORM_IMPL_G3_PIPE_H_
+
+#include <memory>
+
+#include "internal/platform/base_pipe.h"
+#include "internal/platform/implementation/g3/condition_variable.h"
+#include "internal/platform/implementation/g3/mutex.h"
+
+namespace location {
+namespace nearby {
+namespace g3 {
+
+class Pipe : public BasePipe {
+ public:
+ Pipe() {
+ auto mutex = std::make_unique<g3::Mutex>(/*check=*/true);
+ auto cond = std::make_unique<g3::ConditionVariable>(mutex.get());
+ Setup(std::move(mutex), std::move(cond));
+ }
+ ~Pipe() override = default;
+ Pipe(Pipe&&) = delete;
+ Pipe& operator=(Pipe&&) = delete;
+};
+
+} // namespace g3
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_G3_PIPE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/g3/platform.cc b/chromium/third_party/nearby/src/internal/platform/implementation/g3/platform.cc
new file mode 100644
index 00000000000..ed937acd10e
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/g3/platform.cc
@@ -0,0 +1,176 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/platform.h"
+
+#include <atomic>
+#include <cstdint>
+#include <memory>
+
+#include "absl/memory/memory.h"
+#include "absl/strings/str_cat.h"
+#include "absl/time/time.h"
+#include "internal/platform/implementation/atomic_boolean.h"
+#include "internal/platform/implementation/atomic_reference.h"
+#include "internal/platform/implementation/ble_v2.h"
+#include "internal/platform/implementation/bluetooth_adapter.h"
+#include "internal/platform/implementation/bluetooth_classic.h"
+#include "internal/platform/implementation/condition_variable.h"
+#include "internal/platform/implementation/shared/count_down_latch.h"
+#include "internal/platform/implementation/log_message.h"
+#include "internal/platform/implementation/mutex.h"
+#include "internal/platform/implementation/scheduled_executor.h"
+#include "internal/platform/implementation/server_sync.h"
+#include "internal/platform/implementation/submittable_executor.h"
+#ifndef NO_WEBRTC
+#include "internal/platform/implementation/g3/webrtc.h"
+#include "internal/platform/implementation/webrtc.h"
+#endif
+#include "internal/platform/implementation/g3/atomic_boolean.h"
+#include "internal/platform/implementation/g3/atomic_reference.h"
+#include "internal/platform/implementation/g3/ble.h"
+#include "internal/platform/implementation/g3/bluetooth_adapter.h"
+#include "internal/platform/implementation/g3/bluetooth_classic.h"
+#include "internal/platform/implementation/g3/condition_variable.h"
+#include "internal/platform/implementation/g3/log_message.h"
+#include "internal/platform/implementation/g3/multi_thread_executor.h"
+#include "internal/platform/implementation/g3/mutex.h"
+#include "internal/platform/implementation/g3/scheduled_executor.h"
+#include "internal/platform/implementation/g3/single_thread_executor.h"
+#include "internal/platform/implementation/g3/wifi_lan.h"
+#include "internal/platform/implementation/shared/file.h"
+#include "internal/platform/implementation/wifi.h"
+#include "internal/platform/medium_environment.h"
+
+namespace location {
+namespace nearby {
+namespace api {
+
+namespace {
+std::string GetPayloadPath(PayloadId payload_id) {
+ return absl::StrCat("/tmp/", payload_id);
+}
+} // namespace
+
+int GetCurrentTid() {
+ const LiveThread* my = Thread_GetMyLiveThread();
+ return LiveThread_Pthread_TID(my);
+}
+
+std::unique_ptr<SubmittableExecutor>
+ImplementationPlatform::CreateSingleThreadExecutor() {
+ return absl::make_unique<g3::SingleThreadExecutor>();
+}
+
+std::unique_ptr<SubmittableExecutor>
+ImplementationPlatform::CreateMultiThreadExecutor(int max_concurrency) {
+ return absl::make_unique<g3::MultiThreadExecutor>(max_concurrency);
+}
+
+std::unique_ptr<ScheduledExecutor>
+ImplementationPlatform::CreateScheduledExecutor() {
+ return absl::make_unique<g3::ScheduledExecutor>();
+}
+
+std::unique_ptr<AtomicUint32> ImplementationPlatform::CreateAtomicUint32(
+ std::uint32_t value) {
+ return absl::make_unique<g3::AtomicUint32>(value);
+}
+
+std::unique_ptr<BluetoothAdapter>
+ImplementationPlatform::CreateBluetoothAdapter() {
+ return absl::make_unique<g3::BluetoothAdapter>();
+}
+
+std::unique_ptr<CountDownLatch> ImplementationPlatform::CreateCountDownLatch(
+ std::int32_t count) {
+ return absl::make_unique<shared::CountDownLatch>(count);
+}
+
+std::unique_ptr<AtomicBoolean> ImplementationPlatform::CreateAtomicBoolean(
+ bool initial_value) {
+ return absl::make_unique<g3::AtomicBoolean>(initial_value);
+}
+
+std::unique_ptr<InputFile> ImplementationPlatform::CreateInputFile(
+ PayloadId payload_id, std::int64_t total_size) {
+ return shared::IOFile::CreateInputFile(GetPayloadPath(payload_id),
+ total_size);
+}
+
+std::unique_ptr<OutputFile> ImplementationPlatform::CreateOutputFile(
+ PayloadId payload_id) {
+ return shared::IOFile::CreateOutputFile(GetPayloadPath(payload_id));
+}
+
+std::unique_ptr<LogMessage> ImplementationPlatform::CreateLogMessage(
+ const char* file, int line, LogMessage::Severity severity) {
+ return absl::make_unique<g3::LogMessage>(file, line, severity);
+}
+
+std::unique_ptr<BluetoothClassicMedium>
+ImplementationPlatform::CreateBluetoothClassicMedium(
+ api::BluetoothAdapter& adapter) {
+ return absl::make_unique<g3::BluetoothClassicMedium>(adapter);
+}
+
+std::unique_ptr<BleMedium> ImplementationPlatform::CreateBleMedium(
+ api::BluetoothAdapter& adapter) {
+ return absl::make_unique<g3::BleMedium>(adapter);
+}
+
+std::unique_ptr<ble_v2::BleMedium> ImplementationPlatform::CreateBleV2Medium(
+ api::BluetoothAdapter& adapter) {
+ return std::unique_ptr<ble_v2::BleMedium>();
+}
+
+std::unique_ptr<ServerSyncMedium>
+ImplementationPlatform::CreateServerSyncMedium() {
+ return std::unique_ptr<ServerSyncMedium>(/*new ServerSyncMediumImpl()*/);
+}
+
+std::unique_ptr<WifiMedium> ImplementationPlatform::CreateWifiMedium() {
+ return std::unique_ptr<WifiMedium>();
+}
+
+std::unique_ptr<WifiLanMedium> ImplementationPlatform::CreateWifiLanMedium() {
+ return absl::make_unique<g3::WifiLanMedium>();
+}
+
+#ifndef NO_WEBRTC
+std::unique_ptr<WebRtcMedium> ImplementationPlatform::CreateWebRtcMedium() {
+ if (MediumEnvironment::Instance().GetEnvironmentConfig().webrtc_enabled) {
+ return absl::make_unique<g3::WebRtcMedium>();
+ } else {
+ return nullptr;
+ }
+}
+#endif
+
+std::unique_ptr<Mutex> ImplementationPlatform::CreateMutex(Mutex::Mode mode) {
+ if (mode == Mutex::Mode::kRecursive)
+ return absl::make_unique<g3::RecursiveMutex>();
+ else
+ return absl::make_unique<g3::Mutex>(mode == Mutex::Mode::kRegular);
+}
+
+std::unique_ptr<ConditionVariable>
+ImplementationPlatform::CreateConditionVariable(Mutex* mutex) {
+ return std::unique_ptr<ConditionVariable>(
+ new g3::ConditionVariable(static_cast<g3::Mutex*>(mutex)));
+}
+
+} // namespace api
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/g3/scheduled_executor.cc b/chromium/third_party/nearby/src/internal/platform/implementation/g3/scheduled_executor.cc
new file mode 100644
index 00000000000..2013f20f4f2
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/g3/scheduled_executor.cc
@@ -0,0 +1,79 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/g3/scheduled_executor.h"
+
+#include <atomic>
+#include <memory>
+
+#include "absl/time/clock.h"
+#include "internal/platform/implementation/cancelable.h"
+#include "internal/platform/runnable.h"
+
+namespace location {
+namespace nearby {
+namespace g3 {
+
+namespace {
+
+class ScheduledCancelable : public api::Cancelable {
+ public:
+ bool Cancel() override {
+ Status expected = kNotRun;
+ while (expected == kNotRun) {
+ if (status_.compare_exchange_strong(expected, kCanceled)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ bool MarkExecuted() {
+ Status expected = kNotRun;
+ while (expected == kNotRun) {
+ if (status_.compare_exchange_strong(expected, kExecuted)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private:
+ enum Status {
+ kNotRun,
+ kExecuted,
+ kCanceled,
+ };
+ std::atomic<Status> status_ = kNotRun;
+};
+
+} // namespace
+
+std::shared_ptr<api::Cancelable> ScheduledExecutor::Schedule(
+ Runnable&& runnable, absl::Duration delay) {
+ auto scheduled_cancelable = std::make_shared<ScheduledCancelable>();
+ if (executor_.InShutdown()) {
+ return scheduled_cancelable;
+ }
+ executor_.ScheduleAfter(
+ delay, [this, scheduled_cancelable, runnable(std::move(runnable))]() {
+ if (!executor_.InShutdown() && scheduled_cancelable->MarkExecuted()) {
+ runnable();
+ }
+ });
+ return scheduled_cancelable;
+}
+
+} // namespace g3
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/g3/scheduled_executor.h b/chromium/third_party/nearby/src/internal/platform/implementation/g3/scheduled_executor.h
new file mode 100644
index 00000000000..2c1c3baae67
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/g3/scheduled_executor.h
@@ -0,0 +1,54 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_G3_SCHEDULED_EXECUTOR_H_
+#define PLATFORM_IMPL_G3_SCHEDULED_EXECUTOR_H_
+
+#include <atomic>
+#include <memory>
+
+#include "absl/time/clock.h"
+#include "internal/platform/implementation/cancelable.h"
+#include "internal/platform/implementation/scheduled_executor.h"
+#include "internal/platform/runnable.h"
+#include "internal/platform/implementation/g3/single_thread_executor.h"
+#include "nisaba/port/thread_pool.h"
+
+namespace location {
+namespace nearby {
+namespace g3 {
+
+// An Executor that reuses a fixed number of threads operating off a shared
+// unbounded queue.
+class ScheduledExecutor final : public api::ScheduledExecutor {
+ public:
+ ScheduledExecutor() = default;
+ ~ScheduledExecutor() override { executor_.Shutdown(); }
+
+ void Execute(Runnable&& runnable) override {
+ executor_.Execute(std::move(runnable));
+ }
+ std::shared_ptr<api::Cancelable> Schedule(Runnable&& runnable,
+ absl::Duration delay) override;
+ void Shutdown() override { executor_.Shutdown(); }
+
+ private:
+ SingleThreadExecutor executor_;
+};
+
+} // namespace g3
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_G3_SCHEDULED_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/g3/single_thread_executor.h b/chromium/third_party/nearby/src/internal/platform/implementation/g3/single_thread_executor.h
new file mode 100644
index 00000000000..1164e629049
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/g3/single_thread_executor.h
@@ -0,0 +1,36 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_G3_SINGLE_THREAD_EXECUTOR_H_
+#define PLATFORM_IMPL_G3_SINGLE_THREAD_EXECUTOR_H_
+
+#include "internal/platform/implementation/g3/multi_thread_executor.h"
+
+namespace location {
+namespace nearby {
+namespace g3 {
+
+// An Executor that uses a single worker thread operating off an unbounded
+// queue.
+class SingleThreadExecutor final : public MultiThreadExecutor {
+ public:
+ SingleThreadExecutor() : MultiThreadExecutor(1) {}
+ ~SingleThreadExecutor() override = default;
+};
+
+} // namespace g3
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_G3_SINGLE_THREAD_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/g3/system_clock.cc b/chromium/third_party/nearby/src/internal/platform/implementation/g3/system_clock.cc
new file mode 100644
index 00000000000..2a860aa2734
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/g3/system_clock.cc
@@ -0,0 +1,30 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/system_clock.h"
+
+#include "absl/time/clock.h"
+#include "internal/platform/exception.h"
+
+namespace location {
+namespace nearby {
+
+absl::Time SystemClock::ElapsedRealtime() { return absl::Now(); }
+Exception SystemClock::Sleep(absl::Duration duration) {
+ absl::SleepFor(duration);
+ return {Exception::kSuccess};
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/g3/webrtc.cc b/chromium/third_party/nearby/src/internal/platform/implementation/g3/webrtc.cc
new file mode 100644
index 00000000000..c6bc2387851
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/g3/webrtc.cc
@@ -0,0 +1,97 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/g3/webrtc.h"
+
+#include <memory>
+
+#include "internal/platform/medium_environment.h"
+#include "webrtc/api/task_queue/default_task_queue_factory.h"
+
+namespace location {
+namespace nearby {
+namespace g3 {
+
+WebRtcSignalingMessenger::WebRtcSignalingMessenger(
+ absl::string_view self_id, const connections::LocationHint& location_hint)
+ : self_id_(self_id), location_hint_(location_hint) {}
+
+bool WebRtcSignalingMessenger::SendMessage(absl::string_view peer_id,
+ const ByteArray& message) {
+ auto& env = MediumEnvironment::Instance();
+ env.SendWebRtcSignalingMessage(peer_id, message);
+ return true;
+}
+
+bool WebRtcSignalingMessenger::StartReceivingMessages(
+ OnSignalingMessageCallback on_message_callback,
+ OnSignalingCompleteCallback on_complete_callback) {
+ auto& env = MediumEnvironment::Instance();
+ env.RegisterWebRtcSignalingMessenger(self_id_, on_message_callback,
+ on_complete_callback);
+ return true;
+}
+
+void WebRtcSignalingMessenger::StopReceivingMessages() {
+ auto& env = MediumEnvironment::Instance();
+ env.UnregisterWebRtcSignalingMessenger(self_id_);
+}
+
+WebRtcMedium::~WebRtcMedium() { single_thread_executor_.Shutdown(); }
+
+const std::string WebRtcMedium::GetDefaultCountryCode() { return "US"; }
+
+void WebRtcMedium::CreatePeerConnection(
+ webrtc::PeerConnectionObserver* observer, PeerConnectionCallback callback) {
+ auto& env = MediumEnvironment::Instance();
+ if (!env.GetUseValidPeerConnection()) {
+ callback(nullptr);
+ return;
+ }
+
+ webrtc::PeerConnectionInterface::RTCConfiguration rtc_config;
+ rtc_config.sdp_semantics = webrtc::SdpSemantics::kUnifiedPlan;
+ webrtc::PeerConnectionDependencies dependencies(observer);
+
+ std::unique_ptr<rtc::Thread> signaling_thread = rtc::Thread::Create();
+ signaling_thread->SetName("signaling_thread", nullptr);
+ RTC_CHECK(signaling_thread->Start()) << "Failed to start thread";
+
+ webrtc::PeerConnectionFactoryDependencies factory_dependencies;
+ factory_dependencies.task_queue_factory =
+ webrtc::CreateDefaultTaskQueueFactory();
+ factory_dependencies.signaling_thread = signaling_thread.release();
+
+ rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection =
+ webrtc::CreateModularPeerConnectionFactory(
+ std::move(factory_dependencies))
+ ->CreatePeerConnection(rtc_config, std::move(dependencies));
+
+ single_thread_executor_.Execute(
+ [&env, callback = std::move(callback),
+ peer_connection = std::move(peer_connection)]() {
+ absl::SleepFor(env.GetPeerConnectionLatency());
+ callback(peer_connection);
+ });
+}
+
+std::unique_ptr<api::WebRtcSignalingMessenger>
+WebRtcMedium::GetSignalingMessenger(
+ absl::string_view self_id, const connections::LocationHint& location_hint) {
+ return std::make_unique<WebRtcSignalingMessenger>(self_id, location_hint);
+}
+
+} // namespace g3
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/g3/webrtc.h b/chromium/third_party/nearby/src/internal/platform/implementation/g3/webrtc.h
new file mode 100644
index 00000000000..2edeb8dff0d
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/g3/webrtc.h
@@ -0,0 +1,81 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_G3_WEBRTC_H_
+#define PLATFORM_IMPL_G3_WEBRTC_H_
+
+#include <memory>
+
+#include "absl/strings/string_view.h"
+#include "internal/platform/implementation/webrtc.h"
+#include "internal/platform/implementation/g3/single_thread_executor.h"
+#include "webrtc/api/peer_connection_interface.h"
+
+namespace location {
+namespace nearby {
+namespace g3 {
+
+class WebRtcSignalingMessenger : public api::WebRtcSignalingMessenger {
+ public:
+ using OnSignalingMessageCallback =
+ api::WebRtcSignalingMessenger::OnSignalingMessageCallback;
+ using OnSignalingCompleteCallback =
+ api::WebRtcSignalingMessenger::OnSignalingCompleteCallback;
+
+ explicit WebRtcSignalingMessenger(
+ absl::string_view self_id,
+ const connections::LocationHint& location_hint);
+ ~WebRtcSignalingMessenger() override = default;
+
+ bool SendMessage(absl::string_view peer_id,
+ const ByteArray& message) override;
+ bool StartReceivingMessages(
+ OnSignalingMessageCallback on_message_callback,
+ OnSignalingCompleteCallback on_complete_callback) override;
+ void StopReceivingMessages() override;
+
+ private:
+ std::string self_id_;
+ connections::LocationHint location_hint_;
+};
+
+class WebRtcMedium : public api::WebRtcMedium {
+ public:
+ using PeerConnectionCallback = api::WebRtcMedium::PeerConnectionCallback;
+
+ WebRtcMedium() = default;
+ ~WebRtcMedium() override;
+
+ const std::string GetDefaultCountryCode() override;
+
+ // Creates and returns a new webrtc::PeerConnectionInterface object via
+ // |callback|.
+ void CreatePeerConnection(webrtc::PeerConnectionObserver* observer,
+ PeerConnectionCallback callback) override;
+
+ // Returns a signaling messenger for sending WebRTC signaling messages.
+ std::unique_ptr<api::WebRtcSignalingMessenger> GetSignalingMessenger(
+ absl::string_view self_id,
+ const connections::LocationHint& location_hint) override;
+
+ private:
+ // Executor for handling calls to create a peer connection.
+ SingleThreadExecutor single_thread_executor_;
+};
+
+} // namespace g3
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_G3_WEBRTC_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/g3/wifi_lan.cc b/chromium/third_party/nearby/src/internal/platform/implementation/g3/wifi_lan.cc
new file mode 100644
index 00000000000..e07de9a6996
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/g3/wifi_lan.cc
@@ -0,0 +1,371 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/g3/wifi_lan.h"
+
+#include <iostream>
+#include <memory>
+#include <string>
+#include <utility>
+
+#include "absl/strings/escaping.h"
+#include "absl/strings/str_format.h"
+#include "absl/synchronization/mutex.h"
+#include "internal/platform/implementation/wifi_lan.h"
+#include "internal/platform/cancellation_flag_listener.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/medium_environment.h"
+#include "internal/platform/nsd_service_info.h"
+
+namespace location {
+namespace nearby {
+namespace g3 {
+
+WifiLanSocket::~WifiLanSocket() {
+ absl::MutexLock lock(&mutex_);
+ DoClose();
+}
+
+void WifiLanSocket::Connect(WifiLanSocket& other) {
+ absl::MutexLock lock(&mutex_);
+ remote_socket_ = &other;
+ input_ = other.output_;
+}
+
+InputStream& WifiLanSocket::GetInputStream() {
+ auto* remote_socket = GetRemoteSocket();
+ CHECK(remote_socket != nullptr);
+ return remote_socket->GetLocalInputStream();
+}
+
+OutputStream& WifiLanSocket::GetOutputStream() {
+ return GetLocalOutputStream();
+}
+
+WifiLanSocket* WifiLanSocket::GetRemoteSocket() {
+ absl::MutexLock lock(&mutex_);
+ return remote_socket_;
+}
+
+bool WifiLanSocket::IsConnected() const {
+ absl::MutexLock lock(&mutex_);
+ return IsConnectedLocked();
+}
+
+bool WifiLanSocket::IsClosed() const {
+ absl::MutexLock lock(&mutex_);
+ return closed_;
+}
+
+Exception WifiLanSocket::Close() {
+ absl::MutexLock lock(&mutex_);
+ DoClose();
+ return {Exception::kSuccess};
+}
+
+void WifiLanSocket::DoClose() {
+ if (!closed_) {
+ remote_socket_ = nullptr;
+ output_->GetOutputStream().Close();
+ output_->GetInputStream().Close();
+ input_->GetOutputStream().Close();
+ input_->GetInputStream().Close();
+ closed_ = true;
+ }
+}
+
+bool WifiLanSocket::IsConnectedLocked() const { return input_ != nullptr; }
+
+InputStream& WifiLanSocket::GetLocalInputStream() {
+ absl::MutexLock lock(&mutex_);
+ return output_->GetInputStream();
+}
+
+OutputStream& WifiLanSocket::GetLocalOutputStream() {
+ absl::MutexLock lock(&mutex_);
+ return output_->GetOutputStream();
+}
+
+std::string WifiLanServerSocket::GetName(const std::string& ip_address,
+ int port) {
+ std::string dot_delimited_string;
+ if (!ip_address.empty()) {
+ for (auto byte : ip_address) {
+ if (!dot_delimited_string.empty())
+ absl::StrAppend(&dot_delimited_string, ".");
+ absl::StrAppend(&dot_delimited_string, absl::StrFormat("%d", byte));
+ }
+ }
+ std::string out = absl::StrCat(dot_delimited_string, ":", port);
+ return out;
+}
+
+std::unique_ptr<api::WifiLanSocket> WifiLanServerSocket::Accept() {
+ absl::MutexLock lock(&mutex_);
+ while (!closed_ && pending_sockets_.empty()) {
+ cond_.Wait(&mutex_);
+ }
+ // whether or not we were running in the wait loop, return early if closed.
+ if (closed_) return {};
+ auto* remote_socket =
+ pending_sockets_.extract(pending_sockets_.begin()).value();
+ CHECK(remote_socket);
+
+ auto local_socket = std::make_unique<WifiLanSocket>();
+ local_socket->Connect(*remote_socket);
+ remote_socket->Connect(*local_socket);
+ cond_.SignalAll();
+ return local_socket;
+}
+
+bool WifiLanServerSocket::Connect(WifiLanSocket& socket) {
+ absl::MutexLock lock(&mutex_);
+ if (closed_) return false;
+ if (socket.IsConnected()) {
+ NEARBY_LOGS(ERROR)
+ << "Failed to connect to WifiLan server socket: already connected";
+ return true; // already connected.
+ }
+ // add client socket to the pending list
+ pending_sockets_.insert(&socket);
+ cond_.SignalAll();
+ while (!socket.IsConnected()) {
+ cond_.Wait(&mutex_);
+ if (closed_) return false;
+ }
+ return true;
+}
+
+void WifiLanServerSocket::SetCloseNotifier(std::function<void()> notifier) {
+ absl::MutexLock lock(&mutex_);
+ close_notifier_ = std::move(notifier);
+}
+
+WifiLanServerSocket::~WifiLanServerSocket() {
+ absl::MutexLock lock(&mutex_);
+ DoClose();
+}
+
+Exception WifiLanServerSocket::Close() {
+ absl::MutexLock lock(&mutex_);
+ return DoClose();
+}
+
+Exception WifiLanServerSocket::DoClose() {
+ bool should_notify = !closed_;
+ closed_ = true;
+ if (should_notify) {
+ cond_.SignalAll();
+ if (close_notifier_) {
+ auto notifier = std::move(close_notifier_);
+ mutex_.Unlock();
+ // Notifier may contain calls to public API, and may cause deadlock, if
+ // mutex_ is held during the call.
+ notifier();
+ mutex_.Lock();
+ }
+ }
+ return {Exception::kSuccess};
+}
+
+WifiLanMedium::WifiLanMedium() {
+ auto& env = MediumEnvironment::Instance();
+ env.RegisterWifiLanMedium(*this);
+}
+
+WifiLanMedium::~WifiLanMedium() {
+ auto& env = MediumEnvironment::Instance();
+ env.UnregisterWifiLanMedium(*this);
+}
+
+bool WifiLanMedium::StartAdvertising(const NsdServiceInfo& nsd_service_info) {
+ std::string service_type = nsd_service_info.GetServiceType();
+ NEARBY_LOGS(INFO) << "G3 WifiLan StartAdvertising: nsd_service_info="
+ << &nsd_service_info
+ << ", service_name=" << nsd_service_info.GetServiceName()
+ << ", service_type=" << service_type;
+ {
+ absl::MutexLock lock(&mutex_);
+ if (advertising_info_.Existed(service_type)) {
+ NEARBY_LOGS(INFO)
+ << "G3 WifiLan StartAdvertising: Can't start advertising because "
+ "service_type="
+ << service_type << ", has started already.";
+ return false;
+ }
+ }
+ auto& env = MediumEnvironment::Instance();
+ env.UpdateWifiLanMediumForAdvertising(*this, nsd_service_info,
+ /*enabled=*/true);
+ {
+ absl::MutexLock lock(&mutex_);
+ advertising_info_.Add(service_type);
+ }
+ return true;
+}
+
+bool WifiLanMedium::StopAdvertising(const NsdServiceInfo& nsd_service_info) {
+ std::string service_type = nsd_service_info.GetServiceType();
+ NEARBY_LOGS(INFO) << "G3 WifiLan StopAdvertising: nsd_service_info="
+ << &nsd_service_info
+ << ", service_name=" << nsd_service_info.GetServiceName()
+ << ", service_type=" << service_type;
+ {
+ absl::MutexLock lock(&mutex_);
+ if (!advertising_info_.Existed(service_type)) {
+ NEARBY_LOGS(INFO)
+ << "G3 WifiLan StopAdvertising: Can't stop advertising because "
+ "we never started advertising for service_type="
+ << service_type;
+ return false;
+ }
+ advertising_info_.Remove(service_type);
+ }
+ auto& env = MediumEnvironment::Instance();
+ env.UpdateWifiLanMediumForAdvertising(*this, nsd_service_info,
+ /*enabled=*/false);
+ return true;
+}
+
+bool WifiLanMedium::StartDiscovery(const std::string& service_type,
+ DiscoveredServiceCallback callback) {
+ NEARBY_LOGS(INFO) << "G3 WifiLan StartDiscovery: service_type="
+ << service_type;
+ {
+ absl::MutexLock lock(&mutex_);
+ if (discovering_info_.Existed(service_type)) {
+ NEARBY_LOGS(INFO)
+ << "G3 WifiLan StartDiscovery: Can't start discovery because "
+ "service_type="
+ << service_type << " has started already.";
+ return false;
+ }
+ }
+ auto& env = MediumEnvironment::Instance();
+ env.UpdateWifiLanMediumForDiscovery(*this, std::move(callback), service_type,
+ true);
+ {
+ absl::MutexLock lock(&mutex_);
+ discovering_info_.Add(service_type);
+ }
+ return true;
+}
+
+bool WifiLanMedium::StopDiscovery(const std::string& service_type) {
+ NEARBY_LOGS(INFO) << "G3 WifiLan StopDiscovery: service_type="
+ << service_type;
+ {
+ absl::MutexLock lock(&mutex_);
+ if (!discovering_info_.Existed(service_type)) {
+ NEARBY_LOGS(INFO)
+ << "G3 WifiLan StopDiscovery: Can't stop discovering because we "
+ "never started discovering.";
+ return false;
+ }
+ discovering_info_.Remove(service_type);
+ }
+ auto& env = MediumEnvironment::Instance();
+ env.UpdateWifiLanMediumForDiscovery(*this, {}, service_type, false);
+ return true;
+}
+
+std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
+ const NsdServiceInfo& remote_service_info,
+ CancellationFlag* cancellation_flag) {
+ std::string service_type = remote_service_info.GetServiceType();
+ NEARBY_LOGS(INFO) << "G3 WifiLan ConnectToService [self]: medium=" << this
+ << ", service_type=" << service_type;
+ return ConnectToService(remote_service_info.GetIPAddress(),
+ remote_service_info.GetPort(), cancellation_flag);
+}
+
+std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
+ const std::string& ip_address, int port,
+ CancellationFlag* cancellation_flag) {
+ std::string socket_name = WifiLanServerSocket::GetName(ip_address, port);
+ NEARBY_LOGS(INFO) << "G3 WifiLan ConnectToService [self]: medium=" << this
+ << ", ip address + port=" << socket_name;
+ // First, find an instance of remote medium, that exposed this service.
+ auto& env = MediumEnvironment::Instance();
+ auto* remote_medium =
+ static_cast<WifiLanMedium*>(env.GetWifiLanMedium(ip_address, port));
+ if (!remote_medium) {
+ return {};
+ }
+
+ WifiLanServerSocket* server_socket = nullptr;
+ NEARBY_LOGS(INFO) << "G3 WifiLan ConnectToService [peer]: medium="
+ << remote_medium
+ << ", remote ip address + port=" << socket_name;
+ // Then, find our server socket context in this medium.
+ {
+ absl::MutexLock medium_lock(&remote_medium->mutex_);
+ auto item = remote_medium->server_sockets_.find(socket_name);
+ server_socket = item != server_sockets_.end() ? item->second : nullptr;
+ if (server_socket == nullptr) {
+ NEARBY_LOGS(ERROR)
+ << "G3 WifiLan Failed to find WifiLan Server socket: socket_name="
+ << socket_name;
+ return {};
+ }
+ }
+
+ if (cancellation_flag->Cancelled()) {
+ NEARBY_LOGS(ERROR) << "G3 WifiLan Connect: Has been cancelled: socket_name="
+ << socket_name;
+ return {};
+ }
+
+ CancellationFlagListener listener(cancellation_flag, [&server_socket]() {
+ NEARBY_LOGS(INFO) << "G3 WifiLan Cancel Connect.";
+ if (server_socket != nullptr) {
+ server_socket->Close();
+ }
+ });
+
+ auto socket = std::make_unique<WifiLanSocket>();
+ // Finally, Request to connect to this socket.
+ if (!server_socket->Connect(*socket)) {
+ NEARBY_LOGS(ERROR) << "G3 WifiLan Failed to connect to existing WifiLan "
+ "Server socket: name="
+ << socket_name;
+ return {};
+ }
+ NEARBY_LOGS(INFO) << "G3 WifiLan ConnectToService: connected: socket="
+ << socket.get();
+ return socket;
+}
+
+std::unique_ptr<api::WifiLanServerSocket> WifiLanMedium::ListenForService(
+ int port) {
+ auto& env = MediumEnvironment::Instance();
+ auto server_socket = std::make_unique<WifiLanServerSocket>();
+ server_socket->SetIPAddress(env.GetFakeIPAddress());
+ server_socket->SetPort(port == 0 ? env.GetFakePort() : port);
+ std::string socket_name = WifiLanServerSocket::GetName(
+ server_socket->GetIPAddress(), server_socket->GetPort());
+ server_socket->SetCloseNotifier([this, socket_name]() {
+ absl::MutexLock lock(&mutex_);
+ server_sockets_.erase(socket_name);
+ });
+ NEARBY_LOGS(INFO) << "G3 WifiLan Adding server socket: medium=" << this
+ << ", socket_name=" << socket_name;
+ absl::MutexLock lock(&mutex_);
+ server_sockets_.insert({socket_name, server_socket.get()});
+ return server_socket;
+}
+
+} // namespace g3
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/g3/wifi_lan.h b/chromium/third_party/nearby/src/internal/platform/implementation/g3/wifi_lan.h
new file mode 100644
index 00000000000..870eb25e2cf
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/g3/wifi_lan.h
@@ -0,0 +1,285 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_G3_WIFI_LAN_H_
+#define PLATFORM_IMPL_G3_WIFI_LAN_H_
+
+#include <memory>
+#include <string>
+#include <utility>
+
+#include "absl/container/flat_hash_map.h"
+#include "absl/container/flat_hash_set.h"
+#include "absl/synchronization/mutex.h"
+#include "internal/platform/implementation/wifi_lan.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/input_stream.h"
+#include "internal/platform/nsd_service_info.h"
+#include "internal/platform/output_stream.h"
+#include "internal/platform/implementation/g3/multi_thread_executor.h"
+#include "internal/platform/implementation/g3/pipe.h"
+
+namespace location {
+namespace nearby {
+namespace g3 {
+
+class WifiLanMedium;
+
+class WifiLanSocket : public api::WifiLanSocket {
+ public:
+ WifiLanSocket() = default;
+ ~WifiLanSocket() override;
+
+ // Connect to another WifiLanSocket, to form a functional low-level channel.
+ // from this point on, and until Close is called, connection exists.
+ void Connect(WifiLanSocket& other) ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns the InputStream of this connected WifiLanSocket.
+ InputStream& GetInputStream() override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns the OutputStream of this connected WifiLanSocket.
+ // This stream is for local side to write.
+ OutputStream& GetOutputStream() override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns address of a remote WifiLanSocket or nullptr.
+ WifiLanSocket* GetRemoteSocket() ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns true if connection exists to the (possibly closed) remote socket.
+ bool IsConnected() const ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns true if socket is closed.
+ bool IsClosed() const ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns Exception::kIo on error, Exception::kSuccess otherwise.
+ Exception Close() override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ private:
+ void DoClose() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Returns true if connection exists to the (possibly closed) remote socket.
+ bool IsConnectedLocked() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ // Returns InputStream of our side of a connection.
+ // This is what the remote side is supposed to read from.
+ // This is a helper for GetInputStream() method.
+ InputStream& GetLocalInputStream() ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns OutputStream of our side of a connection.
+ // This is what the local size is supposed to write to.
+ // This is a helper for GetOutputStream() method.
+ OutputStream& GetLocalOutputStream() ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Output pipe is initialized by constructor, it remains always valid, until
+ // it is closed. it represents output part of a local socket. Input part of a
+ // local socket comes from the peer socket, after connection.
+ std::shared_ptr<Pipe> output_{new Pipe};
+ std::shared_ptr<Pipe> input_;
+ mutable absl::Mutex mutex_;
+ WifiLanSocket* remote_socket_ ABSL_GUARDED_BY(mutex_) = nullptr;
+ bool closed_ ABSL_GUARDED_BY(mutex_) = false;
+};
+
+class WifiLanServerSocket : public api::WifiLanServerSocket {
+ public:
+ static std::string GetName(const std::string& ip_address, int port);
+
+ ~WifiLanServerSocket() override;
+
+ // Gets ip address.
+ std::string GetIPAddress() const override ABSL_LOCKS_EXCLUDED(mutex_) {
+ absl::MutexLock lock(&mutex_);
+ return ip_address_;
+ }
+
+ // Sets the ip address.
+ void SetIPAddress(const std::string& ip_address) ABSL_LOCKS_EXCLUDED(mutex_) {
+ absl::MutexLock lock(&mutex_);
+ ip_address_ = ip_address;
+ }
+
+ // Gets the port.
+ int GetPort() const override ABSL_LOCKS_EXCLUDED(mutex_) {
+ absl::MutexLock lock(&mutex_);
+ return port_;
+ }
+
+ // Sets the port.
+ void SetPort(int port) ABSL_LOCKS_EXCLUDED(mutex_) {
+ absl::MutexLock lock(&mutex_);
+ port_ = port;
+ }
+
+ // Blocks until either:
+ // - at least one incoming connection request is available, or
+ // - ServerSocket is closed.
+ // On success, returns connected socket, ready to exchange data.
+ // Returns nullptr on error.
+ // Once error is reported, it is permanent, and ServerSocket has to be closed.
+ //
+ // Called by the server side of a connection.
+ // Returns WifiLanSocket to the server side.
+ // If not null, returned socket is connected to its remote (client-side) peer.
+ std::unique_ptr<api::WifiLanSocket> Accept() override
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Blocks until either:
+ // - connection is available, or
+ // - server socket is closed, or
+ // - error happens.
+ //
+ // Called by the client side of a connection.
+ // Returns true, if socket is successfully connected.
+ bool Connect(WifiLanSocket& socket) ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Called by the server side of a connection before passing ownership of
+ // WifiLanServerSocker to user, to track validity of a pointer to this
+ // server socket.
+ void SetCloseNotifier(std::function<void()> notifier)
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns Exception::kIo on error, Exception::kSuccess otherwise.
+ // Calls close_notifier if it was previously set, and marks socket as closed.
+ Exception Close() override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ private:
+ Exception DoClose() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ mutable absl::Mutex mutex_;
+ std::string ip_address_ ABSL_GUARDED_BY(mutex_);
+ int port_ ABSL_GUARDED_BY(mutex_);
+ absl::CondVar cond_;
+ absl::flat_hash_set<WifiLanSocket*> pending_sockets_ ABSL_GUARDED_BY(mutex_);
+ std::function<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
+ bool closed_ ABSL_GUARDED_BY(mutex_) = false;
+};
+
+// Container of operations that can be performed over the WifiLan medium.
+class WifiLanMedium : public api::WifiLanMedium {
+ public:
+ WifiLanMedium();
+ ~WifiLanMedium() override;
+
+ // Starts WifiLan advertising.
+ //
+ // nsd_service_info - NsdServiceInfo data that's advertised through mDNS
+ // service.
+ // On success if the service is now advertising.
+ // On error if the service cannot start to advertise or the service type in
+ // NsdServiceInfo has been passed previously which StopAdvertising is not
+ // been called.
+ bool StartAdvertising(const NsdServiceInfo& nsd_service_info) override
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Stops WifiLan advertising.
+ //
+ // nsd_service_info - NsdServiceInfo data that's advertised through mDNS
+ // service.
+ // On success if the service stops advertising.
+ // On error if the service cannot stop advertising or the service type in
+ // NsdServiceInfo cannot be found.
+ bool StopAdvertising(const NsdServiceInfo& nsd_service_info) override
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Starts the discovery of nearby WifiLan services.
+ //
+ // Returns true once the WifiLan discovery has been initiated. The
+ // service_type is associated with callback.
+ bool StartDiscovery(const std::string& service_type,
+ DiscoveredServiceCallback callback) override
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Stops the discovery of nearby WifiLan services.
+ //
+ // service_type - The one assigend in StartDiscovery.
+ // On success if service_type is matched to the callback and will be removed
+ // from the list. If list is empty then stops the WifiLan discovery
+ // service.
+ // On error if the service_type is not existed, then return immediately.
+ bool StopDiscovery(const std::string& service_type) override
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Connects to a WifiLan service.
+ // On success, returns a new WifiLanSocket.
+ // On error, returns nullptr.
+ std::unique_ptr<api::WifiLanSocket> ConnectToService(
+ const NsdServiceInfo& remote_service_info,
+ CancellationFlag* cancellation_flag) override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Connects to a WifiLan service by ip address and port.
+ // On success, returns a new WifiLanSocket.
+ // On error, returns nullptr.
+ std::unique_ptr<api::WifiLanSocket> ConnectToService(
+ const std::string& ip_address, int port,
+ CancellationFlag* cancellation_flag) override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Listens for incoming connection.
+ //
+ // port - A port number.
+ // 0 : use a random port.
+ // 1~65536 : open a server socket on that exact port.
+ // On success, returns a new WifiLanServerSocket.
+ // On error, returns nullptr.
+ std::unique_ptr<api::WifiLanServerSocket> ListenForService(int port) override
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ // Returns the port range as a pair of min and max port.
+ absl::optional<std::pair<std::int32_t, std::int32_t>> GetDynamicPortRange()
+ override {
+ return std::make_pair(49152, 65535);
+ }
+
+ private:
+ struct AdvertisingInfo {
+ bool Empty() const { return service_types.empty(); }
+ void Clear() { service_types.clear(); }
+ void Add(const std::string& service_type) {
+ service_types.insert(service_type);
+ }
+ void Remove(const std::string& service_type) {
+ service_types.erase(service_type);
+ }
+ bool Existed(const std::string& service_type) const {
+ return service_types.contains(service_type);
+ }
+
+ absl::flat_hash_set<std::string> service_types;
+ };
+ struct DiscoveringInfo {
+ bool Empty() const { return service_types.empty(); }
+ void Clear() { service_types.clear(); }
+ void Add(const std::string& service_type) {
+ service_types.insert(service_type);
+ }
+ void Remove(const std::string& service_type) {
+ service_types.erase(service_type);
+ }
+ bool Existed(const std::string& service_type) const {
+ return service_types.contains(service_type);
+ }
+
+ absl::flat_hash_set<std::string> service_types;
+ };
+
+ absl::Mutex mutex_;
+ AdvertisingInfo advertising_info_ ABSL_GUARDED_BY(mutex_);
+ DiscoveringInfo discovering_info_ ABSL_GUARDED_BY(mutex_);
+ absl::flat_hash_map<std::string, WifiLanServerSocket*> server_sockets_
+ ABSL_GUARDED_BY(mutex_);
+};
+
+} // namespace g3
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_G3_WIFI_LAN_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/input_file.h b/chromium/third_party/nearby/src/internal/platform/implementation/input_file.h
new file mode 100644
index 00000000000..4129b52a9fa
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/input_file.h
@@ -0,0 +1,40 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_API_INPUT_FILE_H_
+#define PLATFORM_API_INPUT_FILE_H_
+
+#include <cstdint>
+
+#include "internal/platform/byte_array.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/input_stream.h"
+
+namespace location {
+namespace nearby {
+namespace api {
+
+// An InputFile represents a readable file on the system.
+class InputFile : public InputStream {
+ public:
+ ~InputFile() override = default;
+ virtual std::string GetFilePath() const = 0;
+ virtual std::int64_t GetTotalSize() const = 0;
+};
+
+} // namespace api
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_API_INPUT_FILE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/BUILD b/chromium/third_party/nearby/src/internal/platform/implementation/ios/BUILD
new file mode 100644
index 00000000000..7c5c5be7ed7
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/BUILD
@@ -0,0 +1,72 @@
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+load("//tools/build_defs/apple:ios.bzl", "ios_static_framework")
+
+licenses(["notice"])
+
+package(default_visibility = ["//visibility:public"])
+
+objc_library(
+ name = "Connections",
+ srcs = [
+ "Source/Internal/GNCAdvertiser.mm",
+ "Source/Internal/GNCCore.mm",
+ "Source/Internal/GNCCoreConnection.mm",
+ "Source/Internal/GNCDiscoverer.mm",
+ "Source/Internal/GNCPayload.mm",
+ "Source/Internal/GNCPayloadListener.mm",
+ "Source/Internal/GNCUtils.mm",
+ "Source/Internal/platform.mm",
+ ],
+ hdrs = [
+ "Source/GNCAdvertiser.h",
+ "Source/GNCConnection.h",
+ "Source/GNCConnections.h",
+ "Source/GNCDiscoverer.h",
+ "Source/GNCPayload.h",
+ "Source/Internal/GNCCore.h",
+ "Source/Internal/GNCCoreConnection.h",
+ "Source/Internal/GNCPayload+Internal.h",
+ "Source/Internal/GNCPayloadListener.h",
+ "Source/Internal/GNCUtils.h",
+ ],
+ deps = [
+ "//connections:core",
+ "//connections:core_types",
+ "//internal/platform/implementation/ios/Source/Mediums",
+ "//internal/platform/implementation/ios/Source/Platform",
+ "//internal/platform/implementation/ios/Source/Shared",
+ "//third_party/objective_c/google_toolbox_for_mac:GTM_Logger",
+ "@com_google_absl//absl/functional:bind_front",
+ ],
+)
+
+MIN_IOS_VERSION = "12.0"
+
+HDRS_POD = [
+ "Source/GNCAdvertiser.h",
+ "Source/GNCConnection.h",
+ "Source/GNCDiscoverer.h",
+ "Source/GNCPayload.h",
+]
+
+ios_static_framework(
+ name = "NearbyConnections_framework",
+ hdrs = HDRS_POD,
+ bundle_name = "NearbyConnections",
+ minimum_os_version = MIN_IOS_VERSION,
+ deps = [
+ ":Connections",
+ ],
+)
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample.png b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample.png
new file mode 100644
index 00000000000..c495d68b156
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample.png
Binary files differ
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample.xcodeproj/project.pbxproj b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample.xcodeproj/project.pbxproj
new file mode 100644
index 00000000000..5f57eaffa2d
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample.xcodeproj/project.pbxproj
@@ -0,0 +1,355 @@
+// !$*UTF8*$!
+{
+ archiveVersion = 1;
+ classes = {
+ };
+ objectVersion = 50;
+ objects = {
+
+/* Begin PBXBuildFile section */
+ 41B7A2C3208F900100EBA53E /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 41B7A2C2208F900100EBA53E /* AppDelegate.m */; };
+ 41B7A2C6208F900100EBA53E /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 41B7A2C5208F900100EBA53E /* ViewController.m */; };
+ 41B7A2C9208F900100EBA53E /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 41B7A2C7208F900100EBA53E /* Main.storyboard */; };
+ 41B7A2CB208F900200EBA53E /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 41B7A2CA208F900200EBA53E /* Assets.xcassets */; };
+ 41B7A2CE208F900200EBA53E /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 41B7A2CC208F900200EBA53E /* LaunchScreen.storyboard */; };
+ 41B7A2D1208F900200EBA53E /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 41B7A2D0208F900200EBA53E /* main.m */; };
+/* End PBXBuildFile section */
+
+/* Begin PBXFileReference section */
+ 41B7A2BE208F900100EBA53E /* NearbyConnectionsExample.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = NearbyConnectionsExample.app; sourceTree = BUILT_PRODUCTS_DIR; };
+ 41B7A2C1208F900100EBA53E /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = "<group>"; };
+ 41B7A2C2208F900100EBA53E /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = "<group>"; };
+ 41B7A2C4208F900100EBA53E /* ViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ViewController.h; sourceTree = "<group>"; };
+ 41B7A2C5208F900100EBA53E /* ViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ViewController.m; sourceTree = "<group>"; };
+ 41B7A2C8208F900100EBA53E /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
+ 41B7A2CA208F900200EBA53E /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
+ 41B7A2CD208F900200EBA53E /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
+ 41B7A2CF208F900200EBA53E /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
+ 41B7A2D0208F900200EBA53E /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };
+/* End PBXFileReference section */
+
+/* Begin PBXFrameworksBuildPhase section */
+ 41B7A2BB208F900100EBA53E /* Frameworks */ = {
+ isa = PBXFrameworksBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXFrameworksBuildPhase section */
+
+/* Begin PBXGroup section */
+ 41B7A2B5208F900000EBA53E = {
+ isa = PBXGroup;
+ children = (
+ 41B7A2C0208F900100EBA53E /* NearbyConnectionsExample */,
+ 41B7A2BF208F900100EBA53E /* Products */,
+ );
+ sourceTree = "<group>";
+ };
+ 41B7A2BF208F900100EBA53E /* Products */ = {
+ isa = PBXGroup;
+ children = (
+ 41B7A2BE208F900100EBA53E /* NearbyConnectionsExample.app */,
+ );
+ name = Products;
+ sourceTree = "<group>";
+ };
+ 41B7A2C0208F900100EBA53E /* NearbyConnectionsExample */ = {
+ isa = PBXGroup;
+ children = (
+ 41B7A2C1208F900100EBA53E /* AppDelegate.h */,
+ 41B7A2C2208F900100EBA53E /* AppDelegate.m */,
+ 41B7A2C4208F900100EBA53E /* ViewController.h */,
+ 41B7A2C5208F900100EBA53E /* ViewController.m */,
+ 41B7A2C7208F900100EBA53E /* Main.storyboard */,
+ 41B7A2CA208F900200EBA53E /* Assets.xcassets */,
+ 41B7A2CC208F900200EBA53E /* LaunchScreen.storyboard */,
+ 41B7A2CF208F900200EBA53E /* Info.plist */,
+ 41B7A2D0208F900200EBA53E /* main.m */,
+ );
+ path = NearbyConnectionsExample;
+ sourceTree = "<group>";
+ };
+/* End PBXGroup section */
+
+/* Begin PBXNativeTarget section */
+ 41B7A2BD208F900100EBA53E /* NearbyConnectionsExample */ = {
+ isa = PBXNativeTarget;
+ buildConfigurationList = 41B7A2D4208F900200EBA53E /* Build configuration list for PBXNativeTarget "NearbyConnectionsExample" */;
+ buildPhases = (
+ 41B7A2BA208F900100EBA53E /* Sources */,
+ 41B7A2BB208F900100EBA53E /* Frameworks */,
+ 41B7A2BC208F900100EBA53E /* Resources */,
+ );
+ buildRules = (
+ );
+ dependencies = (
+ );
+ name = NearbyConnectionsExample;
+ productName = NearbyConnectionsExample;
+ productReference = 41B7A2BE208F900100EBA53E /* NearbyConnectionsExample.app */;
+ productType = "com.apple.product-type.application";
+ };
+/* End PBXNativeTarget section */
+
+/* Begin PBXProject section */
+ 41B7A2B6208F900000EBA53E /* Project object */ = {
+ isa = PBXProject;
+ attributes = {
+ LastUpgradeCheck = 0930;
+ ORGANIZATIONNAME = Google;
+ TargetAttributes = {
+ 41B7A2BD208F900100EBA53E = {
+ CreatedOnToolsVersion = 9.3;
+ };
+ };
+ };
+ buildConfigurationList = 41B7A2B9208F900000EBA53E /* Build configuration list for PBXProject "NearbyConnectionsExample" */;
+ compatibilityVersion = "Xcode 9.3";
+ developmentRegion = en;
+ hasScannedForEncodings = 0;
+ knownRegions = (
+ en,
+ Base,
+ );
+ mainGroup = 41B7A2B5208F900000EBA53E;
+ productRefGroup = 41B7A2BF208F900100EBA53E /* Products */;
+ projectDirPath = "";
+ projectRoot = "";
+ targets = (
+ 41B7A2BD208F900100EBA53E /* NearbyConnectionsExample */,
+ );
+ };
+/* End PBXProject section */
+
+/* Begin PBXResourcesBuildPhase section */
+ 41B7A2BC208F900100EBA53E /* Resources */ = {
+ isa = PBXResourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 41B7A2CE208F900200EBA53E /* LaunchScreen.storyboard in Resources */,
+ 41B7A2CB208F900200EBA53E /* Assets.xcassets in Resources */,
+ 41B7A2C9208F900100EBA53E /* Main.storyboard in Resources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXResourcesBuildPhase section */
+
+/* Begin PBXSourcesBuildPhase section */
+ 41B7A2BA208F900100EBA53E /* Sources */ = {
+ isa = PBXSourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 41B7A2C6208F900100EBA53E /* ViewController.m in Sources */,
+ 41B7A2D1208F900200EBA53E /* main.m in Sources */,
+ 41B7A2C3208F900100EBA53E /* AppDelegate.m in Sources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXSourcesBuildPhase section */
+
+/* Begin PBXVariantGroup section */
+ 41B7A2C7208F900100EBA53E /* Main.storyboard */ = {
+ isa = PBXVariantGroup;
+ children = (
+ 41B7A2C8208F900100EBA53E /* Base */,
+ );
+ name = Main.storyboard;
+ sourceTree = "<group>";
+ };
+ 41B7A2CC208F900200EBA53E /* LaunchScreen.storyboard */ = {
+ isa = PBXVariantGroup;
+ children = (
+ 41B7A2CD208F900200EBA53E /* Base */,
+ );
+ name = LaunchScreen.storyboard;
+ sourceTree = "<group>";
+ };
+/* End PBXVariantGroup section */
+
+/* Begin XCBuildConfiguration section */
+ 41B7A2D2208F900200EBA53E /* Debug */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ CLANG_ANALYZER_NONNULL = YES;
+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
+ CLANG_CXX_LIBRARY = "libc++";
+ CLANG_ENABLE_MODULES = YES;
+ CLANG_ENABLE_OBJC_ARC = YES;
+ CLANG_ENABLE_OBJC_WEAK = YES;
+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
+ CLANG_WARN_BOOL_CONVERSION = YES;
+ CLANG_WARN_COMMA = YES;
+ CLANG_WARN_CONSTANT_CONVERSION = YES;
+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
+ CLANG_WARN_EMPTY_BODY = YES;
+ CLANG_WARN_ENUM_CONVERSION = YES;
+ CLANG_WARN_INFINITE_RECURSION = YES;
+ CLANG_WARN_INT_CONVERSION = YES;
+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
+ CLANG_WARN_STRICT_PROTOTYPES = YES;
+ CLANG_WARN_SUSPICIOUS_MOVE = YES;
+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
+ CLANG_WARN_UNREACHABLE_CODE = YES;
+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
+ CODE_SIGN_IDENTITY = "iPhone Developer";
+ COPY_PHASE_STRIP = NO;
+ DEBUG_INFORMATION_FORMAT = dwarf;
+ ENABLE_BITCODE = NO;
+ ENABLE_STRICT_OBJC_MSGSEND = YES;
+ ENABLE_TESTABILITY = YES;
+ GCC_C_LANGUAGE_STANDARD = gnu11;
+ GCC_DYNAMIC_NO_PIC = NO;
+ GCC_NO_COMMON_BLOCKS = YES;
+ GCC_OPTIMIZATION_LEVEL = 0;
+ GCC_PREPROCESSOR_DEFINITIONS = (
+ "DEBUG=1",
+ "$(inherited)",
+ );
+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
+ GCC_WARN_UNDECLARED_SELECTOR = YES;
+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
+ GCC_WARN_UNUSED_FUNCTION = YES;
+ GCC_WARN_UNUSED_VARIABLE = YES;
+ IPHONEOS_DEPLOYMENT_TARGET = 9.3;
+ MTL_ENABLE_DEBUG_INFO = YES;
+ ONLY_ACTIVE_ARCH = YES;
+ SDKROOT = iphoneos;
+ };
+ name = Debug;
+ };
+ 41B7A2D3208F900200EBA53E /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ CLANG_ANALYZER_NONNULL = YES;
+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
+ CLANG_CXX_LIBRARY = "libc++";
+ CLANG_ENABLE_MODULES = YES;
+ CLANG_ENABLE_OBJC_ARC = YES;
+ CLANG_ENABLE_OBJC_WEAK = YES;
+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
+ CLANG_WARN_BOOL_CONVERSION = YES;
+ CLANG_WARN_COMMA = YES;
+ CLANG_WARN_CONSTANT_CONVERSION = YES;
+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
+ CLANG_WARN_EMPTY_BODY = YES;
+ CLANG_WARN_ENUM_CONVERSION = YES;
+ CLANG_WARN_INFINITE_RECURSION = YES;
+ CLANG_WARN_INT_CONVERSION = YES;
+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
+ CLANG_WARN_STRICT_PROTOTYPES = YES;
+ CLANG_WARN_SUSPICIOUS_MOVE = YES;
+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
+ CLANG_WARN_UNREACHABLE_CODE = YES;
+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
+ CODE_SIGN_IDENTITY = "iPhone Developer";
+ COPY_PHASE_STRIP = NO;
+ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+ ENABLE_BITCODE = NO;
+ ENABLE_NS_ASSERTIONS = NO;
+ ENABLE_STRICT_OBJC_MSGSEND = YES;
+ GCC_C_LANGUAGE_STANDARD = gnu11;
+ GCC_NO_COMMON_BLOCKS = YES;
+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
+ GCC_WARN_UNDECLARED_SELECTOR = YES;
+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
+ GCC_WARN_UNUSED_FUNCTION = YES;
+ GCC_WARN_UNUSED_VARIABLE = YES;
+ IPHONEOS_DEPLOYMENT_TARGET = 9.3;
+ MTL_ENABLE_DEBUG_INFO = NO;
+ SDKROOT = iphoneos;
+ VALIDATE_PRODUCT = YES;
+ };
+ name = Release;
+ };
+ 41B7A2D5208F900200EBA53E /* Debug */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+ CODE_SIGN_IDENTITY = "iPhone Developer";
+ CODE_SIGN_STYLE = Automatic;
+ DEVELOPMENT_TEAM = "";
+ FRAMEWORK_SEARCH_PATHS = (
+ "$(inherited)",
+ "$(PROJECT_DIR)",
+ );
+ INFOPLIST_FILE = NearbyConnectionsExample/Info.plist;
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/Frameworks",
+ );
+ PRODUCT_BUNDLE_IDENTIFIER = com.google.NearbyConnectionsExample;
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ PROVISIONING_PROFILE = "";
+ PROVISIONING_PROFILE_SPECIFIER = "";
+ TARGETED_DEVICE_FAMILY = "1,2";
+ };
+ name = Debug;
+ };
+ 41B7A2D6208F900200EBA53E /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+ CODE_SIGN_IDENTITY = "iPhone Developer";
+ CODE_SIGN_STYLE = Automatic;
+ DEVELOPMENT_TEAM = "";
+ FRAMEWORK_SEARCH_PATHS = (
+ "$(inherited)",
+ "$(PROJECT_DIR)",
+ );
+ INFOPLIST_FILE = NearbyConnectionsExample/Info.plist;
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/Frameworks",
+ );
+ PRODUCT_BUNDLE_IDENTIFIER = com.google.NearbyConnectionsExample;
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ PROVISIONING_PROFILE_SPECIFIER = "";
+ TARGETED_DEVICE_FAMILY = "1,2";
+ };
+ name = Release;
+ };
+/* End XCBuildConfiguration section */
+
+/* Begin XCConfigurationList section */
+ 41B7A2B9208F900000EBA53E /* Build configuration list for PBXProject "NearbyConnectionsExample" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ 41B7A2D2208F900200EBA53E /* Debug */,
+ 41B7A2D3208F900200EBA53E /* Release */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Release;
+ };
+ 41B7A2D4208F900200EBA53E /* Build configuration list for PBXNativeTarget "NearbyConnectionsExample" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ 41B7A2D5208F900200EBA53E /* Debug */,
+ 41B7A2D6208F900200EBA53E /* Release */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Release;
+ };
+/* End XCConfigurationList section */
+ };
+ rootObject = 41B7A2B6208F900000EBA53E /* Project object */;
+}
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/AppDelegate.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/AppDelegate.h
new file mode 100644
index 00000000000..c1b1202cdf0
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/AppDelegate.h
@@ -0,0 +1,34 @@
+//
+// Copyright (c) 2021 Google Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+// AppDelegate.h
+// NearbyConnectionsExample
+//
+
+#import <UIKit/UIKit.h>
+
+/**
+ * A delegate for NSApplication to handle notifications about app launch and
+ * shutdown. Owned by the application object.
+ */
+@interface AppDelegate : UIResponder <UIApplicationDelegate>
+
+/**
+ * Main screen window displayed to the user which contains any active view
+ * hierarchy.
+ */
+@property(nonatomic) UIWindow *window;
+
+@end
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/AppDelegate.m b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/AppDelegate.m
new file mode 100644
index 00000000000..69022507528
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/AppDelegate.m
@@ -0,0 +1,23 @@
+//
+// Copyright (c) 2021 Google Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+// AppDelegate.m
+// NearbyConnectionsExample
+//
+
+#import "AppDelegate.h"
+
+@implementation AppDelegate
+@end
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/Assets.xcassets/AppIcon.appiconset/Contents.json b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/Assets.xcassets/AppIcon.appiconset/Contents.json
new file mode 100644
index 00000000000..d8db8d65fd7
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/Assets.xcassets/AppIcon.appiconset/Contents.json
@@ -0,0 +1,98 @@
+{
+ "images" : [
+ {
+ "idiom" : "iphone",
+ "size" : "20x20",
+ "scale" : "2x"
+ },
+ {
+ "idiom" : "iphone",
+ "size" : "20x20",
+ "scale" : "3x"
+ },
+ {
+ "idiom" : "iphone",
+ "size" : "29x29",
+ "scale" : "2x"
+ },
+ {
+ "idiom" : "iphone",
+ "size" : "29x29",
+ "scale" : "3x"
+ },
+ {
+ "idiom" : "iphone",
+ "size" : "40x40",
+ "scale" : "2x"
+ },
+ {
+ "idiom" : "iphone",
+ "size" : "40x40",
+ "scale" : "3x"
+ },
+ {
+ "idiom" : "iphone",
+ "size" : "60x60",
+ "scale" : "2x"
+ },
+ {
+ "idiom" : "iphone",
+ "size" : "60x60",
+ "scale" : "3x"
+ },
+ {
+ "idiom" : "ipad",
+ "size" : "20x20",
+ "scale" : "1x"
+ },
+ {
+ "idiom" : "ipad",
+ "size" : "20x20",
+ "scale" : "2x"
+ },
+ {
+ "idiom" : "ipad",
+ "size" : "29x29",
+ "scale" : "1x"
+ },
+ {
+ "idiom" : "ipad",
+ "size" : "29x29",
+ "scale" : "2x"
+ },
+ {
+ "idiom" : "ipad",
+ "size" : "40x40",
+ "scale" : "1x"
+ },
+ {
+ "idiom" : "ipad",
+ "size" : "40x40",
+ "scale" : "2x"
+ },
+ {
+ "idiom" : "ipad",
+ "size" : "76x76",
+ "scale" : "1x"
+ },
+ {
+ "idiom" : "ipad",
+ "size" : "76x76",
+ "scale" : "2x"
+ },
+ {
+ "idiom" : "ipad",
+ "size" : "83.5x83.5",
+ "scale" : "2x"
+ },
+ {
+ "idiom" : "ios-marketing",
+ "size" : "1024x1024",
+ "scale" : "1x"
+ }
+ ],
+ "info" : {
+ "version" : 1,
+ "author" : "xcode"
+ }
+} \ No newline at end of file
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/Assets.xcassets/Contents.json b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/Assets.xcassets/Contents.json
new file mode 100644
index 00000000000..da4a164c918
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/Assets.xcassets/Contents.json
@@ -0,0 +1,6 @@
+{
+ "info" : {
+ "version" : 1,
+ "author" : "xcode"
+ }
+} \ No newline at end of file
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/Base.lproj/LaunchScreen.storyboard b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/Base.lproj/LaunchScreen.storyboard
new file mode 100644
index 00000000000..f83f6fd5810
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/Base.lproj/LaunchScreen.storyboard
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" systemVersion="17A277" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
+ <dependencies>
+ <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/>
+ <capability name="Safe area layout guides" minToolsVersion="9.0"/>
+ <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
+ </dependencies>
+ <scenes>
+ <!--View Controller-->
+ <scene sceneID="EHf-IW-A2E">
+ <objects>
+ <viewController id="01J-lp-oVM" sceneMemberID="viewController">
+ <view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
+ <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
+ <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
+ <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
+ <viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
+ </view>
+ </viewController>
+ <placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
+ </objects>
+ <point key="canvasLocation" x="53" y="375"/>
+ </scene>
+ </scenes>
+</document>
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/Base.lproj/Main.storyboard b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/Base.lproj/Main.storyboard
new file mode 100644
index 00000000000..b39e95c8009
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/Base.lproj/Main.storyboard
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14113" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="fos-Uz-R9B">
+ <device id="retina4_7" orientation="portrait">
+ <adaptation id="fullscreen"/>
+ </device>
+ <dependencies>
+ <deployment identifier="iOS"/>
+ <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14088"/>
+ <capability name="Safe area layout guides" minToolsVersion="9.0"/>
+ <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
+ </dependencies>
+ <scenes>
+ <!--View Controller-->
+ <scene sceneID="BVh-fg-s4x">
+ <objects>
+ <viewController id="Tuj-3T-cB2" customClass="ViewController" sceneMemberID="viewController">
+ <view key="view" contentMode="scaleToFill" id="9NC-2J-1xS">
+ <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
+ <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
+ <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
+ <viewLayoutGuide key="safeArea" id="wwJ-gb-kZn"/>
+ </view>
+ <navigationItem key="navigationItem" id="ega-4i-ebx"/>
+ </viewController>
+ <placeholder placeholderIdentifier="IBFirstResponder" id="xJQ-q8-wWg" userLabel="First Responder" sceneMemberID="firstResponder"/>
+ </objects>
+ <point key="canvasLocation" x="433" y="-133"/>
+ </scene>
+ <!--Navigation Controller-->
+ <scene sceneID="Jcj-tp-czJ">
+ <objects>
+ <navigationController id="fos-Uz-R9B" sceneMemberID="viewController">
+ <navigationBar key="navigationBar" contentMode="scaleToFill" insetsLayoutMarginsFromSafeArea="NO" id="x6x-US-muI">
+ <rect key="frame" x="0.0" y="20" width="375" height="44"/>
+ <autoresizingMask key="autoresizingMask"/>
+ </navigationBar>
+ <connections>
+ <segue destination="Tuj-3T-cB2" kind="relationship" relationship="rootViewController" id="Xa2-HD-mUn"/>
+ </connections>
+ </navigationController>
+ <placeholder placeholderIdentifier="IBFirstResponder" id="99I-fh-ObP" userLabel="First Responder" sceneMemberID="firstResponder"/>
+ </objects>
+ <point key="canvasLocation" x="-455" y="-132"/>
+ </scene>
+ </scenes>
+</document>
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/Info.plist b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/Info.plist
new file mode 100644
index 00000000000..44aa9d70a41
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/Info.plist
@@ -0,0 +1,51 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>$(DEVELOPMENT_LANGUAGE)</string>
+ <key>CFBundleExecutable</key>
+ <string>$(EXECUTABLE_NAME)</string>
+ <key>CFBundleIdentifier</key>
+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>$(PRODUCT_NAME)</string>
+ <key>CFBundlePackageType</key>
+ <string>APPL</string>
+ <key>CFBundleShortVersionString</key>
+ <string>1.0</string>
+ <key>CFBundleVersion</key>
+ <string>1</string>
+ <key>LSRequiresIPhoneOS</key>
+ <true/>
+ <key>UILaunchStoryboardName</key>
+ <string>LaunchScreen</string>
+ <key>UIMainStoryboardFile</key>
+ <string>Main</string>
+ <key>UIRequiredDeviceCapabilities</key>
+ <array>
+ <string>armv7</string>
+ </array>
+ <key>UISupportedInterfaceOrientations</key>
+ <array>
+ <string>UIInterfaceOrientationPortrait</string>
+ <string>UIInterfaceOrientationLandscapeLeft</string>
+ <string>UIInterfaceOrientationLandscapeRight</string>
+ </array>
+ <key>UISupportedInterfaceOrientations~ipad</key>
+ <array>
+ <string>UIInterfaceOrientationPortrait</string>
+ <string>UIInterfaceOrientationPortraitUpsideDown</string>
+ <string>UIInterfaceOrientationLandscapeLeft</string>
+ <string>UIInterfaceOrientationLandscapeRight</string>
+ </array>
+ <key>NSLocalNetworkUsageDescription</key>
+ <string>Exchange data with nearby devices running the NearbyConnectionsExmaple app.</string>
+ <key>NSBonjourServices</key>
+ <array>
+ <string>_54167B379724._tcp</string>
+ </array>
+</dict>
+</plist>
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/ViewController.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/ViewController.h
new file mode 100644
index 00000000000..599609942ca
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/ViewController.h
@@ -0,0 +1,24 @@
+//
+// Copyright (c) 2021 Google Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+// ViewController.h
+// NearbyConnectionsExample
+//
+
+#import <UIKit/UIKit.h>
+
+/** View controller for demo by loading NearbyConnections lib for advertiser and discoverer. */
+@interface ViewController : UIViewController
+@end
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/ViewController.m b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/ViewController.m
new file mode 100644
index 00000000000..f6c8b82aa52
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/ViewController.m
@@ -0,0 +1,291 @@
+//
+// Copyright (c) 2021 Google Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+// ViewController.m
+// NearbyConnectionsExample
+//
+
+#import "ViewController.h"
+
+#import <NearbyConnections/NearbyConnections.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+static NSString *kServiceId = @"com.google.NearbyConnectionsExample";
+static NSString *kCellIdentifier = @"endpointCell";
+
+// Simplified version of dispatch_after.
+void delay(NSTimeInterval delay, dispatch_block_t block) {
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)),
+ dispatch_get_main_queue(), block);
+}
+
+// This class contains info about a discovered endpoint.
+@interface EndpointInfo : NSObject
+@property(nonatomic, readonly) id<GNCDiscoveredEndpointInfo> discInfo;
+@property(nonatomic, nullable) id<GNCConnection> connection;
+@end
+
+@implementation EndpointInfo
+- (instancetype)initWithDiscoveredInfo:(id<GNCDiscoveredEndpointInfo>)discInfo {
+ self = [super init];
+ if (self) {
+ _discInfo = discInfo;
+ }
+ return self;
+}
+@end
+
+@interface ViewController () <UITableViewDataSource, UITableViewDelegate>
+@property(nonatomic) GNCAdvertiser *advertiser;
+@property(nonatomic) GNCDiscoverer *discoverer;
+@property(nonatomic) NSMutableDictionary<GNCEndpointId, EndpointInfo *> *endpoints;
+@property(nonatomic, readonly) NSData *ping;
+@property(nonatomic, readonly) NSData *pong;
+@property(nonatomic) UITableView *tableView;
+@property(nonatomic) UITextView *statusView;
+@property(nonatomic) NSMutableDictionary<GNCEndpointId, id<GNCConnection> > *incomingConnections;
+@end
+
+@implementation ViewController
+
+- (void)viewDidLoad {
+ [super viewDidLoad];
+ [self makeViews];
+
+ // Enable "info" log messages in the release build.
+ [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"GTMVerboseLogging"];
+
+ self.title = [[UIDevice currentDevice] name];
+ NSData *endpointInfo = [self.title dataUsingEncoding:NSUTF8StringEncoding];
+ _endpoints = [NSMutableDictionary dictionary];
+ _ping = [@"ping" dataUsingEncoding:NSUTF8StringEncoding];
+ _pong = [@"pong" dataUsingEncoding:NSUTF8StringEncoding];
+ _incomingConnections = [NSMutableDictionary dictionary];
+
+ // The advertiser.
+ _advertiser = [GNCAdvertiser
+ advertiserWithEndpointInfo:endpointInfo
+ serviceId:kServiceId
+ strategy:GNCStrategyCluster
+ connectionInitiationHandler:^(GNCEndpointId endpointId,
+ id<GNCAdvertiserConnectionInfo> advConnInfo,
+ GNCConnectionResponseHandler responseHandler) {
+ // Show a status that a discoverer has requested a connection.
+ [self logStatus:@"Accepting connection request" final:NO];
+
+ // Accept the connection request.
+ responseHandler(GNCConnectionResponseAccept);
+ return [GNCConnectionResultHandlers
+ successHandler:^(id<GNCConnection> connection) {
+ // Save the connection until the ping-pong sequence is done.
+ self.incomingConnections[endpointId] = connection;
+ __block BOOL receivedPong = NO;
+
+ // Send a ping, expecting the remote endpoint to send a pong.
+ [self logStatus:@"Connection established; sending ping" final:NO];
+ [connection sendBytesPayload:[GNCBytesPayload payloadWithBytes:self.ping]
+ completion:^(GNCPayloadResult result) {
+ if (result == GNCPayloadResultSuccess) {
+ [self logStatus:@"Sent ping; waiting for pong" final:NO];
+
+ // Show an error if the pong isn't received in the expected
+ // timeframe.
+ delay(3.0, ^{
+ if (receivedPong) {
+ [self logStatus:@"Error: Didn't receive pong" final:YES];
+ [self.incomingConnections
+ removeObjectForKey:endpointId]; // close the connection
+ }
+ });
+ } else {
+ [self logStatus:@"Error: Failed to send ping" final:YES];
+ }
+ }];
+
+ // Return handlers for incoming payloads.
+ return [GNCConnectionHandlers handlersWithBuilder:^(GNCConnectionHandlers *handlers) {
+ handlers.bytesPayloadHandler = ^(GNCBytesPayload *payload) {
+ receivedPong = NO;
+ [self.incomingConnections removeObjectForKey:endpointId]; // close the connection
+
+ // Show a status of whether the pong was received.
+ [self logStatus:[payload.bytes isEqual:self.pong] ? @"Received pong"
+ : @"Error: Payload is not pong"
+ final:YES];
+ };
+ }];
+ }
+ failureHandler:^(GNCConnectionFailure result) {
+ [self
+ logStatus:(result == GNCConnectionFailureRejected) ? @"Error: Connection rejected"
+ : @"Error: Connection failed"
+ final:YES];
+ }];
+ }];
+
+ // The discoverer.
+ __weak typeof(self) weakSelf = self;
+ _discoverer = [GNCDiscoverer
+ discovererWithServiceId:kServiceId
+ strategy:GNCStrategyCluster
+ endpointFoundHandler:^(GNCEndpointId endpointId,
+ id<GNCDiscoveredEndpointInfo> endpointInfo) {
+ typeof(self) self = weakSelf;
+
+ // An endpoint was discovered; add it to the endpoint list and UI.
+ self.endpoints[endpointId] = [[EndpointInfo alloc] initWithDiscoveredInfo:endpointInfo];
+ [self.tableView reloadData];
+
+ // Return the lost handler for this endpoint.
+ return ^{
+ typeof(self) self = weakSelf; // shadow
+
+ // Endpoint disappeared; remove it from the endpoint list and UI.
+ [self.endpoints removeObjectForKey:endpointId];
+ [self.tableView reloadData];
+ };
+ }];
+}
+
+#pragma mark - UITableViewDelegate
+
+- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
+ // The user tapped on a cell; request a connection with it.
+ EndpointInfo *info = _endpoints[_endpoints.allKeys[indexPath.row]];
+ if (!info) return;
+
+ void (^deselectRow)(void) = ^{
+ [tableView deselectRowAtIndexPath:indexPath animated:YES];
+ };
+
+ [self logStatus:@"Requesting connection" final:NO];
+ info.discInfo.requestConnection(
+ self.title,
+ ^(id<GNCDiscovererConnectionInfo> discConnInfo,
+ GNCConnectionResponseHandler responseHandler) {
+ // Accept the auth token.
+ [self logStatus:@"Accepting auth token" final:NO];
+ responseHandler(GNCConnectionResponseAccept);
+ return ^(id<GNCConnection> connection) {
+ // Save the connection until the ping-pong sequence is done.
+ info.connection = connection;
+ __block BOOL receivedPing = NO;
+
+ [self logStatus:@"Connection established; waiting for ping" final:NO];
+
+ // Show an error if the ping isn't received in the expected timeframe.
+ delay(3.0, ^{
+ if (!receivedPing) {
+ deselectRow();
+ [self logStatus:@"Error: Didn't receive ping" final:YES];
+ info.connection = nil; // close the connection
+ }
+ });
+
+ // Return handlers for incoming payloads.
+ __weak id<GNCConnection> weakConnection = connection; // avoid a retain cycle
+ return [GNCConnectionHandlers handlersWithBuilder:^(GNCConnectionHandlers *handlers) {
+ handlers.bytesPayloadHandler = ^(GNCBytesPayload *payload) {
+ receivedPing = YES;
+
+ // If a ping was received, send a pong back to the advertiser.
+ if ([payload.bytes isEqual:self.ping]) {
+ [self logStatus:@"Received ping; sending pong" final:NO];
+ [weakConnection sendBytesPayload:[GNCBytesPayload payloadWithBytes:self.pong]
+ completion:^(GNCPayloadResult result) {
+ deselectRow();
+ [self logStatus:(result == GNCPayloadResultSuccess)
+ ? @"Sent pong"
+ : @"Error: Failed to send pong"
+ final:YES];
+
+ // Pong was sent, so close the connection.
+ info.connection = nil;
+ }];
+ } else {
+ deselectRow();
+ [self logStatus:@"Error: Payload is not ping" final:YES];
+ }
+ };
+ }];
+ };
+ },
+ ^(GNCConnectionFailure result) {
+ // Connection failed.
+ deselectRow();
+ [self logStatus:(result == GNCConnectionFailureRejected) ? @"Connection rejected"
+ : @"Connection failed"
+ final:YES];
+ });
+}
+
+- (UITableViewCell *)tableView:(UITableView *)tableView
+ cellForRowAtIndexPath:(NSIndexPath *)indexPath {
+ UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier
+ forIndexPath:indexPath];
+ cell.textLabel.text = _endpoints[_endpoints.allKeys[indexPath.row]].discInfo.name;
+ return cell;
+}
+
+#pragma mark - UITableViewDataSource
+
+- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
+ return [_endpoints.allKeys count];
+}
+
+#pragma mark - Private
+
+- (void)makeViews {
+ _tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
+ [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kCellIdentifier];
+ _tableView.delegate = self;
+ _tableView.dataSource = self;
+ _tableView.rowHeight = 48;
+ _tableView.scrollEnabled = YES;
+ _tableView.showsVerticalScrollIndicator = YES;
+ _tableView.userInteractionEnabled = YES;
+ _tableView.bounces = YES;
+ _tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
+ [self.view addSubview:_tableView];
+
+ // Make the status view.
+ UITextView * (^newTextView)(CGRect) = ^(CGRect frame) {
+ UITextView *textView = [[UITextView alloc] initWithFrame:frame];
+ textView.autoresizingMask =
+ UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
+ textView.layer.borderColor = [UIColor blackColor].CGColor;
+ textView.layer.borderWidth = 1;
+ textView.editable = NO;
+ textView.textContainerInset = UIEdgeInsetsZero;
+ return textView;
+ };
+ CGRect selfFrame = self.view.frame;
+ static const int kStatusHeight = 144;
+ CGRect statusFrame = (CGRect){{selfFrame.origin.x + 4, selfFrame.size.height - kStatusHeight},
+ {selfFrame.size.width - 8, kStatusHeight - 4}};
+ _statusView = newTextView(statusFrame);
+ [self.view addSubview:_statusView];
+}
+
+- (void)logStatus:(NSString *)status final:(BOOL)final {
+ _statusView.text = [NSString stringWithFormat:@"%@\n%@%@", _statusView.text, status,
+ final ? @"\n–––––––––––––––––––––––––" : @""];
+ [_statusView scrollRangeToVisible:NSMakeRange(_statusView.text.length - 1, 1)];
+}
+
+@end
+
+NS_ASSUME_NONNULL_END
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/main.m b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/main.m
new file mode 100644
index 00000000000..3111188ca69
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/NearbyConnectionsExample/main.m
@@ -0,0 +1,27 @@
+//
+// Copyright (c) 2021 Google Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+// main.m
+// NearbyConnectionsExample
+//
+
+#import <UIKit/UIKit.h>
+#import "AppDelegate.h"
+
+int main(int argc, char * argv[]) {
+ @autoreleasepool {
+ return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
+ }
+}
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/README.md b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/README.md
new file mode 100755
index 00000000000..bf98df6070b
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/README.md
@@ -0,0 +1,198 @@
+# Nearby Connections Sample App for iOS
+
+This is a sample app for third party developers using the Nearby Connections
+library. On startup, it advertises and discovers. Discovered advertisers are
+added to the list in the UI. When the user taps on an advertiser in the list,
+the discoverer requests a connection with it. When the connection is
+established, the advertiser sends a "ping" payload to the discoverer, which
+sends "pong" payload back to the advertiser. The connection is then closed.
+
+## Setup
+
+1.Get the NearbyConnections_framework.zip from https://github.com/google/nearby/releases/tag/v0.0.1-ios, unzip it,
+and put your unzipped folder under your project folder. The directory structure
+looks like:
+
+```
+/NearbyConnectionsExample
+ /NearbyConnectionsExample
+ NearbyConnectionsExample.xcodeproj
+ README.md
+ /NearbyConnections.framework
+```
+
+2.Import NearbyConnections.framework
+
+- In Xcode, click the NearbyConnectionsExample in the left pane. And click the one in TARGETS-NearbyConnectionsExample at the left of right pane and the Build Phases at the right.
+- See the **Link Binary With Libraries**, and press **+** to import the file - **libc++.tbd**.
+- In Add **Other…**, import the NearbyConnections.framework folder which was unzipped.
+
+![Import framework in Xcode](./XcodeSetup.png)
+
+3.Update info.plist:
+
+- add **NSLocalNetworkUsageDescription** key with a description of your usage of Nearby Connections.
+- add **NSBonjourServices** key.
+ for NSBonjourServices key, add the bonjour type name: `_54167B379724._tcp`
+
+> **54167B379724** is the 6 byte hash of service id **com.google.NearbyConnectionsExample**
+
+```
+// NearbyConnectionsExample/info.plist
+...
+<key>NSLocalNetworkUsageDescription</key>
+<string>Exchange data with nearby devices running the NearbyConnectionsExmaple app.</string>
+<key>NSBonjourServices</key>
+<array>
+ <string>_54167B379724._tcp</string>
+</array>
+...
+```
+
+
+4.Add service id and import `<NearbyConnections/NearbyConnections.h>` in your main view controller.
+
+```
+// NearbyConnectionsExample/ViewController.m
+
+static NSString *kServiceId = @"com.google.NearbyConnectionsExample";
+
+#import <NearbyConnections/NearbyConnections.h>
+```
+
+## Code Snippets
+Note: All of the callbacks in this library use blocks rather than delegates. Be careful to avoid retain cycles in your block implementations. See the [Apple documentation](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html#//apple_ref/doc/uid/TP40004447-SW1) describing how to avoid retain cycles.
+
+Here is the skeleton code for an advertiser:
+
+```objc
+_advertiser = [GNCAdvertiser
+ advertiserWithEndpointInfo:endpointInfo
+ serviceId:myServiceId
+ strategy:GNCStrategyCluster
+ connectionInitiationHandler:^(GNCEndpointId endpointId,
+ id<GNCAdvertiserConnectionInfo> connectionInfo,
+ GNCConnectionResponseHandler responseHandler) {
+ // Decide whether to accept or reject the connection. The following code would normally
+ // exist in the callback for an alert, for instance.
+ if (/* user rejected */) {
+ responseHandler(GNCConnectionResponseReject); // the user rejected the invitation
+ } else {
+ responseHandler(GNCConnectionResponseAccept); // the user accepted the invitation
+
+ // Return connection result handlers, one of which is called depending on
+ // whether a successful connection was made.
+ return [GNCConnectionResultHandlers successHandler:^(id<GNCConnection> connection) {
+ // A successful connection was made. Save the connection somewhere, which can
+ // be used to send payloads to the remote endpoint.
+
+ // Return the incoming payload and disconnect handlers.
+ return [GNCConnectionHandlers handlersWithBuilder:^(GNCConnectionHandlers *handlers) {
+ // Optionally set the Bytes payload handler.
+ handlers.bytesPayloadHandler = ^(GNCBytesPayload *payload) {
+ // Process the payload received from the remote endpoint.
+ };
+
+ // Optionally set the Stream payload handler.
+ handlers.streamPayloadHandler = ^(GNCStreamPayload *payload, NSProgress *progress) {
+ // Receipt of a Stream payload has started. Input can be read from the payload’s
+ // NSInputStream, and progress/cancellation is handled via the NSProgress object.
+ return ^(GNCPayloadResult result) {
+ if (result == GNCPayloadResultSuccess) {
+ // The payload has been successfully received.
+ }
+ };
+ };
+
+ // Optionally set the disconnected handler.
+ handlers.disconnectedHandler = ^(GNCDisconnectedReason reason) {
+ // The connection was severed by either endpoint or lost.
+ };
+ }
+ failureHandler:^(GNCConnectionFailure result) {
+ // Failed to make the connection.
+ }]);
+ }
+}];
+```
+
+Here is the skeleton code for a discoverer:
+
+```objc
+_discoverer =
+ [GNCDiscoverer discovererWithServiceId:myServiceId
+ strategy:GNCStrategyCluster
+ endpointFoundHandler:^(GNCEndpointId endpointId,
+ id<GNCDiscoveredEndpointInfo> discEndpointInfo) {
+ // An endpoint was found. Typically you would add it to a list of nearby endpoints
+ // displayed in a UITableView, for instance.
+
+ // The following code shows how to request a connection with the endpoint. This code
+ // would normally exist in the -didSelectRowAtIndexPath: of UITableViewDelegate.
+ if (/* user wants to request a connection */) {
+ requestHandler(myName,
+ // This block is called once an authentication string is generated between the endpoints.
+ ^(id<GNCDiscovererConnectionInfo> discConnInfo, GNCConnectionResponseHandler responseHandler) {
+ // Ask the user to confirm the authentication string.
+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Accept auth?" ...];
+ [alert addAction:[UIAlertAction actionWithTitle:@"OK"
+ style:UIAlertActionStyleDefault
+ handler:^(UIAlertAction *action) {
+ responseHandler(GNCConnectionResponseAccept);
+ }]];
+ [alert addAction:[UIAlertAction actionWithTitle:@"Cancel"
+ style:UIAlertActionStyleDefault
+ handler:^(UIAlertAction *action) {
+ responseHandler(GNCConnectionResponseReject);
+ }]];
+ [self presentViewController:alert animated:YES completion:^{}];
+
+ // Return a block that's called if the connection was successful.
+ return ^(id<GNCConnection> connection) {
+ // A successful connection was made. Save the connection somewhere, which can
+ // be used to send payloads to the remote endpoint.
+
+ // Return incoming data handlers as in the advertiser example above.
+ return [GNCConnectionHandlers handlersWithBuilder:^(GNCConnectionHandlers *handlers) {
+ // Set up payload and disconnect handlers here as in the advertiser example above.
+ }];
+ };
+ },
+ // This block is called if the connection failed for any reason.
+ ^(GNCConnectionFailure result) {
+ // Typically an alert would be shown here explaining why the connection failed.
+ });
+ }
+
+ // Return the endpoint-lost handler, which is called when the endpoint goes out of range
+ // or stops advertising.
+ return ^{
+ // The endpoint disappeared.
+ };
+}];
+```
+
+Here is an example of how to send a Bytes payload. The returned NSProgress object can be passed to UIProgressView to display a progress bar.
+
+```objc
+NSProgress *progress = [connection
+ sendBytesPayload:[GNCBytesPayload payloadWithBytes:someData]
+ completion:^(GNCPayloadResult result) {
+ // Check status to see if it was successfully sent.
+ }];
+```
+
+## Build and run
+
+![Sucessful running screenshot](./NearbyConnectionsExample.png)
+
+If you meet the following error in the debug panel of Xcode, you likely need to set up the keys listed in step 3 **Update info.plist**, as well as the service type.
+
+```
+1970-01-01 00:00:00.000 NearbyConnectionsExample[1383/0x16d87b000] [lvl=1] -[GNCMBonjourService netService:didNotPublish:] Error publishing: service: <NSNetService 0x283a18920> local _307BEAB11028._tcp. IjFQWEUwe-oAAA 51898, errorDic: {
+ NSNetServicesErrorCode = "-72008";
+ NSNetServicesErrorDomain = 10;
+}
+```
+---
+NOTE: The iOS simulator is unstable when advertising. We recommend using an real iOS device.
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/XcodeSetup.png b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/XcodeSetup.png
new file mode 100644
index 00000000000..4f353ffeaec
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Example/NearbyConnectionsExample/XcodeSetup.png
Binary files differ
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/GNCAdvertiser.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/GNCAdvertiser.h
new file mode 100644
index 00000000000..03272bb646d
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/GNCAdvertiser.h
@@ -0,0 +1,84 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import <Foundation/Foundation.h>
+
+#import "GNCConnection.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+/** This contains info about a discoverer endpoint intitiating a connection with an advertiser. */
+@protocol GNCAdvertiserConnectionInfo <NSObject>
+/** This is a human readable name of the discoverer. */
+@property(nonatomic, readonly, copy) NSString *name;
+/** This token can be used to verify the identity of the discoverer. */
+@property(nonatomic, readonly, copy) NSString *authToken;
+@end
+
+/** This class contains success and failure handlers for the connection request. */
+@interface GNCConnectionResultHandlers : NSObject
+
+/**
+ * This factory method creates a pair of handlers for a successful or failed connection.
+ *
+ * @param successHandler This handler is called if both endpoints accept the connection.
+ * A @c GNCConnection object is passed, meaning that the connection has
+ * been established and you may start sending and receiving payloads.
+ * @param failureHandler This handler is called if either endpoint rejects the connection.
+ */
++ (instancetype)successHandler:(GNCConnectionHandler)successHandler
+ failureHandler:(GNCConnectionFailureHandler)failureHandler;
+
+@end
+
+/**
+ * This handler is called when a discoverer requests a connection with an advertiser. In
+ * response, the advertiser should accept or reject via @c responseHandler.
+ *
+ * @param endpointId The ID of the endpoint.
+ * @param connectionInfo Information about the discoverer.
+ * @param responseHandler Handler for the connection response, which is either an acceptance or
+ * rejection of the connection request.
+ * @return Handlers for the final connection result. This will be called as soon as the final
+ * connection result is known, when either side rejects or both sides accept.
+ */
+typedef GNCConnectionResultHandlers *_Nonnull (^GNCAdvertiserConnectionInitiationHandler)(
+ GNCEndpointId endpointId, id<GNCAdvertiserConnectionInfo> connectionInfo,
+ GNCConnectionResponseHandler responseHandler);
+
+/**
+ * An advertiser broadcasts a service that can be seen by discoverers, which can then make
+ * requests to connect to it. Release the advertiser object to stop advertising.
+ */
+@interface GNCAdvertiser : NSObject
+
+/**
+ * Factory method that creates an advertiser.
+ *
+ * @param endpointInfo A data for endpoint info which contains readable name of this endpoint,
+ * to be displayed on other endpoints.
+ * @param serviceId A string that uniquely identifies the advertised service.
+ * @param strategy The connection topology to use.
+ * @param connectionInitiationHandler A handler that is called when a discoverer requests a
+ * connection with this endpoint.
+ */
++ (instancetype)advertiserWithEndpointInfo:(NSData *)endpointInfo
+ serviceId:(NSString *)serviceId
+ strategy:(GNCStrategy)strategy
+ connectionInitiationHandler:
+ (GNCAdvertiserConnectionInitiationHandler)connectionInitiationHandler;
+
+@end
+
+NS_ASSUME_NONNULL_END
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/GNCConnection.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/GNCConnection.h
new file mode 100644
index 00000000000..85efca47ce5
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/GNCConnection.h
@@ -0,0 +1,167 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import <Foundation/Foundation.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+@class GNCBytesPayload, GNCStreamPayload, GNCFilePayload;
+
+/** Response to a connection request. */
+typedef NS_ENUM(NSInteger, GNCConnectionResponse) {
+ GNCConnectionResponseReject, // reject the connection request
+ GNCConnectionResponseAccept, // accept the connection request
+};
+
+/** Reason for a failed connection request. */
+typedef NS_ENUM(NSInteger, GNCConnectionFailure) {
+ GNCConnectionFailureRejected, // an endpoint rejected the connection request
+ GNCConnectionFailureUnknown, // there was an error while attempting to make the connection
+};
+
+/** Handler for a @c GNCConnectionFailure value. */
+typedef void (^GNCConnectionFailureHandler)(GNCConnectionFailure);
+
+/** Reasons that a connection can be severed by either endpoint. */
+typedef NS_ENUM(NSInteger, GNCDisconnectedReason) {
+ GNCDisconnectedReasonUnknown, // the endpoint can no longer be reached
+};
+
+/** Handler for a @c GNCDisconnectedReason value. */
+typedef void (^GNCDisconnectedHandler)(GNCDisconnectedReason);
+
+/** Result of a payload transfer. */
+typedef NS_ENUM(NSInteger, GNCPayloadResult) {
+ GNCPayloadResultSuccess, // Payload delivery was successful.
+ GNCPayloadResultFailure, // An error occurred during payload delivery.
+ GNCPayloadResultCanceled, // Payload delivery was canceled.
+};
+
+/** Handler for a @c GNCPayloadResult value. */
+typedef void (^GNCPayloadResultHandler)(GNCPayloadResult);
+
+/** Connection topology. See https://developers.google.com/nearby/connections/strategies. */
+typedef NS_ENUM(NSInteger, GNCStrategy) {
+ GNCStrategyCluster, // M-to-N
+ GNCStrategyStar, // 1-to-N
+ GNCStrategyPointToPoint, // 1-to-1
+};
+
+/** Every endpoint has a unique identifier. */
+typedef NSString *GNCEndpointId;
+
+/** This handler receives a Bytes payload. It is called when the payload data is fully received. */
+typedef void (^GNCBytesPayloadHandler)(GNCBytesPayload *payload);
+
+/**
+ * This handler receives a Stream payload, signifying the start of receipt of a stream. The payload
+ * data should be read from the supplied input stream. The progress object can be used to monitor
+ * progress or cancel the operation. This handler must return a completion handler, which is
+ * called when the operation is finished.
+ */
+typedef GNCPayloadResultHandler _Nonnull (^GNCStreamPayloadHandler)(GNCStreamPayload *payload,
+ NSProgress *progress);
+
+/**
+ * This handler receives a File payload, signifying the start of receipt of a file. The
+ * progress object can be used to monitor progress or cancel the operation. This handler must
+ * return a completion handler, which is called when the operation finishes successfully or if
+ * there is an error. The file will be stored in a temporary location. If an error occurs or the
+ * operation is canceled, the file will contain all data that was received. It is the client's
+ * responsibility to delete the file when it is no longer needed.
+ */
+typedef GNCPayloadResultHandler _Nonnull (^GNCFilePayloadHandler)(GNCFilePayload *payload,
+ NSProgress *progress);
+
+/** This class contains optional handlers for a connection. */
+@interface GNCConnectionHandlers : NSObject
+
+/**
+ * This handler receives Bytes payloads. It is optional; apps that don't send and receive Bytes
+ * payloads need not supply this handler.
+ */
+@property(nonatomic, nullable) GNCBytesPayloadHandler bytesPayloadHandler;
+
+/**
+ * This handler receives a stream that delivers a payload in chunks. It is optional; apps that
+ * don't send and receive Stream payloads need not supply this handler.
+ */
+@property(nonatomic, nullable) GNCStreamPayloadHandler streamPayloadHandler;
+
+/**
+ * This handler receives a File payload. It is optional; apps that don't send and receive File
+ * payloads need not supply this handler.
+ * Note: File payloads are not yet supported.
+ */
+@property(nonatomic, nullable) GNCFilePayloadHandler filePayloadHandler;
+
+/**
+ * This handler is called when the connection is ended, whether due to the endpoint disconnecting
+ * or moving out of range. It is optional.
+ */
+@property(nonatomic, nullable) GNCDisconnectedHandler disconnectedHandler;
+
+/**
+ * This factory method lets you specify a subset of the connection handlers in a single expression.
+ *
+ * @param builderBlock Set up the handlers in this block.
+ */
++ (instancetype)handlersWithBuilder:(void (^)(GNCConnectionHandlers *))builderBlock;
+
+@end
+
+/**
+ * This represents a connection with an endpoint. Use it to send payloads to the endpoint, and
+ * release it to disconnect.
+ */
+@protocol GNCConnection <NSObject>
+
+/**
+ * Send a Bytes payload. A progress object is returned, which can be used to monitor
+ * progress or cancel the operation. |completion| will be called when the operation completes
+ * (in all cases, even if failed or was canceled).
+ */
+- (NSProgress *)sendBytesPayload:(GNCBytesPayload *)payload
+ completion:(GNCPayloadResultHandler)completion;
+
+/**
+ * Send a Stream payload. A progress object is returned, which can be used to monitor
+ * progress or cancel the operation. The stream data is read from the supplied NSInputStream.
+ * |completion| will be called when the operation completes.
+ */
+- (NSProgress *)sendStreamPayload:(GNCStreamPayload *)payload
+ completion:(GNCPayloadResultHandler)completion;
+
+/**
+ * Send a File payload. A progress object is returned, which can be used to monitor progress or
+ * cancel the operation. |completion| will be called when the operation completes.
+ * Note: File payloads are not yet supported.
+ */
+- (NSProgress *)sendFilePayload:(GNCFilePayload *)payload
+ completion:(GNCPayloadResultHandler)completion;
+@end
+
+/**
+ * This handler takes a @c GNCConnection object and returns a @c GNCConnectionHandlers
+ * object containing the desired payload and connection-ended handlers.
+ */
+typedef GNCConnectionHandlers *_Nonnull (^GNCConnectionHandler)(id<GNCConnection> connection);
+
+/**
+ * This handler takes a response to a connection request. Pass @c GNCConnectionResponseAccept to
+ * accept the request and @c GNCConnectionResponseReject to reject it.
+ */
+typedef void (^GNCConnectionResponseHandler)(GNCConnectionResponse response);
+
+NS_ASSUME_NONNULL_END
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/GNCConnections.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/GNCConnections.h
new file mode 100644
index 00000000000..71c280b012c
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/GNCConnections.h
@@ -0,0 +1,20 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Umbrella header file for Nearby Connections library.
+
+#import "GNCAdvertiser.h"
+#import "GNCConnection.h"
+#import "GNCDiscoverer.h"
+#import "GNCPayload.h"
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/GNCDiscoverer.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/GNCDiscoverer.h
new file mode 100644
index 00000000000..f9afe835a3f
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/GNCDiscoverer.h
@@ -0,0 +1,95 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import <Foundation/Foundation.h>
+
+#import "GNCConnection.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+/** This is info about an advertiser endpoint with which the discoverer has requested a connection.
+ */
+@protocol GNCDiscovererConnectionInfo <NSObject>
+/** This token can be used to verify the identity of the advertiser. */
+@property(nonatomic, readonly, copy) NSString *authToken;
+@end
+
+/**
+ * This handler is called to establish authorization with the advertiser. In response,
+ * @c responseHandler should be called to accept or reject the connection.
+ *
+ * @param connectionInfo Information about the advertiser.
+ * @param responseHandler Handler for the connection response, which is either an acceptance or
+ * rejection of the connection request.
+ * @return Handler for the connection if it was successful.
+ */
+typedef GNCConnectionHandler _Nonnull (^GNCDiscovererConnectionInitializationHandler)(
+ id<GNCDiscovererConnectionInfo> connectionInfo, GNCConnectionResponseHandler responseHandler);
+
+/**
+ * This handler should be called to request a connection with an advertiser.
+ *
+ * @param endpointInfo A data for endpoint info which contains readable name of this endpoint,
+ * to be displayed on other endpoints.
+ * @param authorizationHandler This handler is called to establish authorization.
+ * @param failureHandler This handler is called if there was an error making the connection.
+ */
+typedef void (^GNCConnectionRequester)(
+ NSData *endpointInfo, GNCDiscovererConnectionInitializationHandler connectionAuthorizationHandler,
+ GNCConnectionFailureHandler failureHandler);
+
+/** Information about an endpoint when it's discovered. */
+@protocol GNCDiscoveredEndpointInfo <NSObject>
+/** The human readable name of the remote endpoint. */
+@property(nonatomic, readonly, copy) NSString *endpointName;
+/** Information advertised by the remote endpoint. */
+@property(nonatomic, readonly, copy) NSData *endpointInfo;
+/** Call this block to request a connection with the advertiser. */
+@property(nonatomic, readonly) GNCConnectionRequester requestConnection;
+@end
+
+/** This handler is called when a previously discovered advertiser endpoint is lost. */
+typedef void (^GNCEndpointLostHandler)(void);
+
+/**
+ * This handler is called when an advertiser endpoint is discovered.
+ *
+ * @param endpointId The ID of the endpoint.
+ * @param connectionInfo Information about the endpoint.
+ * @return Block that is called when the endpoint is lost.
+ */
+typedef GNCEndpointLostHandler _Nonnull (^GNCEndpointFoundHandler)(
+ GNCEndpointId endpointId, id<GNCDiscoveredEndpointInfo> endpointInfo);
+
+/**
+ * A discoverer searches for endpoints advertising the specified service, and allows connection
+ * requests to be sent to them. Release the discoverer object to stop discovering.
+ */
+@interface GNCDiscoverer : NSObject
+
+/**
+ * Factory method that creates a discoverer.
+ *
+ * @param serviceId A string that uniquely identifies the advertised service to search for.
+ * @param strategy The connection topology to use.
+ * @param endpointFoundHandler This handler is called when an endpoint advertising the service is
+ * discovered.
+ */
++ (instancetype)discovererWithServiceId:(NSString *)serviceId
+ strategy:(GNCStrategy)strategy
+ endpointFoundHandler:(GNCEndpointFoundHandler)endpointFoundHandler;
+
+@end
+
+NS_ASSUME_NONNULL_END
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/GNCPayload.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/GNCPayload.h
new file mode 100644
index 00000000000..83eef679275
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/GNCPayload.h
@@ -0,0 +1,64 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import <Foundation/Foundation.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/** This class encapsulates a Bytes payload. */
+@interface GNCBytesPayload : NSObject
+
+/** The unique identifier of the payload. */
+@property(nonatomic, readonly) int64_t identifier;
+
+/** The content of the payload. */
+@property(nonatomic, readonly) NSData *bytes;
+
+/**
+ * Creates a Bytes payload object.
+ * Note: To maximize performance, @c bytes is strongly referenced, not copied.
+ */
++ (instancetype)payloadWithBytes:(NSData *)bytes;
+
+@end
+
+/** This class encapsulates a Stream payload. */
+@interface GNCStreamPayload : NSObject
+
+/** The unique identifier of the payload. */
+@property(nonatomic, readonly) int64_t identifier;
+
+/** The payload data is read from this input stream. */
+@property(nonatomic, readonly) NSInputStream *stream;
+
++ (instancetype)payloadWithStream:(NSInputStream *)stream;
+
+@end
+
+/** This class encapsulates a File payload. */
+@interface GNCFilePayload : NSObject
+
+/** The unique identifier of the payload. */
+@property(nonatomic, readonly) int64_t identifier;
+
+/** A URL that identifies the file. */
+@property(nonatomic, readonly, copy) NSURL *fileURL;
+
++ (instancetype)payloadWithFileURL:(NSURL *)fileURL;
+
++ (instancetype)payloadWithFileURL:(NSURL *)fileURL identifier:(int64_t)identifier;
+
+@end
+
+NS_ASSUME_NONNULL_END
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCAdvertiser.mm b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCAdvertiser.mm
new file mode 100644
index 00000000000..b00bbebdbc3
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCAdvertiser.mm
@@ -0,0 +1,317 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import "internal/platform/implementation/ios/Source/GNCAdvertiser.h"
+
+#include <string>
+
+#include "absl/functional/bind_front.h"
+#include "connections/advertising_options.h"
+#include "connections/core.h"
+#include "connections/listeners.h"
+#include "connections/params.h"
+#include "connections/status.h"
+#include "internal/platform/byte_array.h"
+#import "internal/platform/implementation/ios/Source/GNCConnection.h"
+#import "internal/platform/implementation/ios/Source/Internal/GNCCore.h"
+#import "internal/platform/implementation/ios/Source/Internal/GNCCoreConnection.h"
+#import "internal/platform/implementation/ios/Source/Internal/GNCPayloadListener.h"
+#import "internal/platform/implementation/ios/Source/Internal/GNCUtils.h"
+#import "internal/platform/implementation/ios/Source/Platform/utils.h"
+#import "GoogleToolboxForMac/GTMLogger.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+using ::location::nearby::ByteArrayFromNSData;
+using ::location::nearby::CppStringFromObjCString;
+using ::location::nearby::ObjCStringFromCppString;
+using ::location::nearby::connections::ConnectionListener;
+using ::location::nearby::connections::AdvertisingOptions;
+using ::location::nearby::connections::ConnectionRequestInfo;
+using ::location::nearby::connections::ConnectionResponseInfo;
+using ::location::nearby::connections::GNCStrategyToStrategy;
+using ::location::nearby::connections::Medium;
+using ResultListener = ::location::nearby::connections::ResultCallback;
+using ::location::nearby::connections::Status;
+
+/** This is a GNCAdvertiserConnectionInfo that provides storage for its properties. */
+@interface GNCAdvertiserConnectionInfo : NSObject
+
+@property(nonatomic, readonly) NSString *name;
+@property(nonatomic, readonly) NSString *authToken;
+
+- (instancetype)initWithName:(NSString *)name authToken:(NSString *)authToken;
+
+@end
+
+@implementation GNCAdvertiserConnectionInfo
+
+- (instancetype)initWithName:(NSString *)name authToken:(NSString *)authToken {
+ self = [super init];
+ if (self) {
+ _name = [name copy];
+ _authToken = [authToken copy];
+ }
+ return self;
+}
+
+@end
+
+/** Information retained about an endpoint before and after requesting a connection. */
+@interface GNCAdvertiserEndpointInfo : NSObject
+@property(nonatomic) GNCAdvertiserConnectionInfo *connectionInfo;
+@property(nonatomic) GNCConnectionResponse clientResponse;
+@property(nonatomic) BOOL clientResponseReceived; // whether the client response has been received
+@property(nonatomic, nullable) GNCConnectionResultHandlers *connectionResultHandlers;
+@property(nonatomic, weak) GNCCoreConnection *connection;
+@property(nonatomic) GNCConnectionHandlers *connectionHandlers;
+@end
+
+@implementation GNCAdvertiserEndpointInfo
+
++ (instancetype)infoWithEndpointConnectionInfo:(GNCAdvertiserConnectionInfo *)connInfo {
+ GNCAdvertiserEndpointInfo *info = [[GNCAdvertiserEndpointInfo alloc] init];
+ info.connectionInfo = connInfo;
+ return info;
+}
+
+@end
+
+/** GNCAdvertiser members. */
+@interface GNCAdvertiser ()
+@property(nonatomic) GNCCore *core;
+@property(nonatomic) GNCAdvertiserConnectionInitiationHandler initiationHandler;
+@property(nonatomic, assign) Status status;
+@property(nonatomic) NSMutableDictionary<GNCEndpointId, GNCAdvertiserEndpointInfo *> *endpoints;
+@end
+
+/** C++ classes passed to the core library by GNCAdvertiser. */
+namespace location {
+namespace nearby {
+namespace connections {
+
+/** This class contains the callbacks for establishing and severing a connection. */
+class GNCAdvertiserConnectionListener {
+ public:
+ explicit GNCAdvertiserConnectionListener(GNCAdvertiser *advertiser) : advertiser_(advertiser) {}
+
+ void OnInitiated(const std::string &endpoint_id, const ConnectionResponseInfo &info) {
+ GNCAdvertiser *advertiser = advertiser_; // strongify
+ if (!advertiser) return;
+
+ NSString *endpointId = ObjCStringFromCppString(endpoint_id);
+ GNCAdvertiserEndpointInfo *endpointInfo = advertiser.endpoints[endpointId];
+ if (endpointInfo) {
+ GTMLoggerError(@"Connection already initiated for endpoint: %@", endpointId);
+ } else {
+ // TODO(b/169292092): endpointInfo is an advertisement byte array. Need to implement to
+ // extract the endpoint name not just force to cast string.
+ NSString *name = ObjCStringFromCppString(std::string(info.remote_endpoint_info));
+ NSString *authToken = ObjCStringFromCppString(info.authentication_token);
+ GNCAdvertiserConnectionInfo *connInfo =
+ [[GNCAdvertiserConnectionInfo alloc] initWithName:name authToken:authToken];
+ endpointInfo = [GNCAdvertiserEndpointInfo infoWithEndpointConnectionInfo:connInfo];
+
+ // Call the connection initiation handler. Synchronous because it returns the connection
+ // result handlers.
+ dispatch_sync(dispatch_get_main_queue(), ^{
+ __weak __typeof__(advertiser) weakAdvertiser = advertiser;
+ endpointInfo.connectionResultHandlers = advertiser.initiationHandler(
+ endpointId, (id<GNCAdvertiserConnectionInfo>)connInfo,
+ ^(GNCConnectionResponse response) {
+ __strong __typeof__(advertiser) strongAdvertiser = weakAdvertiser;
+ endpointInfo.clientResponse = response;
+ endpointInfo.clientResponseReceived = YES;
+ if (response == GNCConnectionResponseAccept) {
+ // The connection was accepted by the client.
+ if (payload_listener_ == nullptr) {
+ payload_listener_ = std::make_unique<GNCPayloadListener>(
+ advertiser.core,
+ ^{
+ return endpointInfo.connectionHandlers;
+ },
+ ^{
+ return endpointInfo.connection.payloads;
+ });
+ }
+ advertiser.core->_core->AcceptConnection(
+ CppStringFromObjCString(endpointId),
+ PayloadListener{
+ .payload_cb = absl::bind_front(&GNCPayloadListener::OnPayload,
+ payload_listener_.get()),
+ .payload_progress_cb = absl::bind_front(
+ &GNCPayloadListener::OnPayloadProgress, payload_listener_.get()),
+ },
+ ResultListener{});
+ } else {
+ // The connection was rejected by the client.
+ advertiser.core->_core->RejectConnection(CppStringFromObjCString(endpointId),
+ ResultListener{});
+ }
+ });
+ });
+ advertiser.endpoints[endpointId] = endpointInfo;
+ }
+ }
+
+ void OnAccepted(const std::string &endpoint_id) {
+ GNCAdvertiser *advertiser = advertiser_; // strongify
+ if (!advertiser) return;
+
+ NSString *endpointId = ObjCStringFromCppString(endpoint_id);
+ GNCAdvertiserEndpointInfo *endpointInfo = advertiser.endpoints[endpointId];
+ if (!endpointInfo) {
+ GTMLoggerInfo(@"Connection result for unknown endpoint: %@", endpointId);
+ return;
+ }
+
+ // The connection has been accepted by both endpoints, so create the GNCConnection object
+ // and pass it to |successHandler| for the client to use. It will be removed from |endpoints|
+ // when the client disconnects (on dealloc of GNCConnection).
+ // Note: Use a local strong reference to the connection object; don't just assign to
+ // |endpointInfo.connection|. Without a strong reference, the connection object can be
+ // deallocated before |successHandler| is called in the Release build.
+ __weak __typeof__(advertiser) weakAdvertiser = advertiser;
+ id<GNCConnection> connection = [GNCCoreConnection
+ connectionWithEndpointId:endpointId
+ core:advertiser.core
+ deallocHandler:^{
+ __strong __typeof__(advertiser) strongAdvertiser = weakAdvertiser;
+ if (!strongAdvertiser) return;
+ [strongAdvertiser.endpoints removeObjectForKey:endpointId];
+ }];
+ endpointInfo.connection = connection;
+
+ // Callback is synchronous because it returns the connection handlers.
+ dispatch_sync(dispatch_get_main_queue(), ^{
+ endpointInfo.connectionHandlers =
+ endpointInfo.connectionResultHandlers.successHandler(connection);
+ });
+ }
+
+ void OnRejected(const std::string &endpoint_id, Status status) {
+ GNCAdvertiser *advertiser = advertiser_; // strongify
+ if (!advertiser) return;
+
+ NSString *endpointId = ObjCStringFromCppString(endpoint_id);
+ GNCAdvertiserEndpointInfo *endpointInfo = advertiser.endpoints[endpointId];
+ if (!endpointInfo) {
+ GTMLoggerInfo(@"Connection result for unknown endpoint: %@", endpointId);
+ return;
+ }
+
+ // One side rejected, so call failureHandler with the connection status (we do this in all
+ // cases), and forget the endpoint.
+ dispatch_async(dispatch_get_main_queue(), ^{
+ endpointInfo.connectionResultHandlers.failureHandler(GNCConnectionFailureRejected);
+ });
+ [advertiser.endpoints removeObjectForKey:endpointId];
+ }
+
+ void OnDisconnected(const std::string &endpoint_id) {
+ GNCAdvertiser *advertiser = advertiser_; // strongify
+ if (!advertiser) return;
+
+ NSString *endpointId = ObjCStringFromCppString(endpoint_id);
+ GNCAdvertiserEndpointInfo *endpointInfo = advertiser.endpoints[endpointId];
+ if (endpointInfo) {
+ if (endpointInfo.connection) {
+ GNCDisconnectedHandler disconnectedHandler =
+ endpointInfo.connectionHandlers.disconnectedHandler;
+ dispatch_async(dispatch_get_main_queue(), ^{
+ if (disconnectedHandler) disconnectedHandler(GNCDisconnectedReasonUnknown);
+ });
+ } else {
+ GTMLoggerInfo(@"Disconnect for unconnected endpoint: %@", endpointId);
+ }
+ [advertiser.endpoints removeObjectForKey:endpointId];
+ } else {
+ GTMLoggerInfo(@"Disconnect for unknown endpoint: %@", endpointId);
+ }
+ }
+
+ void OnBandwidthChanged(const std::string &endpoint_id, Medium medium) {
+ GNCAdvertiser *advertiser = advertiser_; // strongify
+ if (!advertiser) return;
+
+ // TODO(b/169292092): Implement.
+ }
+
+ private:
+ __weak GNCAdvertiser *advertiser_;
+ std::unique_ptr<GNCPayloadListener> payload_listener_;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+using ::location::nearby::connections::GNCAdvertiserConnectionListener;
+
+@interface GNCAdvertiser () {
+ std::unique_ptr<GNCAdvertiserConnectionListener> advertiserListener;
+};
+
+@end
+
+@implementation GNCAdvertiser
+
++ (instancetype)advertiserWithEndpointInfo:(NSData *)endpointInfo
+ serviceId:(NSString *)serviceId
+ strategy:(GNCStrategy)strategy
+ connectionInitiationHandler:
+ (GNCAdvertiserConnectionInitiationHandler)initiationHandler {
+ GNCAdvertiser *advertiser = [[GNCAdvertiser alloc] init];
+ advertiser.initiationHandler = initiationHandler;
+ advertiser.endpoints = [[NSMutableDictionary alloc] init];
+ advertiser.core = GNCGetCore();
+ advertiser->advertiserListener = std::make_unique<GNCAdvertiserConnectionListener>(advertiser);
+
+ ConnectionListener listener = {
+ .initiated_cb = absl::bind_front(&GNCAdvertiserConnectionListener::OnInitiated,
+ advertiser->advertiserListener.get()),
+ .accepted_cb = absl::bind_front(&GNCAdvertiserConnectionListener::OnAccepted,
+ advertiser->advertiserListener.get()),
+ .rejected_cb = absl::bind_front(&GNCAdvertiserConnectionListener::OnRejected,
+ advertiser->advertiserListener.get()),
+ .disconnected_cb = absl::bind_front(&GNCAdvertiserConnectionListener::OnDisconnected,
+ advertiser->advertiserListener.get()),
+ };
+
+ advertiser.core->_core->StartAdvertising(
+ CppStringFromObjCString(serviceId),
+ AdvertisingOptions{
+ {
+ GNCStrategyToStrategy(strategy), // .strategy
+ location::nearby::connections::BooleanMediumSelector(), // .allowed
+ },
+ true, // .auto_upgrade_bandwidth
+ true, // .enforce_topology_constraints
+ },
+ ConnectionRequestInfo{
+ .endpoint_info = ByteArrayFromNSData(endpointInfo),
+ .listener = std::move(listener),
+ },
+ ResultListener{});
+ return advertiser;
+}
+
+- (void)dealloc {
+ GTMLoggerInfo(@"GNCAdvertiser deallocated");
+ _core->_core->StopAdvertising(ResultListener{});
+}
+
+@end
+
+NS_ASSUME_NONNULL_END
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCCore.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCCore.h
new file mode 100644
index 00000000000..4c4f0e9e8b5
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCCore.h
@@ -0,0 +1,55 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import <Foundation/Foundation.h>
+
+#include <memory>
+
+#include "connections/core.h"
+#include "connections/implementation/service_controller_router.h"
+#include "internal/platform/payload_id.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+/** This class contains the C++ Core object. */
+@interface GNCCore : NSObject {
+ @public
+ std::unique_ptr<::location::nearby::connections::Core> _core;
+ std::unique_ptr<::location::nearby::connections::ServiceControllerRouter>
+ _service_controller_router;
+}
+
+/**
+ * These functions are the utilities to manipulate the InputFile in ImplementationPlatform for
+ * sending File payload.
+ *
+ * Inserts the URL to the map, keyed by payloadID. The element will not be inserted if there
+ * already is an element with the key in the map.
+ */
+- (void)insertURLToMapWithPayloadID:(::location::nearby::PayloadId)payloadId urlToSend:(NSURL *)url;
+
+/**
+ * Returns the URL with the payloadID and removes the entry from the map. Returns nil if
+ * payloadID is not found.
+ */
+- (nullable NSURL *)extractURLWithPayloadID:(::location::nearby::PayloadId)payloadId;
+
+- (void)clearSendingURLMaps;
+
+@end
+
+/** This function returns the Core singleton, wrapped in an Obj-C object for lifetime management. */
+GNCCore *GNCGetCore();
+
+NS_ASSUME_NONNULL_END
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCCore.mm b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCCore.mm
new file mode 100644
index 00000000000..0abfc851e4a
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCCore.mm
@@ -0,0 +1,94 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import "internal/platform/implementation/ios/Source/Internal/GNCCore.h"
+
+#include <utility>
+
+#include "absl/container/flat_hash_map.h"
+#include "absl/container/internal/common.h"
+#include "connections/core.h"
+#include "connections/implementation/service_controller_router.h"
+#include "internal/platform/payload_id.h"
+#import "GoogleToolboxForMac/GTMLogger.h"
+
+using ::location::nearby::connections::Core;
+using ::location::nearby::PayloadId;
+using ::location::nearby::connections::ServiceControllerRouter;
+
+@implementation GNCCore {
+ // A map to store the NSURL object with PayloadId for sendFilePayload in GNCConnection.
+ // This is the place to store the NSURL for InputFile creation in ImplementationPlatform.
+ absl::flat_hash_map<PayloadId, NSURL *> _sending_urls;
+}
+
+- (instancetype)init {
+ GTMLoggerInfo(@"GNCCore created");
+ self = [super init];
+ if (self) {
+ _service_controller_router = std::make_unique<ServiceControllerRouter>();
+ _core = std::make_unique<Core>(_service_controller_router.get());
+ }
+ return self;
+}
+
+- (void)dealloc {
+ _core.reset();
+ _service_controller_router.reset();
+ GTMLoggerInfo(@"GNCCore deallocated");
+}
+
+- (void)insertURLToMapWithPayloadID:(PayloadId)payloadId urlToSend:(NSURL *)url {
+ _sending_urls.emplace(payloadId, url);
+}
+
+- (nullable NSURL *)extractURLWithPayloadID:(PayloadId)payloadId {
+ NSURL *url;
+ auto it = _sending_urls.find(payloadId);
+ if (it != _sending_urls.end()) {
+ auto pair = _sending_urls.extract(it);
+ url = pair.mapped();
+ }
+ return url;
+}
+
+- (void)clearSendingURLMaps {
+ _sending_urls.clear();
+}
+
+@end
+
+GNCCore *GNCGetCore() {
+ static NSObject *syncSingleton;
+ static dispatch_once_t onceToken;
+ dispatch_once(&onceToken, ^{
+ syncSingleton = [[NSObject alloc] init];
+ });
+
+ // The purpose of keeping a weak reference to the GNCCore object is to ensure that it will be
+ // released when all external strong references are gone. I.e., when the app is no longer doing
+ // any NC operations, the core will be released.
+ static __weak GNCCore *core;
+
+ // Strongly reference the GNCCore object for the duration of this function to ensure it isn't
+ // prematurely deallocated by ARC after being created (which can happen in optimized builds).
+ GNCCore *strongCore = core;
+ @synchronized(syncSingleton) {
+ if (!strongCore) {
+ strongCore = [[GNCCore alloc] init];
+ core = strongCore;
+ }
+ }
+ return strongCore;
+}
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCCoreConnection.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCCoreConnection.h
new file mode 100644
index 00000000000..08afddfd3ee
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCCoreConnection.h
@@ -0,0 +1,44 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import <Foundation/Foundation.h>
+
+#import "internal/platform/implementation/ios/Source/GNCConnection.h"
+#import "internal/platform/implementation/ios/Source/Internal/GNCCore.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+/** This holds the progress and completion for a pending payload. */
+@interface GNCPayloadInfo : NSObject
+@property(nonatomic, nullable) NSProgress *progress;
+@property(nonatomic, nullable) GNCPayloadResultHandler completion;
+
++ (instancetype)infoWithProgress:(nullable NSProgress *)progress
+ completion:(GNCPayloadResultHandler)completion;
+- (void)callCompletion:(GNCPayloadResult)result;
+@end
+
+/** GNCConnection that interfaces with the Core library. */
+@interface GNCCoreConnection : NSObject <GNCConnection>
+@property(nonatomic) GNCCore *core;
+@property(nonatomic, copy) GNCEndpointId endpointId;
+@property(nonatomic) dispatch_block_t deallocHandler;
+@property(nonatomic) NSMutableDictionary<NSNumber *, GNCPayloadInfo *> *payloads;
+
++ (instancetype)connectionWithEndpointId:(GNCEndpointId)endpointId
+ core:(GNCCore *)core
+ deallocHandler:(dispatch_block_t)deallocHandler;
+@end
+
+NS_ASSUME_NONNULL_END
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCCoreConnection.mm b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCCoreConnection.mm
new file mode 100644
index 00000000000..a389763e679
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCCoreConnection.mm
@@ -0,0 +1,188 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import "internal/platform/implementation/ios/Source/Internal/GNCCoreConnection.h"
+
+#include "connections/core.h"
+#include "connections/payload.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/file.h"
+#include "internal/platform/implementation/input_file.h"
+#import "internal/platform/implementation/ios/Source/GNCConnection.h"
+#import "internal/platform/implementation/ios/Source/GNCPayload.h"
+#import "internal/platform/implementation/ios/Source/Internal/GNCCore.h"
+#import "internal/platform/implementation/ios/Source/Platform/utils.h"
+#include "internal/platform/input_stream.h"
+#include "internal/platform/payload_id.h"
+
+using ::location::nearby::ByteArrayFromNSData;
+using ::location::nearby::CppStringFromObjCString;
+using ::location::nearby::InputFile;
+using ::location::nearby::InputStream;
+using ::location::nearby::connections::Payload;
+using ::location::nearby::PayloadId;
+using ResultListener = ::location::nearby::connections::ResultCallback;
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+/**
+ * This InputStream subclass takes input from an NSInputStream. The update handler is called for
+ * each chunk of data sent, giving the client an opportunity to handle cancelation.
+ */
+class GNCInputStreamFromNSStream : public InputStream {
+ public:
+ explicit GNCInputStreamFromNSStream(NSInputStream *nsStream) : nsStream_(nsStream) {
+ [nsStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
+ [nsStream open];
+ }
+
+ ~GNCInputStreamFromNSStream() override { Close(); }
+
+ ExceptionOr<ByteArray> Read() { return Read(kMaxChunkSize); }
+
+ ExceptionOr<ByteArray> Read(std::int64_t size) override {
+ uint8_t *bytesRead = new uint8_t[size];
+ NSUInteger numberOfBytesToRead = [[NSNumber numberWithLongLong:size] unsignedIntegerValue];
+ NSInteger numberOfBytesRead = [nsStream_ read:bytesRead maxLength:numberOfBytesToRead];
+ if (numberOfBytesRead == 0) {
+ // Reached end of stream.
+ return ExceptionOr<ByteArray>();
+ } else if (numberOfBytesRead < 0) {
+ // Stream error.
+ return ExceptionOr<ByteArray>{Exception::kIo};
+ }
+ return ExceptionOr<ByteArray>(ByteArrayFromNSData([NSData dataWithBytes:bytesRead
+ length:numberOfBytesRead]));
+ }
+
+ Exception Close() override {
+ [nsStream_ close];
+ return {Exception::kSuccess};
+ }
+
+ private:
+ static const size_t kMaxChunkSize = 32 * 1024;
+ NSInputStream *nsStream_;
+ // dispatch_block_t update_handler_;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+@implementation GNCPayloadInfo
+
++ (instancetype)infoWithProgress:(nullable NSProgress *)progress
+ completion:(GNCPayloadResultHandler)completion {
+ GNCPayloadInfo *info = [[GNCPayloadInfo alloc] init];
+ info.progress = progress;
+ info.completion = completion;
+ return info;
+}
+
+- (void)callCompletion:(GNCPayloadResult)result {
+ if (_completion) _completion(result);
+ _completion = nil;
+}
+
+@end
+
+@implementation GNCCoreConnection
+
++ (instancetype)connectionWithEndpointId:(GNCEndpointId)endpointId
+ core:(GNCCore *)core
+ deallocHandler:(dispatch_block_t)deallocHandler {
+ GNCCoreConnection *connection = [[GNCCoreConnection alloc] init];
+ connection.endpointId = endpointId;
+ connection.core = core;
+ connection.deallocHandler = deallocHandler;
+ connection.payloads = [[NSMutableDictionary alloc] init];
+ return connection;
+}
+
+- (void)dealloc {
+ _core->_core->DisconnectFromEndpoint(CppStringFromObjCString(_endpointId), ResultListener{});
+ _deallocHandler();
+}
+
+- (NSProgress *)sendBytesPayload:(GNCBytesPayload *)payload
+ completion:(GNCPayloadResultHandler)completion {
+ Payload corePayload(ByteArrayFromNSData(payload.bytes));
+ NSUInteger length = payload.bytes.length;
+ PayloadId payloadId = corePayload.GetId();
+ NSProgress *progress = [NSProgress progressWithTotalUnitCount:length];
+ __weak __typeof__(self) weakSelf = self;
+ progress.cancellationHandler = ^{
+ [weakSelf cancelPayloadWithId:payloadId];
+ };
+ return [self sendPayload:std::move(corePayload)
+ size:length
+ progress:progress
+ completion:completion];
+}
+
+- (NSProgress *)sendStreamPayload:(GNCStreamPayload *)payload
+ completion:(GNCPayloadResultHandler)completion {
+ NSProgress *progress = [NSProgress progressWithTotalUnitCount:-1];
+
+ PayloadId payloadId = payload.identifier;
+ Payload corePayload(payloadId, [payload]() -> InputStream & {
+ location::nearby::connections::GNCInputStreamFromNSStream *stream =
+ new location::nearby::connections::GNCInputStreamFromNSStream(payload.stream);
+ return *stream;
+ });
+ return [self sendPayload:std::move(corePayload) size:-1 progress:progress completion:completion];
+}
+
+- (NSProgress *)sendFilePayload:(GNCFilePayload *)payload
+ completion:(GNCPayloadResultHandler)completion {
+ NSProgress *progress = [NSProgress progressWithTotalUnitCount:0];
+
+ std::int64_t fileSize = 0;
+ NSURL *fileURL = payload.fileURL;
+ NSNumber *fileSizeValue = nil;
+ BOOL result = [fileURL getResourceValue:&fileSizeValue forKey:NSURLFileSizeKey error:nil];
+ if (result == YES) {
+ fileSize = fileSizeValue.longValue;
+ }
+ PayloadId payloadId = payload.identifier;
+ // Add the pair of payloadId and fileURL to the map in the GNCCore.
+ [_core insertURLToMapWithPayloadID:payloadId urlToSend:fileURL];
+ Payload corePayload(payloadId, InputFile(payloadId, fileSize));
+ progress.totalUnitCount = fileSize;
+ return [self sendPayload:std::move(corePayload)
+ size:fileSize
+ progress:progress
+ completion:completion];
+}
+
+#pragma mark Private
+
+- (NSProgress *)sendPayload:(Payload)payload
+ size:(uint64_t)size
+ progress:(NSProgress *)progress
+ completion:(GNCPayloadResultHandler)completion {
+ _payloads[@(payload.GetId())] = [GNCPayloadInfo infoWithProgress:progress completion:completion];
+ _core->_core->SendPayload(std::vector<std::string>(1, CppStringFromObjCString(_endpointId)),
+ std::move(payload), ResultListener{});
+ return progress;
+}
+
+- (void)cancelPayloadWithId:(PayloadId)payloadId {
+ _core->_core->CancelPayload(payloadId, ResultListener{});
+}
+
+@end
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCDiscoverer.mm b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCDiscoverer.mm
new file mode 100644
index 00000000000..1175204bc6b
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCDiscoverer.mm
@@ -0,0 +1,401 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import "internal/platform/implementation/ios/Source/GNCDiscoverer.h"
+
+#include <string>
+#include <utility>
+
+#include "absl/functional/bind_front.h"
+#include "connections/connection_options.h"
+#include "connections/core.h"
+#include "connections/discovery_options.h"
+#include "connections/listeners.h"
+#include "connections/status.h"
+#include "internal/platform/byte_array.h"
+#import "internal/platform/implementation/ios/Source/GNCConnection.h"
+#import "internal/platform/implementation/ios/Source/Internal/GNCCore.h"
+#import "internal/platform/implementation/ios/Source/Internal/GNCCoreConnection.h"
+#import "internal/platform/implementation/ios/Source/Internal/GNCPayloadListener.h"
+#import "internal/platform/implementation/ios/Source/Internal/GNCUtils.h"
+#import "internal/platform/implementation/ios/Source/Platform/utils.h"
+#import "GoogleToolboxForMac/GTMLogger.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+using ::location::nearby::ByteArray;
+using ::location::nearby::CppStringFromObjCString;
+using ::location::nearby::connections::DiscoveryOptions;
+using ::location::nearby::connections::ConnectionOptions;
+using ::location::nearby::connections::DiscoveryListener;
+using ::location::nearby::connections::DistanceInfo;
+using ::location::nearby::connections::GNCStrategyToStrategy;
+using ResultListener = ::location::nearby::connections::ResultCallback;
+using ::location::nearby::connections::Status;
+
+/** This is a GNCDiscovererConnectionInfo that provides storage for its properties. */
+@interface GNCDiscovererConnectionInfo : NSObject <GNCDiscovererConnectionInfo>
+@property(nonatomic, copy) NSString *authToken;
+
+/** Creates a GNCDiscovererConnectionInfo object. */
++ (instancetype)infoWithAuthToken:(NSString *)authToken;
+@end
+
+@implementation GNCDiscovererConnectionInfo
+
++ (instancetype)infoWithAuthToken:(NSString *)authToken {
+ GNCDiscovererConnectionInfo *info = [[GNCDiscovererConnectionInfo alloc] init];
+ info.authToken = authToken;
+ return info;
+}
+
+@end
+
+/** This is a GNCDiscoveredEndpointInfo that provides storage for its properties. */
+@interface GNCDiscoveredEndpointInfo : NSObject <GNCDiscoveredEndpointInfo>
+@property(nonatomic, copy) NSString *endpointName;
+@property(nonatomic, copy) NSData *endpointInfo;
+@end
+
+@implementation GNCDiscoveredEndpointInfo
+
+@synthesize requestConnection = _requestConnection;
+
++ (instancetype)infoWithName:(NSString *)endpointName
+ endpointInfo:(NSData *)endpointInfo
+ requestConnection:(GNCConnectionRequester)requestConnection {
+ GNCDiscoveredEndpointInfo *info = [[GNCDiscoveredEndpointInfo alloc] init];
+ info.endpointName = endpointName;
+ info.endpointInfo = endpointInfo;
+ info->_requestConnection = requestConnection;
+ return info;
+}
+
+@end
+
+/** Information retained by the discoverer about each discovered endpoint. */
+@interface GNCDiscovererEndpointInfo : NSObject
+
+/** Handles lostHandler once |onEndpointLost| has been callback. */
+@property(nonatomic) GNCEndpointLostHandler lostHandler;
+
+/** The connInitHandler is stored after requestConnection. */
+@property(nonatomic, nullable) GNCDiscovererConnectionInitializationHandler connInitHandler;
+
+/** The connFailureHandler is stored after requestConnection. */
+@property(nonatomic, nullable) GNCConnectionFailureHandler connFailureHandler;
+
+/** Client responses Accept or Reject. */
+@property(nonatomic) GNCConnectionResponse clientResponse;
+
+/** Whether the client response has been received. */
+@property(nonatomic) BOOL clientResponseReceived;
+
+/**
+ * The connectionhandler returned by connInitHandler. Stored here if the connection is accepted.
+ */
+@property(nonatomic, nullable) GNCConnectionHandler connectionHandler;
+
+/** @c GNCCoreConnection is created and stored if connection is accepted. */
+@property(nonatomic, weak) GNCCoreConnection *connection;
+
+/** @c GNCConnectionHandlers object is returned by connectionHandler and stored here. */
+@property(nonatomic) GNCConnectionHandlers *connectionHandlers;
+@end
+
+@implementation GNCDiscovererEndpointInfo
+@end
+
+/** GNCDiscoverer members. */
+@interface GNCDiscoverer ()
+@property(nonatomic) GNCCore *core;
+@property(nonatomic) GNCEndpointFoundHandler endpointFoundHandler;
+@property(nonatomic, assign) Status status;
+@property(nonatomic) NSMapTable<GNCEndpointId, GNCDiscovererEndpointInfo *> *endpoints;
+@end
+
+/** C++ classes passed to the core library by GNCDiscoverer. */
+namespace location {
+namespace nearby {
+namespace connections {
+
+/** This class contains the discoverer callbacks related to a connection. */
+class GNCDiscovererConnectionListener {
+ public:
+ GNCDiscovererConnectionListener(GNCCore *core,
+ NSMapTable<GNCEndpointId, GNCDiscovererEndpointInfo *> *endpoints)
+ : core_(core), endpoints_(endpoints) {}
+
+ void OnInitiated(const std::string &endpoint_id, const ConnectionResponseInfo &info) {
+ NSString *endpointId = ObjCStringFromCppString(endpoint_id);
+ GNCDiscovererEndpointInfo *endpointInfo = [endpoints_ objectForKey:endpointId];
+ if (!endpointInfo) {
+ return;
+ }
+
+ // Call the connection initiation handler. Synchronous because it returns the connection
+ // handler.
+ NSString *authToken = ObjCStringFromCppString(info.authentication_token);
+ GNCCore *core = core_; // don't capture |this|
+ dispatch_sync(dispatch_get_main_queue(), ^{
+ endpointInfo.connectionHandler = endpointInfo.connInitHandler(
+ [GNCDiscovererConnectionInfo infoWithAuthToken:authToken],
+ ^(GNCConnectionResponse response) {
+ endpointInfo.clientResponse = response;
+ endpointInfo.clientResponseReceived = YES;
+ if (response == GNCConnectionResponseAccept) {
+ // The connect was accepted by the client.
+ if (payload_listener_ == nullptr) {
+ payload_listener_ = std::make_unique<GNCPayloadListener>(
+ core,
+ ^{
+ return endpointInfo.connectionHandlers;
+ },
+ ^{
+ return endpointInfo.connection.payloads;
+ });
+ }
+ core->_core->AcceptConnection(
+ CppStringFromObjCString(endpointId),
+ PayloadListener{
+ .payload_cb =
+ absl::bind_front(&GNCPayloadListener::OnPayload, payload_listener_.get()),
+ .payload_progress_cb = absl::bind_front(
+ &GNCPayloadListener::OnPayloadProgress, payload_listener_.get()),
+ },
+ ResultListener{});
+ } else {
+ // The connect was rejected by the client.
+ core->_core->RejectConnection(CppStringFromObjCString(endpointId), ResultListener{});
+ }
+ });
+ });
+ }
+
+ void OnAccepted(const std::string &endpoint_id) {
+ NSString *endpointId = ObjCStringFromCppString(endpoint_id);
+ GNCDiscovererEndpointInfo *endpointInfo = [endpoints_ objectForKey:endpointId];
+ if (!endpointInfo) {
+ return;
+ }
+
+ // The connection has been accepted by both endpoints, so create the GNCConnection object
+ // and pass it to |successHandler| for the client to use.
+ // Note: Use a local strong reference to the connection object; don't just assign to
+ // |endpointInfo.connection|. Without a strong reference, the connection object can be
+ // deallocated before |successHandler| is called in the Release build.
+ id<GNCConnection> connection = [GNCCoreConnection
+ connectionWithEndpointId:endpointId
+ core:core_
+ deallocHandler:^{
+ // Don't remove the remote endpoint (like GNCAdvertiser does) because that's
+ // done when the endpoint is lost.
+ }];
+ endpointInfo.connection = connection;
+
+ // Callback is synchronous because it returns the connection handlers.
+ dispatch_sync(dispatch_get_main_queue(), ^{
+ endpointInfo.connectionHandlers = endpointInfo.connectionHandler(endpointInfo.connection);
+ });
+ endpointInfo.clientResponseReceived = NO; // support reconnection after disconnection
+ }
+
+ void OnRejected(const std::string &endpoint_id, Status status) {
+ NSString *endpointId = ObjCStringFromCppString(endpoint_id);
+ GNCDiscovererEndpointInfo *endpointInfo = [endpoints_ objectForKey:endpointId];
+ if (!endpointInfo) {
+ return;
+ }
+
+ // If either side rejected, call failureHandler with the connection status.
+ dispatch_async(dispatch_get_main_queue(), ^{
+ endpointInfo.connFailureHandler(GNCConnectionFailureRejected);
+ });
+ endpointInfo.clientResponseReceived = NO; // support reconnection after disconnection
+ }
+
+ void OnDisconnected(const std::string &endpoint_id) {
+ NSString *endpointId = ObjCStringFromCppString(endpoint_id);
+ GNCDiscovererEndpointInfo *endpointInfo = [endpoints_ objectForKey:endpointId];
+ if (!endpointInfo) {
+ return;
+ }
+
+ if (endpointInfo.connection) {
+ GNCDisconnectedHandler disconnectedHandler =
+ endpointInfo.connectionHandlers.disconnectedHandler;
+ dispatch_async(dispatch_get_main_queue(), ^{
+ if (disconnectedHandler) disconnectedHandler(GNCDisconnectedReasonUnknown);
+ });
+ }
+ }
+
+ void OnBandwidthChanged(const std::string &endpoint_id, Medium medium) {
+ // TODO(b/169292092): Implement.
+ }
+
+ private:
+ GNCCore *core_;
+ NSMapTable<GNCEndpointId, GNCDiscovererEndpointInfo *> *endpoints_;
+ std::unique_ptr<GNCPayloadListener> payload_listener_;
+};
+
+class GNCDiscoveryListener {
+ public:
+ explicit GNCDiscoveryListener(GNCDiscoverer *discoverer) : discoverer_(discoverer) {}
+
+ void OnEndpointFound(const std::string &endpoint_id, const ByteArray &endpoint_info,
+ const std::string &service_id) {
+ GNCDiscoverer *discoverer = discoverer_; // strongify
+ if (!discoverer) {
+ return;
+ }
+ NSString *endpointId = ObjCStringFromCppString(endpoint_id);
+
+ if ([discoverer.endpoints objectForKey:endpointId] != nil) {
+ GTMLoggerError(@"Endpoint already discovered: %@", endpointId);
+ } else {
+ // The GNCDiscoveredEndpointInfo object created here lives as long as the client has strong
+ // reference to it. Here's the chain of strong references maintained here:
+ // client -> GNCDiscoveredEndpointInfo -> RequestConnection block ->
+ // GNCDiscovererEndpointInfo (stored weakly in the |endpoints| map table)
+ GNCDiscovererEndpointInfo *endpointInfo = [[GNCDiscovererEndpointInfo alloc] init];
+ [discoverer.endpoints setObject:endpointInfo forKey:endpointId];
+
+ NSString *name = ObjCStringFromCppString(std::string(endpoint_info));
+ NSData *info = NSDataFromByteArray(endpoint_info);
+ GNCCore *core = discoverer.core; // don't capture |this| or |discoverer|
+ NSMapTable<GNCEndpointId, GNCDiscovererEndpointInfo *> *endpoints = discoverer.endpoints;
+ GNCDiscoveredEndpointInfo *discEndpointInfo = [GNCDiscoveredEndpointInfo
+ infoWithName:name
+ endpointInfo:info
+ requestConnection:^(NSData *info,
+ GNCDiscovererConnectionInitializationHandler connInitHandler,
+ GNCConnectionFailureHandler connFailureHandler) {
+ endpointInfo.connInitHandler = connInitHandler;
+ endpointInfo.connFailureHandler = connFailureHandler;
+ if (discoverer_connection_listener_ == nullptr) {
+ discoverer_connection_listener_ =
+ std::make_unique<GNCDiscovererConnectionListener>(core, endpoints);
+ }
+
+ ConnectionListener listener = {
+ .initiated_cb = absl::bind_front(&GNCDiscovererConnectionListener::OnInitiated,
+ discoverer_connection_listener_.get()),
+ .accepted_cb = absl::bind_front(&GNCDiscovererConnectionListener::OnAccepted,
+ discoverer_connection_listener_.get()),
+ .rejected_cb = absl::bind_front(&GNCDiscovererConnectionListener::OnRejected,
+ discoverer_connection_listener_.get()),
+ .disconnected_cb =
+ absl::bind_front(&GNCDiscovererConnectionListener::OnDisconnected,
+ discoverer_connection_listener_.get()),
+ };
+
+ core->_core->RequestConnection(
+ CppStringFromObjCString(endpointId),
+ ConnectionRequestInfo{.endpoint_info = ByteArrayFromNSData(info),
+ .listener = std::move(listener)},
+ ConnectionOptions{},
+ ResultListener{.result_cb = [&connFailureHandler](Status status) {
+ if (!status.Ok()) {
+ dispatch_sync(dispatch_get_main_queue(), ^{
+ connFailureHandler(GNCConnectionFailureUnknown);
+ });
+ }
+ }});
+ }];
+
+ // Call the client endpoint-found handler. Tail call for reentrancy.
+ dispatch_sync(dispatch_get_main_queue(), ^{
+ endpointInfo.lostHandler = discoverer.endpointFoundHandler(endpointId, discEndpointInfo);
+ });
+ }
+ }
+
+ void OnEndpointLost(const std::string &endpoint_id) {
+ GNCDiscoverer *discoverer = discoverer_; // strongify
+ if (!discoverer) {
+ return;
+ }
+
+ NSString *endpointId = ObjCStringFromCppString(endpoint_id);
+ GNCDiscovererEndpointInfo *info = [discoverer.endpoints objectForKey:endpointId];
+ if (!info) {
+ GTMLoggerError(@"Endpoint already lost: %@", endpointId);
+ } else {
+ dispatch_async(dispatch_get_main_queue(), ^{
+ info.lostHandler();
+ });
+ }
+ [discoverer.endpoints removeObjectForKey:endpointId];
+ }
+
+ void OnEndpointDistanceChanged_cb(const std::string &endpoint_id, DistanceInfo info) {
+ // TODO(b/169292092): Implement.
+ }
+
+ private:
+ __weak GNCDiscoverer *discoverer_;
+ std::unique_ptr<GNCDiscovererConnectionListener> discoverer_connection_listener_;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+using ::location::nearby::connections::GNCDiscoveryListener;
+
+@interface GNCDiscoverer () {
+ std::unique_ptr<GNCDiscoveryListener> discoveryListener;
+};
+
+@end
+
+@implementation GNCDiscoverer
+
++ (instancetype)discovererWithServiceId:(NSString *)serviceId
+ strategy:(GNCStrategy)strategy
+ endpointFoundHandler:(GNCEndpointFoundHandler)endpointFoundHandler {
+ GNCDiscoverer *discoverer = [[GNCDiscoverer alloc] init];
+ discoverer.endpointFoundHandler = endpointFoundHandler;
+ discoverer.endpoints = [NSMapTable strongToWeakObjectsMapTable];
+ discoverer.core = GNCGetCore();
+ discoverer->discoveryListener = std::make_unique<GNCDiscoveryListener>(discoverer);
+
+ DiscoveryListener listener = {
+ .endpoint_found_cb = absl::bind_front(&GNCDiscoveryListener::OnEndpointFound,
+ discoverer->discoveryListener.get()),
+ .endpoint_lost_cb = absl::bind_front(&GNCDiscoveryListener::OnEndpointLost,
+ discoverer->discoveryListener.get()),
+ };
+
+ discoverer.core->_core->StartDiscovery(CppStringFromObjCString(serviceId),
+ DiscoveryOptions{
+ {
+ GNCStrategyToStrategy(strategy),
+ },
+ },
+ std::move(listener), ResultListener{});
+
+ return discoverer;
+}
+
+- (void)dealloc {
+ GTMLoggerInfo(@"GNCDiscoverer deallocated");
+ _core->_core->StopDiscovery(ResultListener{});
+}
+
+@end
+
+NS_ASSUME_NONNULL_END
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCPayload+Internal.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCPayload+Internal.h
new file mode 100644
index 00000000000..4792826c7e9
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCPayload+Internal.h
@@ -0,0 +1,36 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import "internal/platform/implementation/ios/Source/GNCPayload.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+/** This category adds the ability to specify a payload ID. */
+@interface GNCBytesPayload (Internal)
++ (instancetype)payloadWithBytes:(NSData *)bytes identifier:(int64_t)identifier;
+@end
+
+
+/** This category adds the ability to specify a payload ID. */
+@interface GNCStreamPayload (Internal)
++ (instancetype)payloadWithStream:(NSInputStream *)stream identifier:(int64_t)identifier;
+@end
+
+
+/** This category adds the ability to specify a payload ID. */
+@interface GNCFilePayload (Internal)
++ (instancetype)payloadWithFileURL:(NSURL *)fileURL identifier:(int64_t)identifier;
+@end
+
+NS_ASSUME_NONNULL_END
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCPayload.mm b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCPayload.mm
new file mode 100644
index 00000000000..30c88fe5e7a
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCPayload.mm
@@ -0,0 +1,94 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import "internal/platform/implementation/ios/Source/GNCPayload.h"
+
+#include "connections/payload.h"
+#include "internal/platform/payload_id.h"
+
+#include <stdlib.h>
+
+using ::location::nearby::connections::Payload;
+using ::location::nearby::PayloadId;
+
+NS_ASSUME_NONNULL_BEGIN
+
+PayloadId GenerateId() {
+ return Payload::GenerateId();
+}
+
+@implementation GNCBytesPayload
+
+- (instancetype)initWithBytes:(NSData *)bytes identifier:(int64_t)identifier {
+ self = [super init];
+ if (self) {
+ _identifier = identifier;
+ _bytes = bytes;
+ }
+ return self;
+}
+
++ (instancetype)payloadWithBytes:(NSData *)bytes {
+ return [[self alloc] initWithBytes:bytes identifier:GenerateId()];
+}
+
++ (instancetype)payloadWithBytes:(NSData *)bytes identifier:(int64_t)identifier {
+ return [[self alloc] initWithBytes:bytes identifier:identifier];
+}
+
+@end
+
+@implementation GNCStreamPayload
+
+- (instancetype)initWithStream:(NSInputStream *)stream identifier:(int64_t)identifier {
+ self = [super init];
+ if (self) {
+ _identifier = identifier;
+ _stream = stream;
+ }
+ return self;
+}
+
++ (instancetype)payloadWithStream:(NSInputStream *)stream {
+ return [[self alloc] initWithStream:stream identifier:GenerateId()];
+}
+
++ (instancetype)payloadWithStream:(NSInputStream *)stream identifier:(int64_t)identifier {
+ return [[self alloc] initWithStream:stream identifier:identifier];
+}
+
+@end
+
+@implementation GNCFilePayload
+
+- (instancetype)initWithFileURL:(NSURL *)fileURL identifier:(int64_t)identifier {
+ self = [super init];
+ if (self) {
+ _identifier = identifier;
+ _fileURL = [fileURL copy];
+ }
+ return self;
+}
+
++ (instancetype)payloadWithFileURL:(NSURL *)fileURL {
+ return [[self alloc] initWithFileURL:fileURL identifier:GenerateId()];
+}
+
++ (instancetype)payloadWithFileURL:(NSURL *)fileURL identifier:(int64_t)identifier {
+ return [[self alloc] initWithFileURL:fileURL identifier:identifier];
+}
+
+@end
+
+NS_ASSUME_NONNULL_END
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCPayloadListener.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCPayloadListener.h
new file mode 100644
index 00000000000..51ae1a1c998
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCPayloadListener.h
@@ -0,0 +1,55 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import <Foundation/Foundation.h>
+
+#import "internal/platform/implementation/ios/Source/GNCConnection.h"
+#import "internal/platform/implementation/ios/Source/Internal/GNCCore.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+@class GNCPayloadInfo;
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+/** This fetches a GNCConnectionHandlers object. */
+typedef GNCConnectionHandlers *_Nonnull (^GNCConnectionHandlersProvider)();
+
+/** This fetches a payload dictionary. */
+typedef NSMutableDictionary<NSNumber *, GNCPayloadInfo *> *_Nonnull (^GNCPayloadsProvider)();
+
+/** This is the payload handler for an advertiser or discoverer. */
+class GNCPayloadListener : public PayloadListener {
+ public:
+ GNCPayloadListener(GNCCore *core, GNCConnectionHandlersProvider handlersProvider,
+ GNCPayloadsProvider payloadsProvider)
+ : core_(core), handlers_provider_(handlersProvider), payloads_provider_(payloadsProvider) {}
+
+ void OnPayload(const std::string& endpoint_id, Payload payload);
+ void OnPayloadProgress(const std::string& endpoint_id,
+ const PayloadProgressInfo& info);
+
+ private:
+ GNCCore *core_;
+ GNCConnectionHandlersProvider handlers_provider_;
+ GNCPayloadsProvider payloads_provider_;
+};
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+NS_ASSUME_NONNULL_END
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCPayloadListener.mm b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCPayloadListener.mm
new file mode 100644
index 00000000000..29c0feec54a
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCPayloadListener.mm
@@ -0,0 +1,218 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import "internal/platform/implementation/ios/Source/Internal/GNCPayloadListener.h"
+
+#include <string>
+
+#include "connections/core.h"
+#include "connections/listeners.h"
+#include "connections/payload.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/file.h"
+#import "internal/platform/implementation/ios/Source/GNCConnection.h"
+#import "internal/platform/implementation/ios/Source/GNCPayload.h"
+#import "internal/platform/implementation/ios/Source/Internal/GNCCore.h"
+#import "internal/platform/implementation/ios/Source/Internal/GNCCoreConnection.h"
+#import "internal/platform/implementation/ios/Source/Internal/GNCPayload+Internal.h"
+#include "internal/platform/implementation/ios/Source/Platform/utils.h"
+#include "internal/platform/input_stream.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+void GNCPayloadListener::OnPayload(const std::string &endpoint_id, Payload payload) {
+ GNCConnectionHandlers *handlers = handlers_provider_();
+ int64_t payloadId = payload.GetId();
+
+ // Note: The payload must be destroyed by each individual payload type handler below, because in
+ // the Stream payload case, it runs an asynchronous read-write loop, which needs the payload
+ // and its stream to live until the stream ends.
+ NSMutableDictionary<NSNumber *, GNCPayloadInfo *> *payloads = payloads_provider_();
+
+ switch (payload.GetType()) {
+ case Payload::Type::kBytes: {
+ NSData *data = NSDataFromByteArray(payload.AsBytes()); // don't capture C++ object
+
+ // Wait for the payload transfer update to arrive before calling the Bytes payload handler.
+ GNCPayloadInfo *info = [GNCPayloadInfo
+ infoWithProgress:nil
+ completion:^(GNCPayloadResult result) {
+ NSCAssert(result == GNCPayloadResultSuccess, @"Expected success");
+ if (handlers.bytesPayloadHandler) {
+ // Call the Bytes payload handler.
+ dispatch_async(dispatch_get_main_queue(), ^{
+ handlers.bytesPayloadHandler([GNCBytesPayload payloadWithBytes:data
+ identifier:payloadId]);
+ });
+ }
+ }];
+ payloads[@(payloadId)] = info;
+ break;
+ }
+
+ case Payload::Type::kStream:
+ if (handlers.streamPayloadHandler) {
+ // Make a pair of bound streams so data pumped into the output stream becomes
+ // available for reading from the input stream.
+ NSInputStream *clientInputStream;
+ NSOutputStream *clientOutputStream;
+ // TODO(b/169292092): Base on medium's bandwidth?
+ [NSStream getBoundStreamsWithBufferSize:1024
+ inputStream:&clientInputStream
+ outputStream:&clientOutputStream];
+
+ NSProgress *progress = [NSProgress progressWithTotalUnitCount:-1]; // indeterminate
+ progress.cancellable = YES;
+
+ // Pass the payload to the stream payload handler, receiving the completion handler from it.
+ // Since it returns a value, it must be called synchronously.
+ __block GNCPayloadResultHandler completion;
+ dispatch_sync(dispatch_get_main_queue(), ^{
+ completion = handlers.streamPayloadHandler(
+ [GNCStreamPayload payloadWithStream:clientInputStream identifier:payloadId],
+ progress);
+ });
+ GNCPayloadInfo *info = [GNCPayloadInfo infoWithProgress:progress completion:completion];
+ payloads[@(payloadId)] = info;
+
+ // This is a loop that reads data from the C++ input stream and writes it to the output
+ // stream that feeds it to the client input stream.
+ __block InputStream *payloadInputStream = payload.AsStream();
+ dispatch_queue_t queue =
+ dispatch_queue_create("StreamReceiverQueue", DISPATCH_QUEUE_SERIAL);
+ dispatch_async(queue, ^{
+ [clientOutputStream open];
+ while (true) {
+ if (progress.isCancelled) {
+ // Payload was canceled by the client.
+ core_->_core->CancelPayload(payloadId, ResultCallback{.result_cb = [](Status status) {
+ // TODO(b/148640962): Implement.
+ }});
+ break;
+ }
+
+ ExceptionOr<ByteArray> readResult = payloadInputStream->Read(1024);
+ if (!readResult.ok()) {
+ // Error reading from stream.
+ // TODO(b/169292092): Tell core an error has occurred?
+ dispatch_async(dispatch_get_main_queue(), ^{
+ [info callCompletion:GNCPayloadResultFailure];
+ });
+ break;
+ }
+ ByteArray byteArray = readResult.GetResult();
+ if (byteArray.Empty()) {
+ // End of stream.
+ break;
+ }
+
+ // Loop until it's all been consumed by the client output stream.
+ NSData *data = NSDataFromByteArray(byteArray);
+ NSUInteger totalLength = data.length;
+ NSUInteger totalNumberWritten = 0;
+ while (totalNumberWritten < totalLength) {
+ NSInteger numberWritten =
+ [clientOutputStream write:&((const uint8_t *)data.bytes)[totalNumberWritten]
+ maxLength:totalLength - totalNumberWritten];
+ if (numberWritten <= 0) { // stream error or reached end of stream
+ // TODO(b/169292092): Tell core an error has occurred?
+ dispatch_async(dispatch_get_main_queue(), ^{
+ [info callCompletion:GNCPayloadResultFailure];
+ });
+ break;
+ }
+ totalNumberWritten += numberWritten;
+ }
+ }
+ });
+ }
+ break;
+
+ case Payload::Type::kFile:
+ if (handlers.filePayloadHandler) {
+ InputFile *payloadInputFile = payload.AsFile();
+ NSURL *fileURL =
+ [NSURL URLWithString:ObjCStringFromCppString(payloadInputFile->GetFilePath())];
+ int64_t fileSize = payloadInputFile->GetTotalSize();
+ NSProgress *progress = [NSProgress progressWithTotalUnitCount:fileSize];
+ progress.cancellable = YES;
+ progress.cancellationHandler = ^{
+ // Payload was canceled by the client.
+ core_->_core->CancelPayload(payloadId, ResultCallback{.result_cb = [](Status status) {
+ // TODO(b/148640962): Implement.
+ }});
+ };
+
+ // Pass the payload to the file payload handler, receiving the completion handler from it.
+ // Since it returns a value, it must be called synchronously.
+ __block GNCPayloadResultHandler completion;
+ void (^passPayloadBlock)(void) = ^{
+ completion = handlers.filePayloadHandler(
+ [GNCFilePayload payloadWithFileURL:fileURL identifier:payloadId], progress);
+ };
+ if ([NSThread isMainThread]) {
+ passPayloadBlock();
+ } else {
+ dispatch_sync(dispatch_get_main_queue(), passPayloadBlock);
+ }
+ GNCPayloadInfo *info = [GNCPayloadInfo infoWithProgress:progress completion:completion];
+ payloads[@(payloadId)] = info;
+ }
+ break;
+
+ default:
+ ;// fall through
+ }
+}
+
+void GNCPayloadListener::OnPayloadProgress(const std::string &endpoint_id,
+ const PayloadProgressInfo &info) {
+ // Note: The logic in this callback for handling progress updates and payload completion is
+ // identical for Bytes, Stream and File payloads.
+ NSMutableDictionary<NSNumber *, GNCPayloadInfo *> *payloads = payloads_provider_();
+ NSNumber *payloadId = @(info.payload_id);
+ GNCPayloadInfo *payloadInfo = payloads[payloadId];
+ if (payloadInfo) {
+ // Update the progress.
+ if (payloadInfo.progress) {
+ payloadInfo.progress.completedUnitCount = info.bytes_transferred;
+ }
+
+ // Call the completion handler for success/failure/canceled, but not in-progress.
+ if (info.status == PayloadProgressInfo::Status::kInProgress) {
+ return;
+ }
+ GNCPayloadResult result =
+ (info.status == PayloadProgressInfo::Status::kSuccess) ? GNCPayloadResultSuccess
+ : (info.status == PayloadProgressInfo::Status::kCanceled) ? GNCPayloadResultCanceled
+ : GNCPayloadResultFailure;
+ dispatch_async(dispatch_get_main_queue(), ^{
+ payloadInfo.completion(result);
+ });
+
+ // Release the payload info.
+ [payloads removeObjectForKey:payloadId];
+ }
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+NS_ASSUME_NONNULL_END
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCUtils.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCUtils.h
new file mode 100644
index 00000000000..7f1e7b66289
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCUtils.h
@@ -0,0 +1,42 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import <Foundation/Foundation.h>
+
+#include <string>
+
+#include "connections/listeners.h"
+#import "internal/platform/implementation/ios/Source/GNCAdvertiser.h"
+#import "internal/platform/implementation/ios/Source/GNCConnection.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+/** Converts GNCStrategy to Strategy. */
+const Strategy& GNCStrategyToStrategy(GNCStrategy strategy);
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+/** Internal-only properties of the connection result handlers class. */
+@interface GNCConnectionResultHandlers ()
+@property(nonatomic) GNCConnectionHandler successHandler;
+@property(nonatomic) GNCConnectionFailureHandler failureHandler;
+@end
+
+NS_ASSUME_NONNULL_END
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCUtils.mm b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCUtils.mm
new file mode 100644
index 00000000000..2f3aa81db29
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/GNCUtils.mm
@@ -0,0 +1,77 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import "internal/platform/implementation/ios/Source/Internal/GNCUtils.h"
+
+#include "connections/strategy.h"
+#import "internal/platform/implementation/ios/Source/GNCAdvertiser.h"
+#import "internal/platform/implementation/ios/Source/GNCConnection.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+namespace location {
+namespace nearby {
+namespace connections {
+
+const Strategy& GNCStrategyToStrategy(GNCStrategy strategy) {
+ switch (strategy) {
+ case GNCStrategyCluster:
+ return Strategy::kP2pCluster;
+ case GNCStrategyStar:
+ return Strategy::kP2pStar;
+ case GNCStrategyPointToPoint:
+ return Strategy::kP2pPointToPoint;
+ }
+}
+
+} // namespace connections
+} // namespace nearby
+} // namespace location
+
+@implementation GNCConnectionHandlers
+
+- (instancetype)initWithBuilderBlock:(void (^)(GNCConnectionHandlers*))builderBlock {
+ self = [super init];
+ if (self) {
+ builderBlock(self);
+ }
+ return self;
+}
+
++ (instancetype)handlersWithBuilder:(void (^)(GNCConnectionHandlers * _Nonnull))builderBlock {
+ return [[self alloc] initWithBuilderBlock:builderBlock];
+}
+
+@end
+
+@implementation GNCConnectionResultHandlers
+
+- (instancetype)initWithSuccessHandler:(GNCConnectionHandler)successHandler
+ failureHandler:(GNCConnectionFailureHandler)failureHandler {
+ self = [super init];
+ if (self) {
+ _successHandler = successHandler;
+ _failureHandler = failureHandler;
+ }
+ return self;
+}
+
++ (instancetype)successHandler:(GNCConnectionHandler)successHandler
+ failureHandler:(GNCConnectionFailureHandler)failureHandler {
+ return [[self alloc] initWithSuccessHandler:successHandler failureHandler:failureHandler];
+}
+
+@end
+
+NS_ASSUME_NONNULL_END
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/platform.mm b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/platform.mm
new file mode 100644
index 00000000000..a7366bb97b4
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Internal/platform.mm
@@ -0,0 +1,151 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/platform.h"
+
+#include <string>
+
+#import "internal/platform/implementation/ios/Source/Internal/GNCCore.h"
+#include "internal/platform/implementation/ios/Source/Platform/atomic_boolean.h"
+#include "internal/platform/implementation/ios/Source/Platform/atomic_uint32.h"
+#include "internal/platform/implementation/ios/Source/Platform/condition_variable.h"
+#include "internal/platform/implementation/ios/Source/Platform/count_down_latch.h"
+#include "internal/platform/implementation/ios/Source/Platform/input_file.h"
+#import "internal/platform/implementation/ios/Source/Platform/log_message.h"
+#import "internal/platform/implementation/ios/Source/Platform/multi_thread_executor.h"
+#include "internal/platform/implementation/ios/Source/Platform/mutex.h"
+#import "internal/platform/implementation/ios/Source/Platform/scheduled_executor.h"
+#import "internal/platform/implementation/ios/Source/Platform/single_thread_executor.h"
+#import "internal/platform/implementation/ios/Source/Platform/utils.h"
+#include "internal/platform/implementation/ios/Source/Platform/wifi_lan.h"
+#include "internal/platform/implementation/mutex.h"
+#include "internal/platform/implementation/shared/file.h"
+#include "internal/platform/payload_id.h"
+
+namespace location {
+namespace nearby {
+namespace api {
+
+namespace {
+std::string GetPayloadPath(PayloadId payload_id) {
+ // This is to get a file path, e.g. /tmp/[payload_id], for the storage of payload file.
+ // NOTE: Per
+ // https://developer.apple.com/library/content/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html
+ // Files saved in the /tmp directory will be deleted by the system. Callers should be responsible
+ // for copying the files to the permanent storage.
+ NSString* payloadIdString = ObjCStringFromCppString(std::to_string(payload_id));
+ return CppStringFromObjCString(
+ [NSTemporaryDirectory() stringByAppendingPathComponent:payloadIdString]);
+}
+} // namespace
+
+// Atomics:
+std::unique_ptr<AtomicBoolean> ImplementationPlatform::CreateAtomicBoolean(bool initial_value) {
+ return std::make_unique<ios::AtomicBoolean>(initial_value);
+}
+
+std::unique_ptr<AtomicUint32> ImplementationPlatform::CreateAtomicUint32(
+ std::uint32_t initial_value) {
+ return std::make_unique<ios::AtomicUint32>(initial_value);
+}
+
+std::unique_ptr<CountDownLatch> ImplementationPlatform::CreateCountDownLatch(std::int32_t count) {
+ return std::make_unique<ios::CountDownLatch>(count);
+}
+
+std::unique_ptr<Mutex> ImplementationPlatform::CreateMutex(Mutex::Mode mode) {
+ // iOS does not support unchecked Mutex in debug mode, therefore
+ // ios::Mutex is used for both kRegular and kRegularNoCheck.
+ if (mode == Mutex::Mode::kRecursive) {
+ return absl::make_unique<ios::RecursiveMutex>();
+ } else {
+ return absl::make_unique<ios::Mutex>();
+ }
+}
+
+std::unique_ptr<ConditionVariable> ImplementationPlatform::CreateConditionVariable(Mutex* mutex) {
+ return std::make_unique<ios::ConditionVariable>(static_cast<ios::Mutex*>(mutex));
+}
+
+std::unique_ptr<InputFile> ImplementationPlatform::CreateInputFile(PayloadId payload_id,
+ std::int64_t total_size) {
+ // Extract the NSURL object with payload_id from |GNCCore| which stores the maps. If the retrieved
+ // NSURL object is not nil, we create InputFile by ios::InputFile. The difference is
+ // that ios::InputFile implements to read bytes from local real file for sending.
+ GNCCore* core = GNCGetCore();
+ NSURL* url = [core extractURLWithPayloadID:payload_id];
+ if (url != nil) {
+ return absl::make_unique<ios::InputFile>(url);
+ } else {
+ return shared::IOFile::CreateInputFile(GetPayloadPath(payload_id), total_size);
+ }
+}
+
+std::unique_ptr<OutputFile> ImplementationPlatform::CreateOutputFile(PayloadId payload_id) {
+ return shared::IOFile::CreateOutputFile(GetPayloadPath(payload_id));
+}
+
+std::unique_ptr<LogMessage> ImplementationPlatform::CreateLogMessage(
+ const char* file, int line, LogMessage::Severity severity) {
+ return absl::make_unique<ios::LogMessage>(file, line, severity);
+}
+
+// Java-like Executors
+std::unique_ptr<SubmittableExecutor> ImplementationPlatform::CreateSingleThreadExecutor() {
+ return std::make_unique<ios::SingleThreadExecutor>();
+}
+
+std::unique_ptr<SubmittableExecutor> ImplementationPlatform::CreateMultiThreadExecutor(
+ int max_concurrency) {
+ return std::make_unique<ios::MultiThreadExecutor>(max_concurrency);
+}
+
+std::unique_ptr<ScheduledExecutor> ImplementationPlatform::CreateScheduledExecutor() {
+ return std::make_unique<ios::ScheduledExecutor>();
+}
+
+// Mediums
+std::unique_ptr<BluetoothAdapter> ImplementationPlatform::CreateBluetoothAdapter() {
+ return nullptr;
+}
+
+std::unique_ptr<BluetoothClassicMedium> ImplementationPlatform::CreateBluetoothClassicMedium(
+ api::BluetoothAdapter& adapter) {
+ return nullptr;
+}
+
+std::unique_ptr<BleMedium> ImplementationPlatform::CreateBleMedium(api::BluetoothAdapter& adapter) {
+ return nullptr;
+}
+
+std::unique_ptr<ble_v2::BleMedium> ImplementationPlatform::CreateBleV2Medium(
+ api::BluetoothAdapter& adapter) {
+ return nullptr;
+}
+
+std::unique_ptr<ServerSyncMedium> ImplementationPlatform::CreateServerSyncMedium() {
+ return nullptr;
+}
+
+std::unique_ptr<WifiMedium> ImplementationPlatform::CreateWifiMedium() { return nullptr; }
+
+std::unique_ptr<WifiLanMedium> ImplementationPlatform::CreateWifiLanMedium() {
+ return std::make_unique<ios::WifiLanMedium>();
+}
+
+std::unique_ptr<WebRtcMedium> ImplementationPlatform::CreateWebRtcMedium() { return nullptr; }
+
+} // namespace api
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/BUILD b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/BUILD
new file mode 100644
index 00000000000..65c811784c7
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/BUILD
@@ -0,0 +1,56 @@
+load("//tools/build_defs/apple:objc.bzl", "objc_proto_library")
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+licenses(["notice"])
+
+package(default_visibility = ["//internal/platform/implementation/ios:__subpackages__"])
+
+objc_library(
+ name = "Mediums",
+ srcs = [
+ "GNCLeaks.m",
+ "GNCMConnection.m",
+ "WifiLan/GNCMBonjourBrowser.m",
+ "WifiLan/GNCMBonjourConnection.m",
+ "WifiLan/GNCMBonjourService.m",
+ "WifiLan/GNCMBonjourUtils.m",
+ ],
+ hdrs = [
+ "GNCLeaks.h",
+ "GNCMConnection.h",
+ "WifiLan/GNCMBonjourBrowser.h",
+ "WifiLan/GNCMBonjourConnection.h",
+ "WifiLan/GNCMBonjourService.h",
+ "WifiLan/GNCMBonjourUtils.h",
+ ],
+ deps = [
+ ":ObjCProtos",
+ "//internal/platform/implementation/ios/Source/Shared",
+ "//third_party/objective_c/google_toolbox_for_mac:GTM_Logger",
+ "@com_google_absl//absl/numeric:int128",
+ ],
+)
+
+objc_proto_library(
+ name = "ObjCProtos",
+ deps = [":Protos"],
+)
+
+proto_library(
+ name = "Protos",
+ deps = [
+ "//connections/implementation/proto:offline_wire_formats_proto",
+ ],
+)
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/GNCLeaks.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/GNCLeaks.h
new file mode 100644
index 00000000000..1b044fd3bd4
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/GNCLeaks.h
@@ -0,0 +1,18 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import <Foundation/Foundation.h>
+
+// Verifies that an object has been deallocated after the given time period.
+void GNCVerifyDealloc(id object, NSTimeInterval timeInterval);
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/GNCLeaks.m b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/GNCLeaks.m
new file mode 100644
index 00000000000..220326a9648
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/GNCLeaks.m
@@ -0,0 +1,27 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import "internal/platform/implementation/ios/Source/Mediums/GNCLeaks.h"
+
+void GNCVerifyDealloc(id object, NSTimeInterval timeInterval) {
+#if DEBUG
+ __weak id weakObj = object;
+ NSCAssert(weakObj != nil, @"Pointer to %@ is already nil", weakObj);
+ NSLog(@"Verifying deallocation of %@", NSStringFromClass([weakObj class]));
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeInterval * NSEC_PER_SEC)),
+ dispatch_get_main_queue(), ^{
+ NSCAssert(weakObj == nil, @"%@ not deallocated.", weakObj);
+ });
+#endif
+}
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/GNCMConnection.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/GNCMConnection.h
new file mode 100644
index 00000000000..67d32fb1dd1
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/GNCMConnection.h
@@ -0,0 +1,101 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import <Foundation/Foundation.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/** Result of a medium payload transfer. */
+typedef NS_ENUM(NSInteger, GNCMPayloadResult) {
+ GNCMPayloadResultSuccess, // Payload delivery was successful.
+ GNCMPayloadResultFailure, // An error occurred during payload delivery.
+ GNCMPayloadResultCanceled, // Payload delivery was canceled.
+};
+
+/** Handler for a @c GNCMPayloadResult value. */
+typedef void (^GNCMPayloadResultHandler)(GNCMPayloadResult);
+
+/**
+ * A progress handler is periodically called during payload delivery. It is passed a value
+ * ranging from 0 (when the operation has just started) to the total size (when the operation is
+ * finished).
+ */
+typedef void (^GNCMProgressHandler)(size_t count);
+
+/** This handler is called when data is received from a remote endpoint. */
+typedef void (^GNCMPayloadHandler)(NSData *data);
+
+/**
+ * This represents a connection with a remote endpoint at the medium level. Use it to send
+ * payloads to the remote endpoint, and release it to disconnect.
+ */
+@protocol GNCMConnection <NSObject>
+
+/**
+ * Sends data to the remote endpoint. Wait for the completion to be called before sending another
+ * payload.
+ *
+ * @param payload The data to send.
+ * @param progressHandler Called repeatedly for progress feedback while the data is being sent.
+ * @param completion Callback called when the data has been fully sent,
+ * or it has failed to be sent (not connected or disconnected).
+ */
+- (void)sendData:(NSData *)payload
+ progressHandler:(GNCMProgressHandler)progressHandler
+ completion:(GNCMPayloadResultHandler)completion;
+
+@end
+
+/** This class contains optional handlers for a connection. */
+@interface GNCMConnectionHandlers : NSObject
+
+/** This handler is called when data is sent from the remote endpoint. */
+@property(nonatomic) GNCMPayloadHandler payloadHandler;
+
+/** This handler is called when the connection is ended. */
+@property(nonatomic) dispatch_block_t disconnectedHandler;
+
+/** This method creates a GNCMConnectionHandlers object from payload and disconnect handlers. */
++ (instancetype)payloadHandler:(GNCMPayloadHandler)payloadHandler
+ disconnectedHandler:(dispatch_block_t)disconnectedHandler;
+
+@end
+
+/**
+ * This handler takes a GNCMConnection object and returns a GNCMConnectionHandlers object. It is
+ * called when a connection is successfully made with a remote endpoint. If |connection| is nil,
+ * the connection couldn't be established; in this case, return nil.
+ */
+typedef GNCMConnectionHandlers *_Nullable (^GNCMConnectionHandler)(
+ id<GNCMConnection> __nullable connection);
+
+/**
+ * This handler is called by a discovering endpoint to request a connection with an an advertising
+ * endpoint.
+ */
+typedef void (^GNCMConnectionRequester)(GNCMConnectionHandler connectionHandler);
+
+/** This handler is called when a previously discovered advertising endpoint is lost. */
+typedef void (^GNCMEndpointLostHandler)(void);
+
+/**
+ * This handler is called on a discoverer when a nearby advertising endpoint is
+ * discovered. Calls |requestConnection| to request a connection with the advertiser.
+ */
+typedef GNCMEndpointLostHandler _Nonnull (^GNCMEndpointFoundHandler)(
+ NSString *endpointId, NSString *serviceType, NSString *serviceName,
+ NSDictionary<NSString *, NSData *> *_Nullable TXTRecordData,
+ GNCMConnectionRequester requestConnection);
+
+NS_ASSUME_NONNULL_END
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/GNCMConnection.m b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/GNCMConnection.m
new file mode 100644
index 00000000000..27b4c20fa62
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/GNCMConnection.m
@@ -0,0 +1,31 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import "internal/platform/implementation/ios/Source/Mediums/GNCMConnection.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+@implementation GNCMConnectionHandlers
+
++ (instancetype)payloadHandler:(GNCMPayloadHandler)payloadHandler
+ disconnectedHandler:(dispatch_block_t)disconnectedHandler {
+ GNCMConnectionHandlers *handlers = [[GNCMConnectionHandlers alloc] init];
+ handlers.payloadHandler = payloadHandler;
+ handlers.disconnectedHandler = disconnectedHandler;
+ return handlers;
+}
+
+@end
+
+NS_ASSUME_NONNULL_END
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourBrowser.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourBrowser.h
new file mode 100644
index 00000000000..6f5d338ee8f
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourBrowser.h
@@ -0,0 +1,42 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import <Foundation/Foundation.h>
+
+#import "internal/platform/implementation/ios/Source/Mediums/GNCMConnection.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ * GNCMBonjourBrowser browses mDNS services publishing the specified mDNS type and domain. The mDNS
+ * type is a string formatted as "_[serviceIdHash]._tcp." in which [serviceIdHash] is generated as
+ * a SHA-256 hash from the service ID and taken the 6 first bytes of string in upper case.
+ * Calls the specififed endpoint found handler when one is found. The endpoint found handler
+ * supplies a requester block, which can be called to establish a socket to the service found.
+ *
+ * Don't hold the strong reference of caller self in endpointFoundHandler to ensure there is no
+ * retain cycle between them.
+ *
+ * @param serviceType An mDNS type that uniquely identifies the published service to search for.
+ * @param endpointFoundHandler The handler that is called when an endpoint publishing the service
+ * ID is discovered.
+ */
+@interface GNCMBonjourBrowser : NSObject
+
+- (instancetype)initWithServiceType:(NSString *)serviceType
+ endpointFoundHandler:(GNCMEndpointFoundHandler)handler;
+
+@end
+
+NS_ASSUME_NONNULL_END
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourBrowser.m b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourBrowser.m
new file mode 100644
index 00000000000..d88f8a10929
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourBrowser.m
@@ -0,0 +1,176 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import "internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourBrowser.h"
+
+#import "internal/platform/implementation/ios/Source/Mediums/GNCMConnection.h"
+#import "internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourConnection.h"
+#import "internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourUtils.h"
+#import "GoogleToolboxForMac/GTMLogger.h"
+
+typedef NSString *GNCEndpointId;
+
+@interface GNCMNetServiceInfo : NSObject
+@property(nonatomic) NSNetService *service;
+@property(nonatomic, copy) GNCMEndpointLostHandler endpointLostHandler;
+@property(nonatomic, copy, nullable) GNCMConnectionHandler connectionHandler;
+@end
+
+@implementation GNCMNetServiceInfo
+
++ (instancetype)infoWithService:(NSNetService *)service {
+ GNCMNetServiceInfo *info = [[GNCMNetServiceInfo alloc] init];
+ info.service = service;
+ return info;
+}
+
+- (BOOL)isEqual:(GNCMNetServiceInfo *)object {
+ return [_service isEqual:object.service];
+}
+
+- (NSUInteger)hash {
+ return [_service hash];
+}
+
+@end
+
+@interface GNCMBonjourBrowser () <NSNetServiceBrowserDelegate, NSNetServiceDelegate>
+
+@property(nonatomic, copy) GNCMEndpointFoundHandler endpointFoundHandler;
+
+@property(nonatomic) NSNetServiceBrowser *netBrowser;
+@property(nonatomic) NSMutableDictionary<GNCEndpointId, GNCMNetServiceInfo *> *endpoints;
+
+@end
+
+@implementation GNCMBonjourBrowser
+
+- (instancetype)initWithServiceType:(NSString *)serviceType
+ endpointFoundHandler:(GNCMEndpointFoundHandler)handler {
+ self = [super init];
+ if (self) {
+ _endpointFoundHandler = handler;
+
+ _netBrowser = [[NSNetServiceBrowser alloc] init];
+ _netBrowser.delegate = self;
+ [_netBrowser scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
+ [_netBrowser searchForServicesOfType:serviceType inDomain:GNCMBonjourDomain];
+ _endpoints = [NSMutableDictionary dictionary];
+ }
+ return self;
+}
+
+#pragma mark NSNetServiceBrowserDelegate
+
+- (void)netServiceBrowserWillSearch:(NSNetServiceBrowser *)browser {
+ GTMLoggerDebug(@"Browsing");
+}
+
+- (void)netServiceBrowserDidStopSearch:(NSNetServiceBrowser *)browser {
+ GTMLoggerDebug(@"Stop browsing");
+}
+
+- (void)netServiceBrowser:(NSNetServiceBrowser *)browser
+ didNotSearch:(NSDictionary<NSString *, NSNumber *> *)errorDict {
+ GTMLoggerDebug(@"Not browsing with errorDict: %@", errorDict);
+}
+
+- (void)netServiceBrowser:(NSNetServiceBrowser *)browser
+ didFindService:(NSNetService *)service
+ moreComing:(BOOL)moreComing {
+ GTMLoggerDebug(@"Found service: %@", service);
+
+ GNCMNetServiceInfo *info = [GNCMNetServiceInfo infoWithService:service];
+
+ // Just to be safe, check if the service is already known and deal with it accordingly.
+ NSArray<GNCEndpointId> *endpointIds = [_endpoints allKeysForObject:info];
+ if (endpointIds.count > 0) return;
+
+ // Add the newly discovered service to the list of services.
+ GNCEndpointId endpointId = [[NSUUID UUID] UUIDString];
+ _endpoints[endpointId] = info;
+
+ service.delegate = self;
+ [service resolveWithTimeout:0];
+}
+
+- (void)netServiceBrowser:(NSNetServiceBrowser *)browser
+ didRemoveService:(NSNetService *)service
+ moreComing:(BOOL)moreComing {
+ GTMLoggerDebug(@"Lost service: %@", service);
+ NSArray<GNCEndpointId> *endpointIds =
+ [_endpoints allKeysForObject:[GNCMNetServiceInfo infoWithService:service]];
+ NSAssert(endpointIds.count <= 1, @"Unexpected duplicate service");
+ if (endpointIds.count > 0) {
+ GNCEndpointId endpointId = endpointIds[0];
+ GNCMNetServiceInfo *info = _endpoints[endpointId];
+ [_endpoints removeObjectForKey:endpointId];
+ // Tail call to preserve reentrancy.
+ if (info.endpointLostHandler) {
+ info.endpointLostHandler();
+ }
+ }
+}
+
+#pragma mark NSNetServiceDelegate
+
+- (void)netServiceDidResolveAddress:(NSNetService *)service {
+ GTMLoggerDebug(@"Resolved service: %@ addresses: %@", service, service.addresses);
+
+ GNCMNetServiceInfo *info = [GNCMNetServiceInfo infoWithService:service];
+
+ NSArray<GNCEndpointId> *endpointIds = [_endpoints allKeysForObject:info];
+ if (endpointIds.count > 0) {
+ // Get TXTRecord data.
+ NSData *data = [service TXTRecordData];
+ NSDictionary<NSString *, NSData *> *TXTRecordData =
+ [NSNetService dictionaryFromTXTRecordData:data];
+
+ // The endpointLostHandler is returned from the endpointFoundHandler. The main benefit of this
+ // is that it allows rejection from the remote endpoint to be received by the local endpoint
+ // before the local endpoint has accepted or rejected.
+ info.endpointLostHandler = _endpointFoundHandler(
+ endpointIds[0], service.type, service.name, TXTRecordData,
+ ^(GNCMConnectionHandler connectionHandler) {
+ // A connection is requested, so resolve the service to get the I/O streams.
+ info.connectionHandler = connectionHandler;
+ if (info.connectionHandler) {
+ dispatch_sync(dispatch_get_main_queue(), ^{
+ NSInputStream *inputStream;
+ NSOutputStream *outputStream;
+ [info.service scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
+ [info.service getInputStream:&inputStream outputStream:&outputStream];
+ GNCMBonjourConnection *connection =
+ [[GNCMBonjourConnection alloc] initWithInputStream:inputStream
+ outputStream:outputStream
+ queue:nil];
+ connection.connectionHandlers = info.connectionHandler(connection);
+ });
+ }
+ });
+ _endpoints[endpointIds[0]] = info;
+ }
+}
+
+- (void)netService:(NSNetService *)service
+ didNotResolve:(NSDictionary<NSString *, NSNumber *> *)errorDict {
+ GTMLoggerDebug(@"Did not resolve service: %@", service);
+ NSArray<GNCEndpointId> *endpointIds =
+ [_endpoints allKeysForObject:[GNCMNetServiceInfo infoWithService:service]];
+ if (endpointIds.count > 0) {
+ _endpoints[endpointIds[0]].connectionHandler = nil;
+ }
+}
+
+@end
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourConnection.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourConnection.h
new file mode 100644
index 00000000000..e88ac9ee4ba
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourConnection.h
@@ -0,0 +1,38 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import <Foundation/Foundation.h>
+
+#import "internal/platform/implementation/ios/Source/Mediums/GNCMConnection.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ * This medium connection sends and receives payloads over the NSInputStream and NSOutputStream
+ * passed to it.
+ *
+ * @param inputStream The input stream to read from.
+ * @param outputStream The output stream to write to.
+ * @param queue The queue on which the GNCMConnection callbacks will be called. If nil, the main
+ * queue is used.
+ */
+@interface GNCMBonjourConnection : NSObject <GNCMConnection>
+@property(nonatomic) GNCMConnectionHandlers *connectionHandlers;
+
+- (instancetype)initWithInputStream:(NSInputStream *)inputStream
+ outputStream:(NSOutputStream *)outputStream
+ queue:(nullable dispatch_queue_t)queue;
+@end
+
+NS_ASSUME_NONNULL_END
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourConnection.m b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourConnection.m
new file mode 100644
index 00000000000..ae318843348
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourConnection.m
@@ -0,0 +1,224 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import "internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourConnection.h"
+
+#import "internal/platform/implementation/ios/Source/Mediums/GNCMConnection.h"
+#import "GoogleToolboxForMac/GTMLogger.h"
+
+enum { kMaxPacketSize = 32 * 1024 };
+
+@interface GNCMBonjourConnection () <NSStreamDelegate>
+@property(nonatomic) NSInputStream *inputStream;
+@property(nonatomic) NSOutputStream *outputStream;
+@property(nonatomic) dispatch_queue_t callbackQueue;
+
+@property(nonatomic, copy, nullable) NSData *dataBeingWritten;
+@property(nonatomic) NSInteger numberOfBytesLeftToWrite;
+@property(nonatomic, copy, nullable) GNCMProgressHandler progressHandler;
+@property(nonatomic, copy, nullable) GNCMPayloadResultHandler completion;
+
+@property(nonatomic) BOOL inputStreamOpen;
+@property(nonatomic) BOOL outputStreamOpen;
+@end
+
+@implementation GNCMBonjourConnection
+
+- (instancetype)initWithInputStream:(NSInputStream *)inputStream
+ outputStream:(NSOutputStream *)outputStream
+ queue:(nullable dispatch_queue_t)queue {
+ self = [super init];
+ if (self) {
+ _inputStreamOpen = NO;
+ _outputStreamOpen = NO;
+
+ _inputStream = inputStream;
+ _inputStream.delegate = self;
+ [_inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
+ [_inputStream open];
+
+ _outputStream = outputStream;
+ _outputStream.delegate = self;
+ [_outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
+ [_outputStream open];
+
+ _callbackQueue = queue;
+ }
+ return self;
+}
+
+- (void)dealloc {
+ [self closeStreams];
+}
+
+- (void)sendData:(NSData *)payload
+ progressHandler:(GNCMProgressHandler)progressHandler
+ completion:(GNCMPayloadResultHandler)completion {
+ if (_dataBeingWritten) {
+ GTMLoggerInfo(@"Attempting to send payload while one is already in flight");
+ [self dispatchCallback:^{
+ completion(GNCMPayloadResultFailure);
+ }];
+ return;
+ }
+
+ self.dataBeingWritten = payload;
+ self.numberOfBytesLeftToWrite = payload.length;
+ self.progressHandler = progressHandler;
+ self.completion = completion;
+ [self writeChunk];
+}
+
+#pragma mark NSStreamDelegate
+
+- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)event {
+ switch (event) {
+ case NSStreamEventHasBytesAvailable: {
+ // Data has arrived on the input stream.
+ NSAssert(stream == _inputStream, @"Error: Expected input stream");
+
+ if (_connectionHandlers.payloadHandler) {
+ uint8_t bytesRead[kMaxPacketSize];
+ NSInteger numberOfBytesRead;
+ @synchronized(self.inputStream) {
+ numberOfBytesRead = [self.inputStream read:bytesRead maxLength:kMaxPacketSize];
+ }
+ NSData *data = nil;
+ if (numberOfBytesRead > 0) {
+ GTMLoggerInfo(@"Read %lu bytes", (u_long)numberOfBytesRead);
+ data = [NSData dataWithBytes:bytesRead length:numberOfBytesRead];
+ }
+ [self dispatchCallback:^{
+ self.connectionHandlers.payloadHandler(data ?: [NSData data]);
+ }];
+ }
+ break;
+ }
+
+ case NSStreamEventHasSpaceAvailable:
+ // There is space available on the output stream.
+ NSAssert(stream == _outputStream, @"Error: Expected output stream");
+
+ // Schedule this in a future runloop cycle because -writeChunk, which can cause this event
+ // to be received synchronously, is not reentrant.
+ [self performSelector:@selector(writeChunk) withObject:nil afterDelay:0.0];
+ break;
+
+ case NSStreamEventErrorOccurred:
+ GTMLoggerInfo(@"Stream error: %@", [stream streamError]);
+ // Fall through.
+ case NSStreamEventEndEncountered: {
+ GTMLoggerInfo(@"Stream closing");
+ [self closeStreams];
+ if (_connectionHandlers.disconnectedHandler) {
+ [self dispatchCallback:^{
+ self.connectionHandlers.disconnectedHandler();
+ }];
+ }
+ break;
+ }
+
+ case NSStreamEventOpenCompleted:
+ if (stream == _inputStream) {
+ _inputStreamOpen = YES;
+ }
+ if (stream == _outputStream) {
+ _outputStreamOpen = YES;
+ }
+ // Schedule this in a future runloop cycle because -writeChunk, which can cause this event
+ // to be received synchronously, is not reentrant.
+ [self performSelector:@selector(writeChunk) withObject:nil afterDelay:0.0];
+ break;
+
+ case NSStreamEventNone:
+ default:
+ break;
+ }
+}
+
+#pragma mark Private
+
+// Calls a block on the callback queue.
+- (void)dispatchCallback:(dispatch_block_t)block {
+ dispatch_async(_callbackQueue ?: dispatch_get_main_queue(), block);
+}
+
+// Writes a chunk of the outgoing data to the output stream, calling the progress and completion
+// handlers as needed.
+- (void)writeChunk {
+ void (^reportProgress)(size_t) = ^(size_t count) {
+ // Captures the progress handler because the property is nilled out below.
+ GNCMProgressHandler progressHandler = _progressHandler;
+ if (progressHandler != nil) {
+ [self dispatchCallback:^{
+ progressHandler(count);
+ }];
+ }
+ };
+
+ void (^completed)(GNCMPayloadResult) = ^(GNCMPayloadResult result) {
+ reportProgress(_dataBeingWritten.length);
+ _progressHandler = nil;
+ _dataBeingWritten = nil;
+
+ // Captures the completion because the property is nilled out below.
+ GNCMPayloadResultHandler completion = _completion;
+ if (completion != nil) {
+ [self dispatchCallback:^{
+ completion(result);
+ }];
+ }
+ _completion = nil;
+ };
+
+ @synchronized(_outputStream) {
+ if (_inputStreamOpen && _outputStreamOpen && _numberOfBytesLeftToWrite) {
+ NSUInteger dataLength = (UInt32)_dataBeingWritten.length;
+ if (_numberOfBytesLeftToWrite == dataLength) {
+ GTMLoggerInfo(@"Starting a write operation of length %lu", (u_long)dataLength);
+ }
+ NSInteger numberOfPayloadBytesWritten =
+ [_outputStream write:&_dataBeingWritten.bytes[dataLength - _numberOfBytesLeftToWrite]
+ maxLength:_numberOfBytesLeftToWrite];
+
+ GTMLoggerInfo(@"Wrote %lu bytes", (u_long)numberOfPayloadBytesWritten);
+ if (numberOfPayloadBytesWritten >= 0) {
+ _numberOfBytesLeftToWrite -= numberOfPayloadBytesWritten;
+ reportProgress(_dataBeingWritten.length - _numberOfBytesLeftToWrite);
+ if (_numberOfBytesLeftToWrite < 0) {
+ GTMLoggerInfo(@"Unexpected number of bytes written");
+ _numberOfBytesLeftToWrite = 0;
+ }
+ if (_numberOfBytesLeftToWrite == 0) completed(GNCMPayloadResultSuccess);
+ } else {
+ GTMLoggerInfo(@"Error writing to output stream");
+ completed(GNCMPayloadResultFailure);
+ }
+ }
+ }
+}
+
+- (void)closeStreams {
+ @synchronized(_inputStream) {
+ [_inputStream close];
+ _inputStream = nil;
+ }
+
+ @synchronized(_outputStream) {
+ [_outputStream close];
+ _outputStream = nil;
+ }
+}
+
+@end
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourService.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourService.h
new file mode 100644
index 00000000000..bdb31d26c86
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourService.h
@@ -0,0 +1,48 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import <Foundation/Foundation.h>
+
+#import "internal/platform/implementation/ios/Source/Mediums/GNCMConnection.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ * GNCMBonjourService publishes mDNS type and domain with the specified service ID via Apple
+ * Bonjour service. The mDNS type is a string formatted as "_[serviceIdHash]._tcp." in which
+ * [serviceIdHash] is generated as a SHA-256 hash from the service ID and taken the 6 first bytes
+ * of string in upper case.
+ * When the service connects, the specified |endpointConnectedHandler| is called, which establishes
+ * a connection to the browser.
+ *
+ * Don't hold the strong reference of caller self in endpointConnectedHandler to ensure there is no
+ * retain cycle between them.
+ *
+ * @param serviceName A service name that embeds the |WifiLanServiceInfo| information.
+ * @param serviceType An mDNS type that uniquely identifies the published service to search for.
+ * @param port The requesting socket port number.
+ * @param txtRecordData The TXTRecord data.
+ * @param endpointConnectedHandler The handler that is called when a browser connects.
+ */
+@interface GNCMBonjourService : NSObject
+
+- (instancetype)initWithServiceName:(NSString *)serviceName
+ serviceType:(NSString *)serviceType
+ port:(NSInteger)port
+ TXTRecordData:(NSDictionary<NSString *, NSData *> *)TXTRecordData
+ endpointConnectedHandler:(GNCMConnectionHandler)handler;
+
+@end
+
+NS_ASSUME_NONNULL_END
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourService.m b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourService.m
new file mode 100644
index 00000000000..aa2176fd221
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourService.m
@@ -0,0 +1,88 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import "internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourService.h"
+
+#import "internal/platform/implementation/ios/Source/Mediums/GNCMConnection.h"
+#import "internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourConnection.h"
+#import "internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourUtils.h"
+#import "GoogleToolboxForMac/GTMLogger.h"
+
+@interface GNCMBonjourService () <NSNetServiceDelegate>
+
+@property(nonatomic, copy) NSString *serviceName;
+@property(nonatomic, copy) NSString *serviceType;
+@property(nonatomic, copy) GNCMConnectionHandler endpointConnectedHandler;
+
+@property(nonatomic) NSNetService *netService;
+
+@end
+
+@implementation GNCMBonjourService
+
+- (instancetype)initWithServiceName:(NSString *)serviceName
+ serviceType:(NSString *)serviceType
+ port:(NSInteger)port
+ TXTRecordData:(NSDictionary<NSString *, NSData *> *)TXTRecordData
+ endpointConnectedHandler:(GNCMConnectionHandler)handler {
+ self = [super init];
+ if (self) {
+ _serviceName = [serviceName copy];
+ _serviceType = [serviceType copy];
+ _endpointConnectedHandler = handler;
+
+ _netService = [[NSNetService alloc] initWithDomain:GNCMBonjourDomain
+ type:_serviceType
+ name:_serviceName
+ port:port];
+ [_netService setTXTRecordData:[NSNetService dataFromTXTRecordDictionary:TXTRecordData]];
+
+ _netService.delegate = self;
+ [_netService scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
+ [_netService publishWithOptions:NSNetServiceListenForConnections];
+ }
+ return self;
+}
+
+- (void)dealloc {
+ [_netService stop];
+}
+
+#pragma mark NSNetServiceDelegate
+
+- (void)netServiceDidPublish:(NSNetService *)service {
+ GTMLoggerDebug(@"Did publish service: %@", service);
+}
+
+- (void)netService:(NSNetService *)service
+ didNotPublish:(NSDictionary<NSString *, NSNumber *> *)errorDict {
+ GTMLoggerDebug(@"Error publishing: service: %@, errorDic: %@", service, errorDict);
+}
+
+- (void)netServiceDidStop:(NSNetService *)service {
+ GTMLoggerDebug(@"Stopped publishing service: %@", service);
+}
+
+- (void)netService:(NSNetService *)service
+ didAcceptConnectionWithInputStream:(NSInputStream *)inputStream
+ outputStream:(NSOutputStream *)outputStream {
+ GTMLoggerDebug(@"Accepted connection, service: %@", service);
+ GNCMBonjourConnection *connection =
+ [[GNCMBonjourConnection alloc] initWithInputStream:inputStream
+ outputStream:outputStream
+ queue:nil];
+ connection.connectionHandlers = _endpointConnectedHandler(connection);
+}
+
+@end
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourUtils.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourUtils.h
new file mode 100644
index 00000000000..e314dec6295
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourUtils.h
@@ -0,0 +1,18 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import <Foundation/Foundation.h>
+
+// mDNS domain.
+FOUNDATION_EXPORT NSString *_Nonnull const GNCMBonjourDomain;
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourUtils.m b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourUtils.m
new file mode 100644
index 00000000000..6f51015594d
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourUtils.m
@@ -0,0 +1,17 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import "internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourUtils.h"
+
+NSString *const GNCMBonjourDomain = @"local";
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/BUILD b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/BUILD
new file mode 100644
index 00000000000..b739c1708d4
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/BUILD
@@ -0,0 +1,94 @@
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+licenses(["notice"])
+
+package(default_visibility = ["//internal/platform/implementation/ios:__subpackages__"])
+
+objc_library(
+ name = "Platform",
+ srcs = [
+ "crypto.mm",
+ "input_file.mm",
+ "log_message.mm",
+ "multi_thread_executor.mm",
+ "scheduled_executor.mm",
+ "utils.mm",
+ "wifi_lan.mm",
+ ],
+ hdrs = [
+ "input_file.h",
+ "log_message.h",
+ "multi_thread_executor.h",
+ "scheduled_executor.h",
+ "single_thread_executor.h",
+ "utils.h",
+ "wifi_lan.h",
+ ],
+ sdk_frameworks = [
+ "CoreBluetooth",
+ "CoreFoundation",
+ ],
+ deps = [
+ ":Platform_cc",
+ "//internal/platform/implementation:platform",
+ "//internal/platform/implementation:types",
+ "//internal/platform/implementation/ios/Source/Mediums",
+ "//internal/platform/implementation/ios/Source/Shared",
+ "//internal/platform/implementation/shared:file",
+ "//third_party/objective_c/google_toolbox_for_mac:GTM_Logger",
+ ],
+)
+
+cc_library(
+ name = "Platform_cc",
+ srcs = [
+ "condition_variable.cc",
+ "count_down_latch.cc",
+ "system_clock.cc",
+ ],
+ hdrs = [
+ "atomic_boolean.h",
+ "atomic_uint32.h",
+ "condition_variable.h",
+ "count_down_latch.h",
+ "mutex.h",
+ ],
+ deps = [
+ "//internal/platform/implementation:platform",
+ "//internal/platform/implementation:types",
+ "@com_google_absl//absl/strings:str_format",
+ "@com_google_absl//absl/synchronization",
+ "@com_google_absl//absl/time",
+ ],
+)
+
+cc_test(
+ name = "Platform_cc_test",
+ srcs = [
+ "atomic_boolean_test.cc",
+ "atomic_uint32_test.cc",
+ "condition_variable_test.cc",
+ "count_down_latch_test.cc",
+ "mutex_test.cc",
+ ],
+ shard_count = 16,
+ deps = [
+ ":Platform_cc",
+ "@com_github_protobuf_matchers//protobuf-matchers",
+ "@com_google_absl//absl/synchronization",
+ "@com_google_absl//absl/time",
+ "@com_google_googletest//:gtest_main",
+ "@com_google_nisaba//nisaba/port:thread_pool/fiber",
+ ],
+)
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/atomic_boolean.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/atomic_boolean.h
new file mode 100644
index 00000000000..ed3bbeebbf2
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/atomic_boolean.h
@@ -0,0 +1,46 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_IOS_ATOMIC_BOOLEAN_H_
+#define PLATFORM_IMPL_IOS_ATOMIC_BOOLEAN_H_
+
+#include <atomic>
+
+#include "internal/platform/implementation/atomic_boolean.h"
+
+namespace location {
+namespace nearby {
+namespace ios {
+
+// Concrete AtomicBoolean implementation.
+class AtomicBoolean : public api::AtomicBoolean {
+ public:
+ explicit AtomicBoolean(bool initial_value) : value_(initial_value) {}
+ ~AtomicBoolean() override = default;
+
+ AtomicBoolean(const AtomicBoolean&) = delete;
+ AtomicBoolean& operator=(const AtomicBoolean&) = delete;
+
+ bool Get() const override { return value_.load(); }
+ bool Set(bool value) override { return value_.exchange(value); }
+
+ private:
+ std::atomic_bool value_;
+};
+
+} // namespace ios
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_IOS_ATOMIC_BOOLEAN_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/atomic_boolean_test.cc b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/atomic_boolean_test.cc
new file mode 100644
index 00000000000..ed4c611db9d
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/atomic_boolean_test.cc
@@ -0,0 +1,78 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/ios/Source/Platform/atomic_boolean.h"
+
+#include "gtest/gtest.h"
+#include "thread/fiber/fiber.h"
+
+namespace location {
+namespace nearby {
+namespace ios {
+namespace {
+
+TEST(AtomicBooleanTest, SetOnSameThread) {
+ AtomicBoolean atomic_boolean_{false};
+
+ EXPECT_EQ(false, atomic_boolean_.Get());
+
+ atomic_boolean_.Set(true);
+ EXPECT_EQ(true, atomic_boolean_.Get());
+}
+
+TEST(AtomicBooleanTest, MultipleSetGetOnSameThread) {
+ AtomicBoolean atomic_boolean_{false};
+
+ EXPECT_EQ(false, atomic_boolean_.Get());
+
+ atomic_boolean_.Set(true);
+ EXPECT_EQ(true, atomic_boolean_.Get());
+
+ atomic_boolean_.Set(true);
+ EXPECT_EQ(true, atomic_boolean_.Get());
+
+ atomic_boolean_.Set(false);
+ EXPECT_EQ(false, atomic_boolean_.Get());
+
+ atomic_boolean_.Set(true);
+ EXPECT_EQ(true, atomic_boolean_.Get());
+}
+
+TEST(AtomicBooleanTest, SetOnNewThread) {
+ AtomicBoolean atomic_boolean_{false};
+
+ EXPECT_EQ(false, atomic_boolean_.Get());
+
+ thread::Fiber f([&] { atomic_boolean_.Set(true); });
+ f.Join();
+
+ EXPECT_EQ(true, atomic_boolean_.Get());
+}
+
+TEST(AtomicBooleanTest, GetOnNewThread) {
+ AtomicBoolean atomic_boolean_{false};
+
+ EXPECT_EQ(false, atomic_boolean_.Get());
+
+ atomic_boolean_.Set(true);
+ EXPECT_EQ(true, atomic_boolean_.Get());
+
+ thread::Fiber f([&] { EXPECT_EQ(true, atomic_boolean_.Get()); });
+ f.Join();
+}
+
+} // namespace
+} // namespace ios
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/atomic_uint32.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/atomic_uint32.h
new file mode 100644
index 00000000000..d9eb3acd487
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/atomic_uint32.h
@@ -0,0 +1,47 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_IOS_ATOMIC_UINT32_H_
+#define PLATFORM_IMPL_IOS_ATOMIC_UINT32_H_
+
+#include <atomic>
+#include <cstdint>
+
+#include "internal/platform/implementation/atomic_reference.h"
+
+namespace location {
+namespace nearby {
+namespace ios {
+
+// Concrete AtomicUint32 implementation.
+class AtomicUint32 : public api::AtomicUint32 {
+ public:
+ explicit AtomicUint32(std::uint32_t initial_value) : value_(initial_value) {}
+ ~AtomicUint32() override = default;
+
+ AtomicUint32(const AtomicUint32&) = delete;
+ AtomicUint32& operator=(const AtomicUint32&) = delete;
+
+ std::uint32_t Get() const override { return value_; }
+ void Set(std::uint32_t value) override { value_ = value; }
+
+ private:
+ std::atomic<std::uint32_t> value_;
+};
+
+} // namespace ios
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_IOS_ATOMIC_UINT32_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/atomic_uint32_test.cc b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/atomic_uint32_test.cc
new file mode 100644
index 00000000000..7893f3c2c1c
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/atomic_uint32_test.cc
@@ -0,0 +1,64 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/ios/Source/Platform/atomic_uint32.h"
+
+#include "gtest/gtest.h"
+#include "thread/fiber/fiber.h"
+
+namespace location {
+namespace nearby {
+namespace ios {
+namespace {
+
+TEST(AtomicUint32Test, GetOnSameThread) {
+ std::uint32_t initial_value = 1450;
+ AtomicUint32 atomic_reference_{initial_value};
+
+ EXPECT_EQ(initial_value, atomic_reference_.Get());
+}
+
+TEST(AtomicUint32Test, SetGetOnSameThread) {
+ std::uint32_t initial_value_ = 1450;
+ AtomicUint32 atomic_reference_{initial_value_};
+
+ std::uint32_t new_value = 28;
+ atomic_reference_.Set(new_value);
+ EXPECT_EQ(new_value, atomic_reference_.Get());
+}
+
+TEST(AtomicUint32Test, SetOnNewThread) {
+ std::uint32_t initial_value_ = 1450;
+ AtomicUint32 atomic_reference_{initial_value_};
+
+ std::uint32_t new_thread_value = 28;
+ thread::Fiber f([&] { atomic_reference_.Set(new_thread_value); });
+ f.Join();
+ EXPECT_EQ(new_thread_value, atomic_reference_.Get());
+}
+
+TEST(AtomicUint32Test, GetOnNewThread) {
+ std::uint32_t initial_value_ = 1450;
+ AtomicUint32 atomic_reference_{initial_value_};
+
+ std::uint32_t new_value = 28;
+ atomic_reference_.Set(new_value);
+ thread::Fiber f([&] { EXPECT_EQ(new_value, atomic_reference_.Get()); });
+ f.Join();
+}
+
+} // namespace
+} // namespace ios
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/condition_variable.cc b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/condition_variable.cc
new file mode 100644
index 00000000000..8ad8752e0ac
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/condition_variable.cc
@@ -0,0 +1,37 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/ios/Source/Platform/condition_variable.h"
+
+#include "internal/platform/implementation/ios/Source/Platform/mutex.h"
+
+namespace location {
+namespace nearby {
+namespace ios {
+
+Exception ConditionVariable::Wait() {
+ condition_variable_.Wait(mutex_);
+ return {Exception::kSuccess};
+}
+
+Exception ConditionVariable::Wait(absl::Duration timeout) {
+ condition_variable_.WaitWithTimeout(mutex_, timeout);
+ return {Exception::kSuccess};
+}
+
+void ConditionVariable::Notify() { condition_variable_.SignalAll(); }
+
+} // namespace ios
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/condition_variable.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/condition_variable.h
new file mode 100644
index 00000000000..65486ff59b0
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/condition_variable.h
@@ -0,0 +1,48 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_IOS_CONDITION_VARIABLE_H_
+#define PLATFORM_IMPL_IOS_CONDITION_VARIABLE_H_
+
+#include "absl/synchronization/mutex.h"
+#include "internal/platform/implementation/condition_variable.h"
+#include "internal/platform/implementation/ios/Source/Platform/mutex.h"
+
+namespace location {
+namespace nearby {
+namespace ios {
+
+// Concrete ConditionVariable implementation.
+class ConditionVariable : public api::ConditionVariable {
+ public:
+ explicit ConditionVariable(ios::Mutex* mutex) : mutex_(&mutex->mutex_) {}
+ ~ConditionVariable() override = default;
+
+ ConditionVariable(const ConditionVariable&) = delete;
+ ConditionVariable& operator=(const ConditionVariable&) = delete;
+
+ Exception Wait() override;
+ Exception Wait(absl::Duration timeout) override;
+ void Notify() override;
+
+ private:
+ absl::Mutex* mutex_;
+ absl::CondVar condition_variable_;
+};
+
+} // namespace ios
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_IOS_CONDITION_VARIABLE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/condition_variable_test.cc b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/condition_variable_test.cc
new file mode 100644
index 00000000000..7d36f8641d7
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/condition_variable_test.cc
@@ -0,0 +1,84 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/ios/Source/Platform/condition_variable.h"
+
+#include "gtest/gtest.h"
+#include "absl/time/clock.h"
+#include "internal/platform/implementation/ios/Source/Platform/mutex.h"
+#include "thread/fiber/fiber.h"
+
+namespace location {
+namespace nearby {
+namespace ios {
+namespace {
+
+TEST(ConditionVariableTest, CanCreate) {
+ Mutex mutex{};
+ ConditionVariable cond{&mutex};
+}
+
+TEST(ConditionVariableTest, CanWakeupWaiter) {
+ Mutex mutex{};
+ ConditionVariable cond{&mutex};
+ bool done = false;
+ bool waiting = false;
+ {
+ thread::Fiber f([&cond, &mutex, &done, &waiting] {
+ mutex.Lock();
+ waiting = true;
+ cond.Wait();
+ waiting = false;
+ done = true;
+ mutex.Unlock();
+ });
+ while (true) {
+ {
+ mutex.Lock();
+ if (waiting) {
+ mutex.Unlock();
+ break;
+ }
+ mutex.Unlock();
+ }
+ absl::SleepFor(absl::Milliseconds(100));
+ }
+ {
+ mutex.Lock();
+ cond.Notify();
+ EXPECT_FALSE(done);
+ mutex.Unlock();
+ }
+ f.Join();
+ }
+ EXPECT_TRUE(done);
+}
+
+TEST(ConditionVariableTest, WaitTerminatesOnTimeoutWithoutNotify) {
+ Mutex mutex{};
+ ConditionVariable cond{&mutex};
+ mutex.Lock();
+
+ const absl::Duration kWaitTime = absl::Milliseconds(100);
+ absl::Time start = absl::Now();
+ cond.Wait(kWaitTime);
+ absl::Duration duration = absl::Now() - start;
+ EXPECT_GE(duration, kWaitTime);
+ mutex.Unlock();
+}
+
+} // namespace
+} // namespace ios
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/count_down_latch.cc b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/count_down_latch.cc
new file mode 100644
index 00000000000..9fce8728ba3
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/count_down_latch.cc
@@ -0,0 +1,40 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/ios/Source/Platform/count_down_latch.h"
+
+namespace location {
+namespace nearby {
+namespace ios {
+
+Exception CountDownLatch::Await() {
+ absl::MutexLock lock(&mutex_, absl::Condition(IsZeroOrNegative, &count_));
+ return {Exception::kSuccess};
+}
+
+ExceptionOr<bool> CountDownLatch::Await(absl::Duration timeout) {
+ bool condition = mutex_.LockWhenWithTimeout(
+ absl::Condition(IsZeroOrNegative, &count_), timeout);
+ mutex_.Unlock();
+ return ExceptionOr<bool>(condition);
+}
+
+void CountDownLatch::CountDown() {
+ absl::MutexLock lock(&mutex_);
+ count_--;
+}
+
+} // namespace ios
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/count_down_latch.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/count_down_latch.h
new file mode 100644
index 00000000000..e5fcd6be20b
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/count_down_latch.h
@@ -0,0 +1,49 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_IOS_COUNT_DOWN_LATCH_H_
+#define PLATFORM_IMPL_IOS_COUNT_DOWN_LATCH_H_
+
+#include "absl/synchronization/mutex.h"
+#include "internal/platform/implementation/count_down_latch.h"
+
+namespace location {
+namespace nearby {
+namespace ios {
+
+// Concrete CountDownLatch implementation.
+class CountDownLatch : public api::CountDownLatch {
+ public:
+ explicit CountDownLatch(int count) : count_(count) {}
+ ~CountDownLatch() override = default;
+
+ CountDownLatch(const CountDownLatch&) = delete;
+ CountDownLatch& operator=(const CountDownLatch&) = delete;
+
+ Exception Await() override;
+ ExceptionOr<bool> Await(absl::Duration timeout) override;
+ void CountDown() override;
+
+ private:
+ static bool IsZeroOrNegative(int* count) { return 0 >= *count; }
+
+ absl::Mutex mutex_;
+ int count_ ABSL_GUARDED_BY(mutex_);
+};
+
+} // namespace ios
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_IOS_COUNT_DOWN_LATCH_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/count_down_latch_test.cc b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/count_down_latch_test.cc
new file mode 100644
index 00000000000..2122bdedeb6
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/count_down_latch_test.cc
@@ -0,0 +1,83 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/ios/Source/Platform/count_down_latch.h"
+
+#include "gtest/gtest.h"
+#include "thread/fiber/fiber.h"
+
+namespace location {
+namespace nearby {
+namespace ios {
+namespace {
+
+TEST(CountDownLatchTest, LatchAwaitCanWait) {
+ CountDownLatch latch(1);
+ std::atomic_bool done = false;
+
+ thread::Fiber f([&done, &latch] {
+ done = true;
+ latch.CountDown();
+ });
+ f.Join();
+
+ latch.Await();
+ EXPECT_TRUE(done);
+}
+
+TEST(CountDownLatchTest, LatchExtraCountDownIgnored) {
+ CountDownLatch latch(1);
+ std::atomic_bool done = false;
+
+ thread::Fiber f([&done, &latch] {
+ done = true;
+ latch.CountDown();
+ latch.CountDown();
+ latch.CountDown();
+ });
+ f.Join();
+
+ latch.Await();
+ EXPECT_TRUE(done);
+}
+
+TEST(CountDownLatchTest, LatchAwaitWithTimeoutCanExpire) {
+ CountDownLatch latch(1);
+
+ auto response = latch.Await(absl::Milliseconds(100));
+
+ EXPECT_TRUE(response.ok());
+ EXPECT_FALSE(response.result());
+}
+
+TEST(CountDownLatchTest, InitialCountZero_AwaitDoesNotBlock) {
+ CountDownLatch latch(0);
+
+ auto response = latch.Await();
+
+ EXPECT_TRUE(response.Ok());
+}
+
+TEST(CountDownLatchTest, InitialCountNegative_AwaitDoesNotBlock) {
+ CountDownLatch latch(-1);
+
+ auto response = latch.Await();
+
+ EXPECT_TRUE(response.Ok());
+}
+
+} // namespace
+} // namespace ios
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/crypto.mm b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/crypto.mm
new file mode 100644
index 00000000000..004cd56f561
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/crypto.mm
@@ -0,0 +1,39 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/crypto.h"
+
+#import "absl/strings/string_view.h"
+#import "internal/platform/implementation/ios/Source/Platform/utils.h"
+#import "internal/platform/implementation/ios/Source/Shared/GNCUtils.h"
+
+namespace location {
+namespace nearby {
+
+void Crypto::Init() {}
+
+ByteArray Crypto::Md5(absl::string_view input) {
+ if (input.empty()) return ByteArray();
+
+ return ByteArrayFromNSData(GNCMd5String(ObjCStringFromCppString(input)));
+}
+
+ByteArray Crypto::Sha256(absl::string_view input) {
+ if (input.empty()) return ByteArray();
+
+ return ByteArrayFromNSData(GNCSha256String(ObjCStringFromCppString(input)));
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/input_file.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/input_file.h
new file mode 100644
index 00000000000..6ccd59f78ef
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/input_file.h
@@ -0,0 +1,48 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_IOS_INPUT_FILE_H_
+#define PLATFORM_IMPL_IOS_INPUT_FILE_H_
+
+#import <Foundation/Foundation.h>
+
+#include "internal/platform/implementation/input_file.h"
+
+namespace location {
+namespace nearby {
+namespace ios {
+
+/** This InputFile subclass takes input from an NSURL. */
+class InputFile : public api::InputFile {
+ public:
+ explicit InputFile(NSURL *nsURL);
+ ~InputFile() override = default;
+ InputFile(InputFile &&) = default;
+ InputFile &operator=(InputFile &&) = default;
+
+ ExceptionOr<ByteArray> Read(std::int64_t size) override;
+ std::string GetFilePath() const override;
+ std::int64_t GetTotalSize() const override;
+ Exception Close() override;
+
+ private:
+ NSURL *nsURL_;
+ NSInputStream *nsStream_;
+};
+
+} // namespace ios
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_IOS_INPUT_FILE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/input_file.mm b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/input_file.mm
new file mode 100644
index 00000000000..532f7e3461f
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/input_file.mm
@@ -0,0 +1,69 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import "internal/platform/implementation/ios/Source/Platform/input_file.h"
+
+#include <string>
+
+#import "internal/platform/exception.h"
+#import "internal/platform/implementation/ios/Source/Platform/utils.h"
+
+namespace location {
+namespace nearby {
+namespace ios {
+
+InputFile::InputFile(NSURL *nsURL) : nsURL_(nsURL) {
+ std::string string = CppStringFromObjCString([nsURL_ absoluteString]);
+ nsStream_ = [NSInputStream inputStreamWithURL:nsURL_];
+ [nsStream_ scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
+ [nsStream_ open];
+}
+
+ExceptionOr<ByteArray> InputFile::Read(std::int64_t size) {
+ uint8_t *bytes_read = new uint8_t[size];
+ NSUInteger numberOfBytesToRead = [[NSNumber numberWithLongLong:size] unsignedIntegerValue];
+ NSInteger numberOfBytesRead = [nsStream_ read:bytes_read maxLength:numberOfBytesToRead];
+ if (numberOfBytesRead == 0) {
+ // Reached end of stream.
+ return ExceptionOr<ByteArray>();
+ } else if (numberOfBytesRead < 0) {
+ // Stream error.
+ return ExceptionOr<ByteArray>(Exception::kIo);
+ }
+ return ExceptionOr<ByteArray>(ByteArrayFromNSData([NSData dataWithBytes:bytes_read
+ length:numberOfBytesRead]));
+}
+
+std::string InputFile::GetFilePath() const {
+ return CppStringFromObjCString([nsURL_ absoluteString]);
+}
+
+std::int64_t InputFile::GetTotalSize() const {
+ NSNumber *fileSizeValue = nil;
+ BOOL result = [nsURL_ getResourceValue:&fileSizeValue forKey:NSURLFileSizeKey error:nil];
+ if (result) {
+ return fileSizeValue.longValue;
+ } else {
+ return 0;
+ }
+}
+
+Exception InputFile::Close() {
+ [nsStream_ close];
+ return {Exception::kSuccess};
+}
+
+} // namespace ios
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/log_message.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/log_message.h
new file mode 100644
index 00000000000..03e3dc1c593
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/log_message.h
@@ -0,0 +1,47 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_IOS_LOG_MESSAGE_H_
+#define PLATFORM_IMPL_IOS_LOG_MESSAGE_H_
+
+#include "glog/logging.h"
+#include "internal/platform/implementation/log_message.h"
+
+namespace location {
+namespace nearby {
+namespace ios {
+
+// Concrete LogMessage implementation
+class LogMessage : public api::LogMessage {
+ public:
+ LogMessage(const char* file, int line, Severity severity);
+ ~LogMessage() override = default;
+
+ LogMessage(const LogMessage&) = delete;
+ LogMessage& operator=(const LogMessage&) = delete;
+
+ void Print(const char* format, ...) override;
+
+ std::ostream& Stream() override;
+
+ private:
+ google::LogMessage log_streamer_;
+ api::LogMessage::Severity severity_;
+};
+
+} // namespace ios
+} // namespace nearby
+} // namespace location
+
+#endif // IPHONE_SHARED_NEARBY_CONNECTIONS_SOURCE_PLATFORM_LOG_MESSAGE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/log_message.mm b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/log_message.mm
new file mode 100644
index 00000000000..c3772da2191
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/log_message.mm
@@ -0,0 +1,87 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/ios/Source/Platform/log_message.h"
+
+#include "glog/logging.h"
+#include "internal/platform/implementation/log_message.h"
+#include "GoogleToolboxForMac/GTMLogger.h"
+
+namespace location {
+namespace nearby {
+namespace ios {
+
+api::LogMessage::Severity gMinLogSeverity = api::LogMessage::Severity::kInfo;
+
+GTMLoggerLevel ConvertSeverity(api::LogMessage::Severity severity) {
+ switch (severity) {
+ case api::LogMessage::Severity::kVerbose:
+ return kGTMLoggerLevelDebug;
+ case api::LogMessage::Severity::kInfo:
+ return kGTMLoggerLevelInfo;
+ case api::LogMessage::Severity::kWarning:
+ return kGTMLoggerLevelInfo;
+ case api::LogMessage::Severity::kError:
+ return kGTMLoggerLevelError;
+ case api::LogMessage::Severity::kFatal:
+ return kGTMLoggerLevelAssert;
+ }
+}
+
+LogMessage::LogMessage(const char* file, int line, Severity severity)
+ : log_streamer_(ConvertSeverity(severity), file, line), severity_(severity) {}
+
+void LogMessage::Print(const char* format, ...) {
+ va_list ap;
+ va_start(ap, format);
+ switch (ConvertSeverity(severity_)) {
+ case kGTMLoggerLevelDebug:
+ [[GTMLogger sharedLogger] logDebug:[NSString stringWithUTF8String:format], ap];
+ break;
+ case kGTMLoggerLevelInfo:
+ [[GTMLogger sharedLogger] logInfo:[NSString stringWithUTF8String:format], ap];
+ break;
+ case kGTMLoggerLevelError:
+ [[GTMLogger sharedLogger] logError:[NSString stringWithUTF8String:format], ap];
+ break;
+ case kGTMLoggerLevelAssert:
+ [[GTMLogger sharedLogger] logAssert:[NSString stringWithUTF8String:format], ap];
+ break;
+ case kGTMLoggerLevelUnknown:
+ // no-op
+ break;
+ }
+}
+
+// TODO(b/169292092): GTMLogger doesn't support stream. Temporarily use absl LogStreamer to make
+// build pass.
+std::ostream& LogMessage::Stream() { return log_streamer_.stream(); }
+
+} // namespace ios
+
+namespace api {
+
+// static
+void LogMessage::SetMinLogSeverity(Severity severity) { ios::gMinLogSeverity = severity; }
+
+// static
+bool LogMessage::ShouldCreateLogMessage(Severity severity) {
+ // TODO(b/169292092): GTMLogger doesn't support stream which cause crash. Temporarily turn off
+ // LogMessage.
+ return false;
+}
+
+} // namespace api
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/multi_thread_executor.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/multi_thread_executor.h
new file mode 100644
index 00000000000..1a371580034
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/multi_thread_executor.h
@@ -0,0 +1,47 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_IOS_MULTI_THREAD_EXECUTOR_H_
+#define PLATFORM_IMPL_IOS_MULTI_THREAD_EXECUTOR_H_
+
+#include "internal/platform/implementation/submittable_executor.h"
+#import "internal/platform/runnable.h"
+#import "internal/platform/implementation/ios/Source/Platform/scheduled_executor.h"
+
+namespace location {
+namespace nearby {
+namespace ios {
+
+class MultiThreadExecutor : public api::SubmittableExecutor {
+ public:
+ explicit MultiThreadExecutor(int max_concurrency);
+ ~MultiThreadExecutor() override = default;
+
+ MultiThreadExecutor(const MultiThreadExecutor&) = delete;
+ MultiThreadExecutor& operator=(const MultiThreadExecutor&) = delete;
+
+ // api::SubmittableExecutor:
+ void Shutdown() override;
+ void Execute(Runnable&& runnable) override;
+ bool DoSubmit(Runnable&& runnable) override;
+
+ private:
+ std::unique_ptr<ScheduledExecutor> scheduled_executor_;
+};
+
+} // namespace ios
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_IOS_MULTI_THREAD_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/multi_thread_executor.mm b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/multi_thread_executor.mm
new file mode 100644
index 00000000000..e4a38712232
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/multi_thread_executor.mm
@@ -0,0 +1,40 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import "internal/platform/implementation/ios/Source/Platform/multi_thread_executor.h"
+
+#import "internal/platform/implementation/ios/Source/Platform/scheduled_executor.h"
+#include "internal/platform/runnable.h"
+
+namespace location {
+namespace nearby {
+namespace ios {
+
+MultiThreadExecutor::MultiThreadExecutor(int max_concurrency) {
+ scheduled_executor_ = std::make_unique<ScheduledExecutor>(max_concurrency);
+}
+
+void MultiThreadExecutor::Shutdown() { scheduled_executor_->Shutdown(); }
+
+void MultiThreadExecutor::Execute(Runnable&& runnable) {
+ scheduled_executor_->Execute(std::move(runnable));
+}
+
+bool MultiThreadExecutor::DoSubmit(Runnable&& runnable) {
+ return scheduled_executor_->DoSubmit(std::move(runnable));
+}
+
+} // namespace ios
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/mutex.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/mutex.h
new file mode 100644
index 00000000000..b60484d4cd0
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/mutex.h
@@ -0,0 +1,84 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_IOS_MUTEX_H_
+#define PLATFORM_IMPL_IOS_MUTEX_H_
+
+#include "absl/synchronization/mutex.h"
+#include "internal/platform/implementation/mutex.h"
+
+namespace location {
+namespace nearby {
+namespace ios {
+
+// Concrete Mutex implementation.
+class ABSL_LOCKABLE Mutex : public api::Mutex {
+ public:
+ explicit Mutex() {}
+ ~Mutex() override = default;
+
+ Mutex(const Mutex&) = delete;
+ Mutex& operator=(const Mutex&) = delete;
+
+ void Lock() ABSL_EXCLUSIVE_LOCK_FUNCTION() override {
+ mutex_.Lock();
+ mutex_.ForgetDeadlockInfo();
+ }
+ void Unlock() ABSL_UNLOCK_FUNCTION() override { mutex_.Unlock(); }
+
+ private:
+ friend class ConditionVariable;
+ absl::Mutex mutex_;
+};
+
+class ABSL_LOCKABLE RecursiveMutex : public api::Mutex {
+ public:
+ RecursiveMutex() = default;
+ ~RecursiveMutex() override = default;
+
+ RecursiveMutex(RecursiveMutex&&) = delete;
+ RecursiveMutex& operator=(RecursiveMutex&&) = delete;
+
+ void Lock() ABSL_EXCLUSIVE_LOCK_FUNCTION() override {
+ intptr_t thread_id = ThreadId();
+ if (thread_id_.load(std::memory_order_acquire) != thread_id) {
+ mutex_.Lock();
+ thread_id_.store(thread_id, std::memory_order_release);
+ }
+ ++count_;
+ }
+
+ void Unlock() ABSL_UNLOCK_FUNCTION() override {
+ if (--count_ == 0) {
+ thread_id_.store(0, std::memory_order_release);
+ mutex_.Unlock();
+ }
+ }
+
+ private:
+ static inline intptr_t ThreadId() {
+ ABSL_CONST_INIT thread_local int per_thread = 0;
+ return reinterpret_cast<intptr_t>(&per_thread);
+ }
+
+ std::atomic<intptr_t> thread_id_{0};
+ int count_{0};
+ absl::Mutex mutex_;
+};
+
+} // namespace ios
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_IOS_MUTEX_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/mutex_test.cc b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/mutex_test.cc
new file mode 100644
index 00000000000..5c5a9dbe380
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/mutex_test.cc
@@ -0,0 +1,92 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/ios/Source/Platform/mutex.h"
+
+#include "gtest/gtest.h"
+#include "absl/synchronization/mutex.h"
+#include "absl/synchronization/notification.h"
+#include "absl/time/clock.h"
+#include "absl/time/time.h"
+#include "thread/fiber/fiber.h"
+
+namespace location {
+namespace nearby {
+namespace ios {
+namespace {
+
+static const absl::Duration kTimeToWait = absl::Milliseconds(500);
+
+TEST(MutexTest, LockOnce_UnlockOnce) {
+ Mutex test_mutex_1{};
+ test_mutex_1.Lock();
+ test_mutex_1.Unlock();
+
+ RecursiveMutex test_mutex_2;
+ test_mutex_2.Lock();
+ test_mutex_2.Unlock();
+}
+
+TEST(MutexTest, BasicLockingWorks) {
+ absl::Notification lock_obtained;
+ Mutex test_mutex{};
+ test_mutex.Lock();
+ thread::Fiber f([&test_mutex, &lock_obtained] {
+ test_mutex.Lock();
+ test_mutex.Unlock();
+ lock_obtained.Notify();
+ });
+ EXPECT_FALSE(lock_obtained.WaitForNotificationWithTimeout(kTimeToWait));
+ test_mutex.Unlock();
+ EXPECT_TRUE(lock_obtained.WaitForNotificationWithTimeout(kTimeToWait));
+ f.Join();
+}
+
+TEST(MutexTest, RecursiveLockingWorks) {
+ absl::Notification lock_obtained;
+ RecursiveMutex test_mutex;
+ test_mutex.Lock();
+ thread::Fiber f([&test_mutex, &lock_obtained] {
+ test_mutex.Lock();
+ test_mutex.Unlock();
+ lock_obtained.Notify();
+ });
+ EXPECT_FALSE(lock_obtained.WaitForNotificationWithTimeout(kTimeToWait));
+ test_mutex.Unlock();
+ EXPECT_TRUE(lock_obtained.WaitForNotificationWithTimeout(kTimeToWait));
+ f.Join();
+}
+
+TEST(MutexTest, RecursiveLockingForNestedWorks) {
+ absl::Notification lock_obtained;
+ RecursiveMutex test_mutex;
+ test_mutex.Lock();
+ thread::Fiber f([&test_mutex, &lock_obtained]()
+ ABSL_NO_THREAD_SAFETY_ANALYSIS {
+ test_mutex.Lock();
+ test_mutex.Lock();
+ test_mutex.Unlock();
+ test_mutex.Unlock();
+ lock_obtained.Notify();
+ });
+ EXPECT_FALSE(lock_obtained.WaitForNotificationWithTimeout(kTimeToWait));
+ test_mutex.Unlock();
+ EXPECT_TRUE(lock_obtained.WaitForNotificationWithTimeout(kTimeToWait));
+ f.Join();
+}
+
+} // namespace
+} // namespace ios
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/scheduled_executor.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/scheduled_executor.h
new file mode 100644
index 00000000000..580389997c4
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/scheduled_executor.h
@@ -0,0 +1,68 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_IOS_SCHEDULED_EXECUTOR_H_
+#define PLATFORM_IMPL_IOS_SCHEDULED_EXECUTOR_H_
+
+#import <Foundation/Foundation.h>
+
+#include <functional>
+#include <memory>
+
+#include "internal/platform/implementation/scheduled_executor.h"
+#include "internal/platform/runnable.h"
+
+/**
+ * The impl class is an Obj-C class so that
+ * (a) the dispatch block can strongly retain it, and
+ * (b) for ease of declaring an atomic property.
+ */
+@interface GNCOperationQueueImpl : NSObject
+@property(nonatomic) NSOperationQueue* queue;
+@property(atomic) BOOL shuttingDown;
+@end
+
+namespace location {
+namespace nearby {
+namespace ios {
+
+// Concrete ScheduledExecutor implementation.
+class ScheduledExecutor : public api::ScheduledExecutor {
+ public:
+ // The max_concurrency = 1 for default constructor.
+ ScheduledExecutor();
+ explicit ScheduledExecutor(int max_concurrency);
+ ~ScheduledExecutor() override;
+
+ ScheduledExecutor(const ScheduledExecutor&) = delete;
+ ScheduledExecutor& operator=(const ScheduledExecutor&) = delete;
+
+ // api::ScheduledExecutor:
+ void Shutdown() override;
+ std::shared_ptr<api::Cancelable> Schedule(Runnable&& runnable, absl::Duration duration) override;
+ void Execute(Runnable&& runnable) override;
+
+ bool DoSubmit(Runnable&& runnable);
+
+ private:
+ void Shutdown(std::int64_t timeout_millis);
+
+ GNCOperationQueueImpl* impl_;
+};
+
+} // namespace ios
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_IOS_SCHEDULED_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/scheduled_executor.mm b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/scheduled_executor.mm
new file mode 100644
index 00000000000..0df19ced163
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/scheduled_executor.mm
@@ -0,0 +1,144 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import "internal/platform/implementation/ios/Source/Platform/scheduled_executor.h"
+
+#import <Foundation/Foundation.h>
+
+#include "absl/time/time.h"
+#import "internal/platform/implementation/ios/Source/Platform/atomic_boolean.h"
+#include "internal/platform/runnable.h"
+
+// This wraps the C++ Runnable in an Obj-C object for memory management. It is retained by the
+// dispatch block below, and deleted when the block is released.
+@interface GNCRunnableWrapper : NSObject {
+ @public
+ location::nearby::Runnable _runnable;
+ std::unique_ptr<location::nearby::ios::AtomicBoolean> _canceled;
+}
+@end
+
+@implementation GNCRunnableWrapper
+
++ (instancetype)wrapperWithRunnable:(location::nearby::Runnable)runnable {
+ GNCRunnableWrapper *wrapper = [[GNCRunnableWrapper alloc] init];
+ wrapper->_runnable = runnable;
+ wrapper->_canceled = std::make_unique<location::nearby::ios::AtomicBoolean>(false);
+ return wrapper;
+}
+
+@end
+
+@implementation GNCOperationQueueImpl
+
++ (instancetype)implWithMaxConcurrency:(int)maxConcurrency {
+ GNCOperationQueueImpl *impl = [[GNCOperationQueueImpl alloc] init];
+ impl.queue = [[NSOperationQueue alloc] init];
+ impl.queue.maxConcurrentOperationCount = maxConcurrency;
+ return impl;
+}
+
+@end
+
+namespace location {
+namespace nearby {
+namespace ios {
+
+static const std::int64_t kExecutorShutdownDefaultTimeout = 500; // 0.5 seconds
+
+// This Cancelable references a Runnable and a cancel method that sets its canceled boolean to true.
+class CancelableForRunnable : public api::Cancelable {
+ public:
+ explicit CancelableForRunnable(GNCRunnableWrapper *runnable) : runnable_(runnable) {}
+ CancelableForRunnable() = default;
+ ~CancelableForRunnable() override = default;
+ CancelableForRunnable(const CancelableForRunnable &) = delete;
+ CancelableForRunnable &operator=(const CancelableForRunnable &) = delete;
+
+ // api::Cancelable:
+ bool Cancel() override {
+ runnable_->_canceled->Set(true);
+ return true;
+ }
+
+ private:
+ GNCRunnableWrapper *runnable_;
+};
+
+ScheduledExecutor::ScheduledExecutor() { impl_ = [GNCOperationQueueImpl implWithMaxConcurrency:1]; }
+
+ScheduledExecutor::ScheduledExecutor(int max_concurrency) {
+ impl_ = [GNCOperationQueueImpl implWithMaxConcurrency:max_concurrency];
+}
+
+ScheduledExecutor::~ScheduledExecutor() { impl_ = nil; }
+
+void ScheduledExecutor::Shutdown() { Shutdown(kExecutorShutdownDefaultTimeout); }
+
+std::shared_ptr<api::Cancelable> ScheduledExecutor::Schedule(Runnable &&runnable,
+ absl::Duration duration) {
+ if (impl_.shuttingDown) return std::shared_ptr<api::Cancelable>(nullptr);
+
+ // Wrap the runnable in an Obj-C object so it can be referenced by the delayed block.
+ GNCRunnableWrapper *wrapper = [GNCRunnableWrapper wrapperWithRunnable:std::move(runnable)];
+ CancelableForRunnable *cancelable = new CancelableForRunnable(wrapper);
+ GNCOperationQueueImpl *impl = impl_; // don't capture |this|
+ dispatch_after(
+ dispatch_time(DISPATCH_TIME_NOW, absl::ToInt64Milliseconds(duration) * NSEC_PER_MSEC),
+ dispatch_get_global_queue(DISPATCH_TARGET_QUEUE_DEFAULT, 0), ^{
+ [impl.queue addOperationWithBlock:^{
+ // Execute the runnable only if the executor is not shutting down, and the runnable isn't
+ // canceled.
+ // Warning: This block should reference only Obj-C objects, and never C++ objects.
+ if (!impl.shuttingDown && !wrapper->_canceled->Get()) {
+ wrapper->_runnable();
+ }
+ }];
+ });
+
+ return std::shared_ptr<api::Cancelable>(cancelable);
+}
+
+void ScheduledExecutor::Execute(Runnable &&runnable) {
+ DoSubmit(std::move(runnable));
+}
+
+bool ScheduledExecutor::DoSubmit(Runnable &&runnable) {
+ if (impl_.shuttingDown) {
+ return false;
+ }
+
+ // Submit the runnable to the queue.
+ Runnable local_runnable = std::move(runnable);
+ [impl_.queue addOperationWithBlock:^{
+ local_runnable();
+ }];
+ return true;
+}
+
+void ScheduledExecutor::Shutdown(std::int64_t timeout_millis) {
+ // Prevent new/delayed operations from being queued/executed.
+ impl_.shuttingDown = YES;
+
+ // Block until either (a) all currently executing operations finish, or (b) the timeout expires.
+ dispatch_group_t group = dispatch_group_create();
+ dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_TARGET_QUEUE_DEFAULT, 0), ^{
+ [impl_.queue waitUntilAllOperationsAreFinished];
+ });
+ dispatch_group_wait(group, dispatch_time(DISPATCH_TIME_NOW, timeout_millis * NSEC_PER_MSEC));
+}
+
+} // namespace ios
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/single_thread_executor.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/single_thread_executor.h
new file mode 100644
index 00000000000..2979672ddce
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/single_thread_executor.h
@@ -0,0 +1,35 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_IOS_SINGLE_THREAD_EXECUTOR_H_
+#define PLATFORM_IMPL_IOS_SINGLE_THREAD_EXECUTOR_H_
+
+#import "internal/platform/implementation/ios/Source/Platform/multi_thread_executor.h"
+
+namespace location {
+namespace nearby {
+namespace ios {
+
+class SingleThreadExecutor : public MultiThreadExecutor {
+ public:
+ SingleThreadExecutor() : MultiThreadExecutor(1) {}
+ ~SingleThreadExecutor() override = default;
+};
+
+} // namespace ios
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_IOS_SINGLE_THREAD_EXECUTOR_H_
+
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/system_clock.cc b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/system_clock.cc
new file mode 100644
index 00000000000..db7c722ff88
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/system_clock.cc
@@ -0,0 +1,33 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/system_clock.h"
+
+#include "absl/time/clock.h"
+
+namespace location {
+namespace nearby {
+
+void SystemClock::Init() {}
+
+absl::Time SystemClock::ElapsedRealtime() { return absl::Now(); }
+
+// TODO(b/169292092): Check the iOS primitive implementation for SystemClock.
+Exception SystemClock::Sleep(absl::Duration duration) {
+ absl::SleepFor(duration);
+ return {Exception::kSuccess};
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/utils.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/utils.h
new file mode 100644
index 00000000000..fd864a13f80
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/utils.h
@@ -0,0 +1,74 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import <CoreBluetooth/CoreBluetooth.h>
+#import <Foundation/Foundation.h>
+
+#include <set>
+#include <string>
+
+#include "absl/container/flat_hash_map.h"
+#include "absl/strings/string_view.h"
+#include "internal/platform/byte_array.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+namespace location {
+namespace nearby {
+
+/// Converts an Obj-C BOOL to a C++ bool.
+bool CppBoolFromObjCBool(BOOL b);
+
+/// Converts NSNumber to a char.
+char CharFromNSNumber(NSNumber *n);
+
+/// Converts a C++ string to an Obj-C string.
+NSString *ObjCStringFromCppString(absl::string_view s);
+
+/// Converts an Obj-C string to a C++ string.
+std::string CppStringFromObjCString(NSString *s);
+
+/// Converts ByteArray to NSData.
+NSData *NSDataFromByteArray(ByteArray byteArray);
+
+/// Converts NSData to ByteArray.
+ByteArray ByteArrayFromNSData(NSData *data);
+
+/// Converts NSUUID to a C++ string (representing a UUID).
+std::string UUIDStringFromNSUUID(NSUUID *uuid);
+
+/// Converts a C++ string (representing a Bluetooth UUID) to CBUUID.
+CBUUID *CBUUIDFromBluetoothUUIDString(absl::string_view bluetoothUUID);
+
+/// Converts CBUUID to a C++ string (representing a Bluetooth UUID).
+std::string BluetoothUUIDStringFromCBUUID(CBUUID *bluetoothUUID);
+
+/// Converts a C++ set of strings (representing Bluetooth UUIDs) to an NSSet of CBUUID.
+NSSet<CBUUID *> *CBUUIDSetFromBluetoothUUIDStringSet(const std::set<std::string> &bluetoothUUIDSet);
+
+/// Converts an NSSet of CBUUID to a C++ set of strings (representing Bluetooth UUIDs).
+std::set<std::string> BluetoothUUIDStringSetFromCBUUIDSet(NSSet<CBUUID *> *bluetoothUUIDSet);
+
+/// Converts a C++ TxtRecord to an Obj-C TxtRecord.
+NSDictionary<NSString *, NSData *> *NSDictionaryFromCppTxtRecords(
+ const absl::flat_hash_map<std::string, std::string> &txt_records);
+
+/// Converts an Obj-C TxtRecord to a C++ TxtRecord.
+absl::flat_hash_map<std::string, std::string> AbslHashMapFromObjCTxtRecords(
+ NSDictionary<NSString *, NSData *> *txtRecords);
+
+} // namespace nearby
+} // namespace location
+
+NS_ASSUME_NONNULL_END
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/utils.mm b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/utils.mm
new file mode 100644
index 00000000000..2dc5bf1525f
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/utils.mm
@@ -0,0 +1,104 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import "internal/platform/implementation/ios/Source/Platform/utils.h"
+
+#import "absl/container/flat_hash_map.h"
+#include "absl/strings/string_view.h"
+#include "internal/platform/byte_array.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+namespace location {
+namespace nearby {
+
+bool CppBoolFromObjCBool(BOOL b) { return b ? true : false; }
+
+char CharFromNSNumber(NSNumber* n) { return n.charValue; }
+
+NSString* ObjCStringFromCppString(absl::string_view s) {
+ return [NSString stringWithUTF8String:s.data()];
+}
+
+std::string CppStringFromObjCString(NSString* s) {
+ return std::string([s UTF8String], [s lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
+}
+
+NSData* NSDataFromByteArray(ByteArray byteArray) {
+ return [NSData dataWithBytes:byteArray.data() length:byteArray.size()];
+}
+
+ByteArray ByteArrayFromNSData(NSData* data) {
+ return ByteArray((const char*)data.bytes, data.length);
+}
+
+std::string UUIDStringFromNSUUID(NSUUID* uuid) { return CppStringFromObjCString(uuid.UUIDString); }
+
+CBUUID* CBUUIDFromBluetoothUUIDString(absl::string_view bluetoothUUID) {
+ return [CBUUID UUIDWithString:ObjCStringFromCppString(bluetoothUUID)];
+}
+
+std::string BluetoothUUIDStringFromCBUUID(CBUUID* bluetoothUUID) {
+ return CppStringFromObjCString(bluetoothUUID.UUIDString);
+}
+
+NSSet<CBUUID*>* CBUUIDSetFromBluetoothUUIDStringSet(const std::set<std::string>& bluetoothUUIDSet) {
+ NSMutableSet<CBUUID*>* objcBluetoothUUIDSet = [NSMutableSet set];
+ for (std::set<std::string>::const_iterator it = bluetoothUUIDSet.begin();
+ it != bluetoothUUIDSet.end(); ++it) {
+ [objcBluetoothUUIDSet addObject:CBUUIDFromBluetoothUUIDString(*it)];
+ }
+ return objcBluetoothUUIDSet;
+}
+
+std::set<std::string> BluetoothUUIDStringSetFromCBUUIDSet(NSSet<CBUUID*>* bluetoothUUIDSet) {
+ std::set<std::string> cppBluetoothUUIDSet;
+ for (CBUUID* bluetoothUUID in bluetoothUUIDSet) {
+ cppBluetoothUUIDSet.insert(BluetoothUUIDStringFromCBUUID(bluetoothUUID));
+ }
+ return cppBluetoothUUIDSet;
+}
+
+NSDictionary<NSString*, NSData*>* NSDictionaryFromCppTxtRecords(
+ const absl::flat_hash_map<std::string, std::string>& txt_records) {
+ NSMutableArray<NSString*>* keyArray = [[NSMutableArray alloc] init];
+ NSMutableArray<NSData*>* valueArray = [[NSMutableArray alloc] init];
+ for (auto it = txt_records.begin(); it != txt_records.end(); it++) {
+ NSString* key = @(it->first.c_str());
+ NSString* value = @(it->second.c_str());
+ [keyArray addObject:key];
+ [valueArray addObject:[value dataUsingEncoding:NSUTF8StringEncoding]];
+ }
+
+ NSDictionary<NSString*, NSData*>* dict = [[NSDictionary alloc] initWithObjects:valueArray
+ forKeys:keyArray];
+ return dict;
+}
+
+absl::flat_hash_map<std::string, std::string> AbslHashMapFromObjCTxtRecords(
+ NSDictionary<NSString*, NSData*>* txtRecords) {
+ absl::flat_hash_map<std::string, std::string> txt_record;
+
+ for (NSString* key in txtRecords) {
+ NSString* value = [[NSString alloc] initWithData:[txtRecords objectForKey:key]
+ encoding:NSUTF8StringEncoding];
+ txt_record.insert({CppStringFromObjCString(key), CppStringFromObjCString(value)});
+ }
+ return txt_record;
+}
+
+} // namespace nearby
+} // namespace location
+
+NS_ASSUME_NONNULL_END
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/wifi_lan.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/wifi_lan.h
new file mode 100644
index 00000000000..5a6198b1fd7
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/wifi_lan.h
@@ -0,0 +1,202 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_IOS_WIFI_LAN_H_
+#define PLATFORM_IMPL_IOS_WIFI_LAN_H_
+
+#import <Foundation/Foundation.h>
+#include <string>
+
+#include "absl/base/thread_annotations.h"
+#include "absl/container/flat_hash_map.h"
+#include "internal/platform/implementation/wifi_lan.h"
+#include "internal/platform/nsd_service_info.h"
+#import "internal/platform/implementation/ios/Source/Mediums/GNCMConnection.h" // IWYU pragma: export
+
+@class GNCMBonjourBrowser;
+@class GNCMBonjourService;
+
+namespace location {
+namespace nearby {
+namespace ios {
+
+/** InputStream that reads from GNCMConnection. */
+class WifiLanInputStream : public InputStream {
+ public:
+ WifiLanInputStream();
+ ~WifiLanInputStream() override;
+
+ ExceptionOr<ByteArray> Read(std::int64_t size) override;
+ Exception Close() override;
+
+ GNCMConnectionHandlers* GetConnectionHandlers() { return connectionHandlers_; }
+
+ private:
+ GNCMConnectionHandlers* connectionHandlers_;
+ NSMutableArray<NSData*>* newDataPackets_;
+ NSMutableData* accumulatedData_;
+ NSCondition* condition_;
+};
+
+/** OutputStream that writes to GNCMConnection. */
+class WifiLanOutputStream : public OutputStream {
+ public:
+ explicit WifiLanOutputStream(id<GNCMConnection> connection)
+ : connection_(connection), condition_([[NSCondition alloc] init]) {}
+ ~WifiLanOutputStream() override;
+
+ Exception Write(const ByteArray& data) override;
+ Exception Flush() override;
+ Exception Close() override;
+
+ private:
+ id<GNCMConnection> connection_;
+ NSCondition* condition_;
+};
+
+/** Concrete WifiLanSocket implementation. */
+class WifiLanSocket : public api::WifiLanSocket {
+ public:
+ WifiLanSocket() = default;
+ explicit WifiLanSocket(id<GNCMConnection> connection);
+ ~WifiLanSocket() override;
+
+ // api::WifiLanSocket:
+ InputStream& GetInputStream() override { return *input_stream_; }
+ OutputStream& GetOutputStream() override { return *output_stream_; }
+ Exception Close() override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ bool IsClosed() const ABSL_LOCKS_EXCLUDED(mutex_);
+
+ private:
+ void DoClose() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ mutable absl::Mutex mutex_;
+ bool closed_ ABSL_GUARDED_BY(mutex_) = false;
+ std::unique_ptr<WifiLanInputStream> input_stream_;
+ std::unique_ptr<WifiLanOutputStream> output_stream_;
+};
+
+/** Concrete WifiLanServerSocket implementation. */
+class WifiLanServerSocket : public api::WifiLanServerSocket {
+ public:
+ static std::string GetName(const std::string& ip_address, int port);
+
+ ~WifiLanServerSocket() override;
+
+ // api::WifiLanServerSocket:
+ std::string GetIPAddress() const override ABSL_LOCKS_EXCLUDED(mutex_) {
+ absl::MutexLock lock(&mutex_);
+ return ip_address_;
+ }
+ void SetIPAddress(const std::string& ip_address) ABSL_LOCKS_EXCLUDED(mutex_) {
+ absl::MutexLock lock(&mutex_);
+ ip_address_ = ip_address;
+ }
+ int GetPort() const override ABSL_LOCKS_EXCLUDED(mutex_) {
+ absl::MutexLock lock(&mutex_);
+ return port_;
+ }
+ void SetPort(int port) ABSL_LOCKS_EXCLUDED(mutex_) {
+ absl::MutexLock lock(&mutex_);
+ port_ = port;
+ }
+ std::unique_ptr<api::WifiLanSocket> Accept() override ABSL_LOCKS_EXCLUDED(mutex_);
+ Exception Close() override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ bool Connect(std::unique_ptr<WifiLanSocket> socket) ABSL_LOCKS_EXCLUDED(mutex_);
+ void SetCloseNotifier(std::function<void()> notifier) ABSL_LOCKS_EXCLUDED(mutex_);
+
+ private:
+ Exception DoClose() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+
+ mutable absl::Mutex mutex_;
+ std::string ip_address_ ABSL_GUARDED_BY(mutex_);
+ int port_ ABSL_GUARDED_BY(mutex_);
+ absl::CondVar cond_;
+ absl::flat_hash_set<std::unique_ptr<WifiLanSocket>> pending_sockets_ ABSL_GUARDED_BY(mutex_);
+ std::function<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
+ bool closed_ ABSL_GUARDED_BY(mutex_) = false;
+};
+
+/** Concrete WifiLanMedium implementation. */
+class WifiLanMedium : public api::WifiLanMedium {
+ public:
+ WifiLanMedium() = default;
+ ~WifiLanMedium() override;
+
+ WifiLanMedium(const WifiLanMedium&) = delete;
+ WifiLanMedium& operator=(const WifiLanMedium&) = delete;
+
+ // api::WifiLanMedium:
+ bool StartAdvertising(const NsdServiceInfo& nsd_service_info) override
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ bool StopAdvertising(const NsdServiceInfo& nsd_service_info) override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ bool StartDiscovery(const std::string& service_type, DiscoveredServiceCallback callback) override
+ ABSL_LOCKS_EXCLUDED(mutex_);
+ bool StopDiscovery(const std::string& service_type) override ABSL_LOCKS_EXCLUDED(mutex_);
+
+ std::unique_ptr<api::WifiLanSocket> ConnectToService(
+ const NsdServiceInfo& remote_service_info, CancellationFlag* cancellation_flag) override;
+ std::unique_ptr<api::WifiLanSocket> ConnectToService(
+ const std::string& ip_address, int port, CancellationFlag* cancellation_flag) override;
+ std::unique_ptr<api::WifiLanServerSocket> ListenForService(int port) override
+ ABSL_LOCKS_EXCLUDED(mutex_);
+
+ absl::optional<std::pair<std::int32_t, std::int32_t>> GetDynamicPortRange() override {
+ return absl::nullopt;
+ }
+
+ private:
+ struct AdvertisingInfo {
+ bool Empty() const { return services.empty(); }
+ void Clear() { services.clear(); }
+ void Add(const std::string& service_type, GNCMBonjourService* service) {
+ services.insert({service_type, service});
+ }
+ void Remove(const std::string& service_type) { services.erase(service_type); }
+ bool Existed(const std::string& service_type) const { return services.contains(service_type); }
+
+ absl::flat_hash_map<std::string, GNCMBonjourService*> services;
+ };
+ struct DiscoveringInfo {
+ bool Empty() const { return services.empty(); }
+ void Clear() { services.clear(); }
+ void Add(const std::string& service_type, GNCMBonjourBrowser* browser) {
+ services.insert({service_type, browser});
+ }
+ void Remove(const std::string& service_type) { services.erase(service_type); }
+ bool Existed(const std::string& service_type) const { return services.contains(service_type); }
+
+ absl::flat_hash_map<std::string, GNCMBonjourBrowser*> services;
+ };
+
+ std::string GetFakeIPAddress() const;
+ int GetFakePort() const;
+
+ absl::Mutex mutex_;
+ AdvertisingInfo advertising_info_ ABSL_GUARDED_BY(mutex_);
+ int requesting_port_ = 0;
+ DiscoveringInfo discovering_info_ ABSL_GUARDED_BY(mutex_);
+ absl::flat_hash_map<std::string, WifiLanServerSocket*> server_sockets_ ABSL_GUARDED_BY(mutex_);
+ absl::flat_hash_map<std::string, GNCMConnectionRequester> connection_requesters_
+ ABSL_GUARDED_BY(mutex_);
+};
+
+} // namespace ios
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_IOS_WIFI_LAN_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/wifi_lan.mm b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/wifi_lan.mm
new file mode 100644
index 00000000000..debaa4cfaa7
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Platform/wifi_lan.mm
@@ -0,0 +1,497 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import "internal/platform/implementation/ios/Source/Platform/wifi_lan.h"
+
+#include <memory>
+#include <string>
+#include <utility>
+
+#include "absl/container/flat_hash_map.h"
+#include "absl/container/internal/common.h"
+#include "absl/memory/memory.h"
+#include "absl/strings/str_cat.h"
+#include "absl/strings/str_format.h"
+#include "absl/synchronization/mutex.h"
+#include "internal/platform/cancellation_flag.h"
+#include "internal/platform/exception.h"
+#import "internal/platform/implementation/ios/Source/Mediums/GNCMConnection.h"
+#import "internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourBrowser.h"
+#import "internal/platform/implementation/ios/Source/Mediums/WifiLan/GNCMBonjourService.h"
+#include "internal/platform/implementation/ios/Source/Platform/utils.h"
+#include "internal/platform/implementation/wifi_lan.h"
+#include "internal/platform/nsd_service_info.h"
+#include "internal/platform/prng.h"
+#import "GoogleToolboxForMac/GTMLogger.h"
+
+namespace location {
+namespace nearby {
+namespace ios {
+
+/** WifiLanInputStream implementation. */
+WifiLanInputStream::WifiLanInputStream()
+ : newDataPackets_([NSMutableArray array]),
+ accumulatedData_([NSMutableData data]),
+ condition_([[NSCondition alloc] init]) {
+ // Create the handlers of incoming data from the remote endpoint.
+ connectionHandlers_ = [GNCMConnectionHandlers
+ payloadHandler:^(NSData* data) {
+ [condition_ lock];
+ // Add the incoming data to the data packet array to be processed in Read() below.
+ [newDataPackets_ addObject:data];
+ [condition_ signal];
+ [condition_ unlock];
+ }
+ disconnectedHandler:^{
+ [condition_ lock];
+ // Release the data packet array, meaning the stream has been closed or severed.
+ newDataPackets_ = nil;
+ [condition_ signal];
+ [condition_ unlock];
+ }];
+}
+
+WifiLanInputStream::~WifiLanInputStream() {
+ NSCAssert(!newDataPackets_, @"WifiLanInputStream not closed before destruction");
+}
+
+ExceptionOr<ByteArray> WifiLanInputStream::Read(std::int64_t size) {
+ // Block until either (a) the connection has been closed, or (b) enough data to return.
+ NSData* dataToReturn;
+ [condition_ lock];
+ while (true) {
+ // Check if the stream has been closed or severed.
+ if (!newDataPackets_) break;
+
+ if (newDataPackets_.count > 0) {
+ // Add the packet data to the accumulated data.
+ for (NSData* data in newDataPackets_) {
+ if (data.length > 0) {
+ [accumulatedData_ appendData:data];
+ }
+ }
+ [newDataPackets_ removeAllObjects];
+ }
+
+ if ((size == -1) && (accumulatedData_.length > 0)) {
+ // Return all of the data.
+ dataToReturn = accumulatedData_;
+ accumulatedData_ = [NSMutableData data];
+ break;
+ } else if (accumulatedData_.length > 0) {
+ // Return up to |size| bytes of the data.
+ std::int64_t sizeToReturn = accumulatedData_.length < size ? accumulatedData_.length : size;
+ NSRange range = NSMakeRange(0, (NSUInteger)sizeToReturn);
+ dataToReturn = [accumulatedData_ subdataWithRange:range];
+ [accumulatedData_ replaceBytesInRange:range withBytes:nil length:0];
+ break;
+ }
+
+ [condition_ wait];
+ }
+ [condition_ unlock];
+
+ if (dataToReturn) {
+ GTMLoggerInfo(@"[NEARBY] Input stream: Received data of size: %lu",
+ (unsigned long)dataToReturn.length);
+ return ExceptionOr<ByteArray>(ByteArrayFromNSData(dataToReturn));
+ } else {
+ return ExceptionOr<ByteArray>{Exception::kIo};
+ }
+}
+
+Exception WifiLanInputStream::Close() {
+ // Unblock pending read operation.
+ [condition_ lock];
+ newDataPackets_ = nil;
+ [condition_ signal];
+ [condition_ unlock];
+ return {Exception::kSuccess};
+}
+
+/** WifiLanOutputStream implementation. */
+WifiLanOutputStream::~WifiLanOutputStream() {
+ NSCAssert(!connection_, @"WifiLanOutputStream not closed before destruction");
+}
+
+Exception WifiLanOutputStream::Write(const ByteArray& data) {
+ [condition_ lock];
+ GTMLoggerDebug(@"[NEARBY] Sending data of size: %lu",
+ (unsigned long)NSDataFromByteArray(data).length);
+
+ NSMutableData* packet = [NSMutableData dataWithData:NSDataFromByteArray(data)];
+
+ // Send the data, blocking until the completion handler is called.
+ __block GNCMPayloadResult sendResult = GNCMPayloadResultFailure;
+ __block bool isComplete = NO;
+ NSCondition* condition = condition_; // don't capture |this| in completion
+ // Check if connection_ is nil, then just don't wait and return as failure.
+ if (connection_ != nil) {
+ [connection_ sendData:packet
+ progressHandler:^(size_t count) {
+ }
+ completion:^(GNCMPayloadResult result) {
+ // Make sure we haven't already reported completion before. This prevents a crash
+ // where we try leaving a dispatch group more times than we entered it.
+ // b/79095653.
+ if (isComplete) {
+ return;
+ }
+ isComplete = YES;
+ sendResult = result;
+ [condition lock];
+ [condition signal];
+ [condition unlock];
+ }];
+ [condition_ wait];
+ [condition_ unlock];
+ } else {
+ sendResult = GNCMPayloadResultFailure;
+ [condition_ unlock];
+ }
+
+ if (sendResult == GNCMPayloadResultSuccess) {
+ return {Exception::kSuccess};
+ } else {
+ return {Exception::kIo};
+ }
+}
+
+Exception WifiLanOutputStream::Flush() {
+ // The Write() function block until the data is received by the remote endpoint, so there's
+ // nothing to do here.
+ return {Exception::kSuccess};
+}
+
+Exception WifiLanOutputStream::Close() {
+ // Unblock pending write operation.
+ [condition_ lock];
+ connection_ = nil;
+ [condition_ signal];
+ [condition_ unlock];
+ return {Exception::kSuccess};
+}
+
+/** WifiLanSocket implementation. */
+WifiLanSocket::WifiLanSocket(id<GNCMConnection> connection)
+ : input_stream_(new WifiLanInputStream()),
+ output_stream_(new WifiLanOutputStream(connection)) {}
+
+WifiLanSocket::~WifiLanSocket() {
+ absl::MutexLock lock(&mutex_);
+ DoClose();
+}
+
+bool WifiLanSocket::IsClosed() const {
+ absl::MutexLock lock(&mutex_);
+ return closed_;
+}
+
+Exception WifiLanSocket::Close() {
+ absl::MutexLock lock(&mutex_);
+ DoClose();
+ return {Exception::kSuccess};
+}
+
+void WifiLanSocket::DoClose() {
+ if (!closed_) {
+ input_stream_->Close();
+ output_stream_->Close();
+ closed_ = true;
+ }
+}
+
+/** WifiLanServerSocket implementation. */
+std::string WifiLanServerSocket::GetName(const std::string& ip_address, int port) {
+ std::string dot_delimited_string;
+ if (!ip_address.empty()) {
+ for (auto byte : ip_address) {
+ if (!dot_delimited_string.empty()) absl::StrAppend(&dot_delimited_string, ".");
+ absl::StrAppend(&dot_delimited_string, absl::StrFormat("%d", byte));
+ }
+ }
+ std::string out = absl::StrCat(dot_delimited_string, ":", port);
+ return out;
+}
+
+WifiLanServerSocket::~WifiLanServerSocket() {
+ absl::MutexLock lock(&mutex_);
+ DoClose();
+}
+
+std::unique_ptr<api::WifiLanSocket> WifiLanServerSocket::Accept() {
+ absl::MutexLock lock(&mutex_);
+ while (!closed_ && pending_sockets_.empty()) {
+ cond_.Wait(&mutex_);
+ }
+ // Return early if closed.
+ if (closed_) return {};
+
+ auto remote_socket = std::move(pending_sockets_.extract(pending_sockets_.begin()).value());
+ return std::move(remote_socket);
+}
+
+bool WifiLanServerSocket::Connect(std::unique_ptr<WifiLanSocket> socket) {
+ absl::MutexLock lock(&mutex_);
+ if (closed_) {
+ return false;
+ }
+ // add client socket to the pending list
+ pending_sockets_.insert(std::move(socket));
+ cond_.SignalAll();
+ if (closed_) {
+ return false;
+ }
+ return true;
+}
+
+void WifiLanServerSocket::SetCloseNotifier(std::function<void()> notifier) {
+ absl::MutexLock lock(&mutex_);
+ close_notifier_ = std::move(notifier);
+}
+
+Exception WifiLanServerSocket::Close() {
+ absl::MutexLock lock(&mutex_);
+ return DoClose();
+}
+
+Exception WifiLanServerSocket::DoClose() {
+ bool should_notify = !closed_;
+ closed_ = true;
+ if (should_notify) {
+ cond_.SignalAll();
+ if (close_notifier_) {
+ auto notifier = std::move(close_notifier_);
+ mutex_.Unlock();
+ // Notifier may contain calls to public API, and may cause deadlock, if
+ // mutex_ is held during the call.
+ notifier();
+ mutex_.Lock();
+ }
+ }
+ return {Exception::kSuccess};
+}
+
+/** WifiLanMedium implementation. */
+WifiLanMedium::~WifiLanMedium() {
+ advertising_info_.Clear();
+ discovering_info_.Clear();
+}
+
+bool WifiLanMedium::StartAdvertising(const NsdServiceInfo& nsd_service_info) {
+ std::string service_type = nsd_service_info.GetServiceType();
+ NSString* serviceType = ObjCStringFromCppString(service_type);
+ {
+ absl::MutexLock lock(&mutex_);
+ if (advertising_info_.Existed(service_type)) {
+ GTMLoggerInfo(@"[NEARBY] WifiLan StartAdvertising: Can't start advertising because "
+ @"service_type=%@, has started already",
+ serviceType);
+ return false;
+ }
+ }
+
+ // Retrieve service name.
+ NSString* serviceName = ObjCStringFromCppString(nsd_service_info.GetServiceName());
+ // Retrieve TXTRecord and convert it to NSDictionary type.
+ NSDictionary<NSString*, NSData*>* TXTRecordData =
+ NSDictionaryFromCppTxtRecords(nsd_service_info.GetTxtRecords());
+ // Get ip address and port to retrieve the server_socket, if not, then return nil.
+ std::string ip_address = nsd_service_info.GetIPAddress();
+ int port = nsd_service_info.GetPort();
+ __block std::string socket_name = WifiLanServerSocket::GetName(ip_address, port);
+ GNCMBonjourService* service = [[GNCMBonjourService alloc]
+ initWithServiceName:serviceName
+ serviceType:serviceType
+ port:requesting_port_
+ TXTRecordData:TXTRecordData
+ endpointConnectedHandler:^GNCMConnectionHandlers*(id<GNCMConnection> connection) {
+ auto item = server_sockets_.find(socket_name);
+ WifiLanServerSocket* server_socket = item != server_sockets_.end() ? item->second : nullptr;
+ if (!server_socket) {
+ return nil;
+ }
+ auto socket = absl::make_unique<WifiLanSocket>(connection);
+ GNCMConnectionHandlers* connectionHandlers =
+ static_cast<WifiLanInputStream&>(socket->GetInputStream()).GetConnectionHandlers();
+ server_socket->Connect(std::move(socket));
+ return connectionHandlers;
+ }];
+ {
+ absl::MutexLock lock(&mutex_);
+ advertising_info_.Add(service_type, service);
+ }
+ return true;
+}
+
+bool WifiLanMedium::StopAdvertising(const NsdServiceInfo& nsd_service_info) {
+ std::string service_type = nsd_service_info.GetServiceType();
+ {
+ absl::MutexLock lock(&mutex_);
+ if (!advertising_info_.Existed(service_type)) {
+ GTMLoggerInfo(@"[NEARBY] WifiLan StopAdvertising: Can't stop advertising because we never "
+ @"started advertising for service_type=%@",
+ ObjCStringFromCppString(service_type));
+ return false;
+ }
+ advertising_info_.Remove(service_type);
+ }
+ return true;
+}
+
+bool WifiLanMedium::StartDiscovery(const std::string& service_type,
+ DiscoveredServiceCallback callback) {
+ NSString* serviceType = ObjCStringFromCppString(service_type);
+ {
+ absl::MutexLock lock(&mutex_);
+ if (discovering_info_.Existed(service_type)) {
+ GTMLoggerInfo(@"[NEARBY] WifiLan StartAdvertising: Can't start discovery because "
+ @"service_type=%@, has started already",
+ serviceType);
+ return false;
+ }
+ }
+ GNCMBonjourBrowser* browser = [[GNCMBonjourBrowser alloc]
+ initWithServiceType:serviceType
+ endpointFoundHandler:^GNCMEndpointLostHandler(
+ NSString* endpointId, NSString* serviceType, NSString* serviceName,
+ NSDictionary<NSString*, NSData*>* _Nullable txtRecordData,
+ GNCMConnectionRequester requestConnection) {
+ __block NsdServiceInfo nsd_service_info = {};
+ nsd_service_info.SetServiceName(CppStringFromObjCString(serviceName));
+ nsd_service_info.SetServiceType(CppStringFromObjCString(serviceType));
+ // Set TXTRecord converted from NSDictionary to hash map.
+ if (txtRecordData != nil) {
+ auto txt_records = AbslHashMapFromObjCTxtRecords(txtRecordData);
+ nsd_service_info.SetTxtRecords(txt_records);
+ }
+ connection_requesters_.insert({CppStringFromObjCString(serviceType), requestConnection});
+ callback.service_discovered_cb(nsd_service_info);
+ return ^{
+ callback.service_lost_cb(nsd_service_info);
+ };
+ }];
+ {
+ absl::MutexLock lock(&mutex_);
+ discovering_info_.Add(service_type, browser);
+ }
+ return true;
+}
+
+bool WifiLanMedium::StopDiscovery(const std::string& service_type) {
+ {
+ absl::MutexLock lock(&mutex_);
+ if (!discovering_info_.Existed(service_type)) {
+ GTMLoggerInfo(@"[NEARBY] WifiLan StopDiscovery: Can't stop discovering because "
+ "we never started discovering.");
+ return false;
+ }
+ discovering_info_.Remove(service_type);
+ }
+ return true;
+}
+
+std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
+ const NsdServiceInfo& remote_service_info, CancellationFlag* cancellation_flag) {
+ std::string service_type = remote_service_info.GetServiceType();
+ GTMLoggerInfo(@"[NEARBY] WifiLan ConnectToService, service_type=%@",
+ ObjCStringFromCppString(service_type));
+
+ GNCMConnectionRequester connection_requester = nil;
+ {
+ absl::MutexLock lock(&mutex_);
+ const auto& it = connection_requesters_.find(service_type);
+ if (it == connection_requesters_.end()) {
+ return {};
+ }
+ connection_requester = it->second;
+ }
+
+ dispatch_group_t group = dispatch_group_create();
+ dispatch_group_enter(group);
+ __block std::unique_ptr<WifiLanSocket> socket;
+ if (connection_requester != nil) {
+ if (cancellation_flag->Cancelled()) {
+ GTMLoggerError(@"[NEARBY] WifiLan Connect: Has been cancelled: service_type=%@",
+ ObjCStringFromCppString(service_type));
+ dispatch_group_leave(group); // unblock
+ return {};
+ }
+
+ connection_requester(^(id<GNCMConnection> connection) {
+ // If the connection wasn't successfully established, return a NULL socket.
+ if (connection) {
+ socket = absl::make_unique<WifiLanSocket>(connection);
+ }
+
+ dispatch_group_leave(group); // unblock
+ return socket != nullptr ? static_cast<WifiLanInputStream&>(socket->GetInputStream())
+ .GetConnectionHandlers()
+ : nullptr;
+ });
+ }
+ dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
+
+ return std::move(socket);
+}
+
+std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
+ const std::string& ip_address, int port, CancellationFlag* cancellation_flag) {
+ // Not implemented.
+ return {};
+}
+
+std::unique_ptr<api::WifiLanServerSocket> WifiLanMedium::ListenForService(int port) {
+ auto server_socket = std::make_unique<WifiLanServerSocket>();
+ // The fake ip address and port need to be set here since they can't be retrieved before
+ // StartAadvertising begins. Furthermore, NSNetService can't resolve ip address when finding
+ // service. Try to fake them and make it socket name as a key of server_sockets_ which acts
+ // the same socket binding.
+ server_socket->SetIPAddress(GetFakeIPAddress());
+ requesting_port_ = port;
+ server_socket->SetPort(requesting_port_ == 0 ? GetFakePort() : requesting_port_);
+ std::string socket_name =
+ WifiLanServerSocket::GetName(server_socket->GetIPAddress(), server_socket->GetPort());
+ server_socket->SetCloseNotifier([this, socket_name]() {
+ absl::MutexLock lock(&mutex_);
+ server_sockets_.erase(socket_name);
+ });
+ GTMLoggerInfo(@"[NEARBY] WifiLan Adding server socket, socket_name=%@",
+ ObjCStringFromCppString(socket_name));
+ absl::MutexLock lock(&mutex_);
+ server_sockets_.insert({socket_name, server_socket.get()});
+ return server_socket;
+}
+
+std::string WifiLanMedium::GetFakeIPAddress() const {
+ std::string ip_address;
+ ip_address.resize(4);
+ uint32_t raw_ip_addr = Prng().NextUint32();
+ ip_address[0] = static_cast<char>(raw_ip_addr >> 24);
+ ip_address[1] = static_cast<char>(raw_ip_addr >> 16);
+ ip_address[2] = static_cast<char>(raw_ip_addr >> 8);
+ ip_address[3] = static_cast<char>(raw_ip_addr >> 0);
+
+ return ip_address;
+}
+
+int WifiLanMedium::GetFakePort() const {
+ uint16_t port = Prng().NextUint32();
+
+ return port;
+}
+
+} // namespace ios
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Shared/BUILD b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Shared/BUILD
new file mode 100644
index 00000000000..1ad2cda37f2
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Shared/BUILD
@@ -0,0 +1,30 @@
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+licenses(["notice"])
+
+package(default_visibility = ["//internal/platform/implementation/ios:__subpackages__"])
+
+objc_library(
+ name = "Shared",
+ srcs = [
+ "GNCUtils.m",
+ ],
+ hdrs = [
+ "GNCUtils.h",
+ ],
+ deps = [
+ "//third_party/objective_c/google_toolbox_for_mac:GTM_StringEncoding",
+ "@aappleby_smhasher//:libmurmur3",
+ ],
+)
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Shared/GNCUtils.h b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Shared/GNCUtils.h
new file mode 100644
index 00000000000..0d27c550978
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Shared/GNCUtils.h
@@ -0,0 +1,50 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import <Foundation/Foundation.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+// Current version of socket protocol.
+extern const int GNCSocketVersion;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/// Generates a SHA-256 hash (32 bytes) from a data object.
+NSData *_Nullable GNCSha256Data(NSData *data);
+
+/// Generates a SHA-256 hash (32 bytes) from a string.
+NSData *_Nullable GNCSha256String(NSString *string);
+
+
+/// Generates an MD5 hash (16 bytes) from a data object.
+NSData *_Nullable GNCMd5Data(NSData *data);
+
+/// Generates an MD5 hash (16 bytes) from a string.
+NSData *_Nullable GNCMd5String(NSString *string);
+
+
+/// Base64-encode.
+NSString *GNCBase64Encode(NSData *data);
+
+/// Base64-decode.
+NSData *GNCBase64Decode(NSString *string);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+NS_ASSUME_NONNULL_END
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Shared/GNCUtils.m b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Shared/GNCUtils.m
new file mode 100644
index 00000000000..ac2bba83386
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Source/Shared/GNCUtils.m
@@ -0,0 +1,65 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import "internal/platform/implementation/ios/Source/Shared/GNCUtils.h"
+
+#import <CommonCrypto/CommonDigest.h>
+
+#import "GoogleToolboxForMac/GTMStringEncoding.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+const int GNCSocketVersion = 2;
+
+NSData *GNCSha256Data(NSData *data) {
+ unsigned char output[CC_SHA256_DIGEST_LENGTH];
+ CC_LONG length = (CC_LONG)data.length;
+ if (!CC_SHA256(data.bytes, length, output)) return nil;
+ return [NSData dataWithBytes:output length:CC_SHA256_DIGEST_LENGTH];
+}
+
+NSData *GNCSha256String(NSString *string) {
+ return GNCSha256Data([string dataUsingEncoding:NSUTF8StringEncoding]);
+}
+
+NSData *GNCMd5Data(NSData *data) {
+ unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
+ CC_MD5(data.bytes, (CC_LONG)data.length, md5Buffer);
+ return [NSData dataWithBytes:md5Buffer length:CC_MD5_DIGEST_LENGTH];
+}
+
+NSData *GNCMd5String(NSString *string) {
+ return GNCMd5Data([string dataUsingEncoding:NSUTF8StringEncoding]);
+}
+
+static GTMStringEncoding *GNCBase64WebSafeEncodingNoPadding() {
+ static dispatch_once_t onceToken;
+ static GTMStringEncoding *encoding;
+ dispatch_once(&onceToken, ^{
+ encoding = [GTMStringEncoding stringEncodingWithString:
+ @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"];
+ [encoding setDoPad:NO];
+ });
+ return encoding;
+}
+
+NSString *GNCBase64Encode(NSData *data) {
+ return [GNCBase64WebSafeEncodingNoPadding() encode:data error:nil];
+}
+
+NSData *GNCBase64Decode(NSString *string) {
+ return [GNCBase64WebSafeEncodingNoPadding() decode:string error:nil];
+}
+
+NS_ASSUME_NONNULL_END
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/BUILD b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/BUILD
new file mode 100644
index 00000000000..4b09d7d57bb
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/BUILD
@@ -0,0 +1,63 @@
+load("//tools/build_defs/apple:ios.bzl", "ios_unit_test")
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+licenses(["notice"])
+
+package(default_visibility = ["//visibility:public"])
+
+objc_library(
+ name = "PlatformTestslib",
+ testonly = 1,
+ srcs = [
+ "Platform/GNCCryptoTest.mm",
+ "Platform/GNCInputFileTest.mm",
+ "Platform/GNCMultiThreadExecutorTest.mm",
+ "Platform/GNCScheduledExecutorTest.mm",
+ "Platform/GNCSingleThreadExecutorTest.mm",
+ ],
+ deps = [
+ "//internal/platform/implementation/ios:Connections",
+ ],
+)
+
+ios_unit_test(
+ name = "PlatformTests",
+ minimum_os_version = "12.0",
+ runner = "//testing/utp/ios:IOS_12",
+ deps = [
+ ":PlatformTestslib",
+ ],
+)
+
+objc_library(
+ name = "SharedTestslib",
+ testonly = 1,
+ srcs = [
+ "Shared/GNCUtilsTest.mm",
+ ],
+ deps = [
+ "//internal/platform/implementation/ios/Source/Platform",
+ "//internal/platform/implementation/ios/Source/Shared",
+ ],
+)
+
+ios_unit_test(
+ name = "SharedTests",
+ minimum_os_version = "12.0",
+ runner = "//testing/utp/ios:IOS_12",
+ deps = [
+ ":SharedTestslib",
+ ],
+)
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/Platform/GNCCryptoTest.mm b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/Platform/GNCCryptoTest.mm
new file mode 100644
index 00000000000..3273325bb72
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/Platform/GNCCryptoTest.mm
@@ -0,0 +1,52 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import <XCTest/XCTest.h>
+
+#include "internal/platform/implementation/crypto.h"
+#include "internal/platform/byte_array.h"
+
+@interface GNCCryptoTest : XCTestCase
+@end
+
+@implementation GNCCryptoTest
+
+// Tests that the hash functions return the expected values.
+- (void)testHashValues {
+ std::string string("com.google.location.nearby");
+
+ // SHA-256 test.
+ {
+ const uint8_t sha256ExpectedHash[] = {
+ 0x09, 0x8e, 0x3c, 0x54, 0x2d, 0xee, 0x9e, 0x35,
+ 0x1d, 0xe7, 0x5b, 0xcf, 0xda, 0xb5, 0x62, 0xd3,
+ 0xde, 0xba, 0x14, 0x49, 0xbd, 0xf5, 0x95, 0x04,
+ 0x1f, 0x1d, 0x99, 0x84, 0x87, 0xc3, 0xcb, 0x8a, };
+ location::nearby::ByteArray sha256Hash = location::nearby::Crypto::Sha256(string);
+ XCTAssert(sha256Hash.size() == sizeof(sha256ExpectedHash) &&
+ memcmp(sha256Hash.data(), sha256ExpectedHash, sizeof(sha256ExpectedHash)) == 0);
+ }
+
+ // MD5 test.
+ {
+ const uint8_t md5ExpectedHash[] = {
+ 0x97, 0x78, 0x1d, 0x3d, 0xee, 0xd7, 0xdc, 0x5a,
+ 0x6e, 0xee, 0x50, 0x08, 0xce, 0xd1, 0xb2, 0xe8 };
+ location::nearby::ByteArray md5Hash = location::nearby::Crypto::Md5(string);
+ XCTAssert(md5Hash.size() == sizeof(md5ExpectedHash) &&
+ memcmp(md5Hash.data(), md5ExpectedHash, sizeof(md5ExpectedHash)) == 0);
+ }
+}
+
+@end
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/Platform/GNCInputFileTest.mm b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/Platform/GNCInputFileTest.mm
new file mode 100644
index 00000000000..e744de067a1
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/Platform/GNCInputFileTest.mm
@@ -0,0 +1,56 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import <XCTest/XCTest.h>
+
+#import "internal/platform/byte_array.h"
+#import "internal/platform/exception.h"
+#import "internal/platform/implementation/ios/Source/Platform/input_file.h"
+
+using ::location::nearby::ios::InputFile;
+using ::location::nearby::ByteArray;
+using ::location::nearby::ExceptionOr;
+
+@interface GNCInputFileTest : XCTestCase
+@end
+
+@implementation GNCInputFileTest
+
+// TODO(b/169292092): Find more tools (e.g. file/util/TempPath) to test fake file.
+- (void)testNonExistentPath {
+ std::string cc_path("/foo/bar/test.ext");
+ NSString* objcPath = [NSString stringWithUTF8String:cc_path.c_str()];
+ NSURL *testURL = [NSURL URLWithString:objcPath];
+
+ auto input_file = std::make_unique<InputFile>(testURL);
+ XCTAssert(input_file != nullptr);
+
+ XCTAssertEqual(input_file->GetTotalSize(), 0);
+ ExceptionOr<ByteArray> read_result = input_file->Read(3);
+ XCTAssertFalse(read_result.ok());
+}
+
+- (void)testGetFilePath {
+ std::string cc_path("/foo/bar/test.ext");
+ NSString* objcPath = [NSString stringWithUTF8String:cc_path.c_str()];
+ NSURL *testURL = [NSURL URLWithString:objcPath];
+
+ auto input_file = std::make_unique<InputFile>(testURL);
+ XCTAssert(input_file != nullptr);
+
+ std::string input_file_path = input_file->GetFilePath();
+ XCTAssertTrue([objcPath isEqualToString:[NSString stringWithUTF8String:input_file_path.c_str()]]);
+}
+
+@end
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/Platform/GNCMultiThreadExecutorTest.mm b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/Platform/GNCMultiThreadExecutorTest.mm
new file mode 100644
index 00000000000..c5439fcffe5
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/Platform/GNCMultiThreadExecutorTest.mm
@@ -0,0 +1,114 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import <XCTest/XCTest.h>
+
+#include "absl/time/time.h"
+#include "internal/platform/implementation/cancelable.h"
+#include "internal/platform/implementation/executor.h"
+#include "internal/platform/implementation/platform.h"
+#include "internal/platform/implementation/submittable_executor.h"
+#include "internal/platform/runnable.h"
+
+using location::nearby::Runnable;
+using location::nearby::api::ImplementationPlatform;
+using MultiThreadExecutor = location::nearby::api::SubmittableExecutor;
+
+@interface GNCMultiThreadExecutorTest : XCTestCase
+@property(atomic) int counter;
+@property(atomic) int otherCounter;
+@end
+
+@implementation GNCMultiThreadExecutorTest
+
+// Creates a MultiThreadExecutor.
+- (std::unique_ptr<MultiThreadExecutor>)executor {
+ std::unique_ptr<MultiThreadExecutor> executor =
+ ImplementationPlatform::CreateMultiThreadExecutor(4);
+ XCTAssert(executor != nullptr);
+ return executor;
+}
+
+// Tests that the executor executes runnables as expected.
+- (void)testExecute {
+ std::unique_ptr<MultiThreadExecutor> executor([self executor]);
+
+ // Execute two runnables that increment the counter.
+ const int kIncrements = 13;
+ Runnable incrementer = [self]() { self.counter++; };
+ for (int i = 0; i < kIncrements; i++) {
+ executor->Execute(std::move(incrementer));
+ }
+
+ // Check that the counter has the expected value after giving the runnables time to run.
+ [NSThread sleepForTimeInterval:0.01];
+ XCTAssertEqual(self.counter, kIncrements);
+}
+
+// Tests that the executor submits runnables as expected.
+- (void)testSubmit {
+ std::unique_ptr<MultiThreadExecutor> executor([self executor]);
+
+ // Submit two runnables that increment the counter.
+ const int kIncrements = 13;
+ Runnable incrementer = [self]() { self.counter++; };
+ for (int i = 0; i < kIncrements; i++) {
+ executor->DoSubmit(std::move(incrementer));
+ }
+
+ // Check that the counter has the expected value after giving the runnables time to run.
+ [NSThread sleepForTimeInterval:0.01];
+ XCTAssertEqual(self.counter, kIncrements);
+}
+
+// Tests that fails to submit when the executor is shut down.
+- (void)testFailtoSubmitAfterShutdown {
+ std::unique_ptr<MultiThreadExecutor> executor([self executor]);
+
+ executor->Shutdown();
+
+ XCTAssertFalse(executor->DoSubmit([self]() { self.counter++; }));
+
+ // Check that the counter has the expected value after giving the runnables time to run.
+ [NSThread sleepForTimeInterval:0.01];
+ XCTAssertEqual(self.counter, 0);
+}
+
+// Tests that when the executor is shut down, it waits for pending operations to finish, and no new
+// operations will be executed.
+- (void)testShutdownToAllowExistingTaskComplete {
+ std::unique_ptr<MultiThreadExecutor> executor([self executor]);
+
+ dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_TARGET_QUEUE_DEFAULT, 0);
+ XCTestExpectation *expectation = [self expectationWithDescription:@"finished"];
+
+ const int kRunnableCount = 1000;
+ for (int i = 0; i < kRunnableCount; i++) {
+ executor->Execute([self]() { self.counter++; });
+ }
+
+ executor->Shutdown();
+
+ executor->Execute([self]() { self.otherCounter++; });
+
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), queue, ^{
+ XCTAssertLessThanOrEqual(self.counter, kRunnableCount);
+ XCTAssertEqual(self.otherCounter, 0);
+ [expectation fulfill];
+ });
+
+ [self waitForExpectationsWithTimeout:0.5 handler:nil];
+}
+
+@end
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/Platform/GNCScheduledExecutorTest.mm b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/Platform/GNCScheduledExecutorTest.mm
new file mode 100644
index 00000000000..9f00bc47391
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/Platform/GNCScheduledExecutorTest.mm
@@ -0,0 +1,139 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import <XCTest/XCTest.h>
+
+#include "absl/time/time.h"
+#include "internal/platform/implementation/cancelable.h"
+#include "internal/platform/implementation/executor.h"
+#include "internal/platform/implementation/platform.h"
+#include "internal/platform/implementation/scheduled_executor.h"
+#include "internal/platform/runnable.h"
+
+using location::nearby::Runnable;
+using location::nearby::api::ImplementationPlatform;
+using location::nearby::api::ScheduledExecutor;
+
+@interface GNCScheduledExecutorTest : XCTestCase
+@property(atomic) int counter;
+@end
+
+@implementation GNCScheduledExecutorTest
+
+// Creates a ScheduledExecutor.
+- (std::unique_ptr<ScheduledExecutor>)executor {
+ std::unique_ptr<ScheduledExecutor> executor = ImplementationPlatform::CreateScheduledExecutor();
+ XCTAssert(executor != nullptr);
+ return executor;
+}
+
+// Tests that the executor schedules operation at the specified time.
+- (void)testScheduling {
+ std::unique_ptr<ScheduledExecutor> executor([self executor]);
+
+ XCTestExpectation *expectation = [self expectationWithDescription:@"finished"];
+
+ Runnable incrementer = [self]() { self.counter++; };
+
+ void (^checkCounter)(int, NSTimeInterval, dispatch_block_t) =
+ ^(int expectedCount, NSTimeInterval delay, dispatch_block_t finalBlock) {
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)),
+ dispatch_get_main_queue(), ^{
+ XCTAssertEqual(self.counter, expectedCount);
+ finalBlock();
+ });
+ };
+
+ // Schedule two runnables that increment the counter, at 0.4 and 0.8 seconds.
+ executor->Schedule(std::move(incrementer), absl::Seconds(0.4));
+ executor->Schedule(std::move(incrementer), absl::Seconds(0.8));
+
+ // Check that the counter contains the expected values at 0.2, 0.6, and 1.0 seconds.
+ checkCounter(0, 0.2, ^{});
+ checkCounter(1, 0.6, ^{});
+ checkCounter(2, 1.0, ^{ [expectation fulfill]; });
+
+ [self waitForExpectationsWithTimeout:1.2 handler:nil];
+}
+
+// Tests that fails to schedule when the executor is shut down.
+- (void)testFailtoScheduleAfterShutdown {
+ std::unique_ptr<ScheduledExecutor> executor([self executor]);
+
+ executor->Shutdown();
+
+ dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_TARGET_QUEUE_DEFAULT, 0);
+ XCTestExpectation *expectation = [self expectationWithDescription:@"finished"];
+
+ const NSTimeInterval delay = 0.1;
+ executor->Schedule([self]() { self.counter++; }, absl::Milliseconds(delay));
+
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * 2 * NSEC_PER_SEC)), queue, ^{
+ XCTAssertEqual(self.counter, 0);
+ [expectation fulfill];
+ });
+
+ [self waitForExpectationsWithTimeout:delay * 5 handler:nil];
+}
+
+// Tests that fails to cancel when the executor is shut down.
+- (void)testFailToCancelAfterShutdown {
+ std::unique_ptr<ScheduledExecutor> executor([self executor]);
+
+ executor->Shutdown();
+
+ auto cancelable = executor->Schedule([self]() { self.counter++; }, absl::Seconds(0.1));
+
+ XCTAssert(cancelable.get() == nullptr);
+}
+
+// Tests that shutting down an existing task fails to complete.
+- (void)testShutdownToFailExistingTask {
+ std::unique_ptr<ScheduledExecutor> executor([self executor]);
+
+ dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_TARGET_QUEUE_DEFAULT, 0);
+ XCTestExpectation *expectation = [self expectationWithDescription:@"finished"];
+
+ const NSTimeInterval delay = 0.1;
+ executor->Schedule([self]() { self.counter++; }, absl::Milliseconds(delay));
+
+ executor->Shutdown();
+
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * 2 * NSEC_PER_SEC)), queue, ^{
+ XCTAssertEqual(self.counter, 0);
+ [expectation fulfill];
+ });
+
+ [self waitForExpectationsWithTimeout:delay * 5 handler:nil];
+}
+
+// Tests that a canceled runnable doesn't run.
+- (void)testCancelable {
+ std::unique_ptr<ScheduledExecutor> executor([self executor]);
+
+ // This runnable should run but not increment the counter because it sleeps for longer than the
+ // cancel below.
+ const NSTimeInterval delay = 0.1;
+ auto cancelable = executor->Schedule([self]() { self.counter++; }, absl::Seconds(delay));
+ XCTAssert(cancelable.get() != nullptr);
+
+ // Cancel the runnable.
+ cancelable->Cancel();
+
+ // Wait for the time interval to pass and verify that it didn't run.
+ [NSThread sleepForTimeInterval:delay * 1.1];
+ XCTAssertEqual(self.counter, 0);
+}
+
+@end
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/Platform/GNCSingleThreadExecutorTest.mm b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/Platform/GNCSingleThreadExecutorTest.mm
new file mode 100644
index 00000000000..31686f804ab
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/Platform/GNCSingleThreadExecutorTest.mm
@@ -0,0 +1,95 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import <XCTest/XCTest.h>
+
+#include "absl/time/time.h"
+#include "internal/platform/implementation/cancelable.h"
+#include "internal/platform/implementation/executor.h"
+#include "internal/platform/implementation/platform.h"
+#include "internal/platform/implementation/submittable_executor.h"
+#include "internal/platform/runnable.h"
+
+using location::nearby::Runnable;
+using location::nearby::api::ImplementationPlatform;
+using SingleThreadExecutor = location::nearby::api::SubmittableExecutor;
+
+@interface GNCSingleThreadExecutorTest : XCTestCase
+@property(atomic) int counter;
+@end
+
+@implementation GNCSingleThreadExecutorTest
+
+// Creates a SingleThreadExecutor.
+- (std::unique_ptr<SingleThreadExecutor>)executor {
+ std::unique_ptr<SingleThreadExecutor> executor =
+ ImplementationPlatform::CreateSingleThreadExecutor();
+ XCTAssert(executor != nullptr);
+ return executor;
+}
+
+// Tests that the executor executes runnables as expected.
+- (void)testRunnables {
+ std::unique_ptr<SingleThreadExecutor> executor([self executor]);
+
+ Runnable incrementer = [self]() { self.counter++; };
+
+ // Schedule two runnables that increment the counter.
+ executor->Execute(std::move(incrementer));
+ executor->Execute(std::move(incrementer));
+
+ // Check that the counter has the expected value after a moment.
+ [NSThread sleepForTimeInterval:0.01];
+ XCTAssertEqual(self.counter, 2);
+}
+
+// Tests that fails to execute when the executor is shut down.
+- (void)testShutdownBeforeInvokeTask {
+ std::unique_ptr<SingleThreadExecutor> executor([self executor]);
+
+ executor->Shutdown();
+
+ dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_TARGET_QUEUE_DEFAULT, 0);
+ XCTestExpectation *expectation = [self expectationWithDescription:@"finished"];
+
+ executor->Execute([self]() { self.counter++; });
+
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), queue, ^{
+ XCTAssertEqual(self.counter, 0);
+ [expectation fulfill];
+ });
+
+ [self waitForExpectationsWithTimeout:0.5 handler:nil];
+}
+
+// Tests that shutting down an existing task allows to complete.
+- (void)testShutdownToAllowExistingTaskComplete {
+ std::unique_ptr<SingleThreadExecutor> executor([self executor]);
+
+ dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_TARGET_QUEUE_DEFAULT, 0);
+ XCTestExpectation *expectation = [self expectationWithDescription:@"finished"];
+
+ executor->Execute([self]() { self.counter++; });
+
+ executor->Shutdown();
+
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), queue, ^{
+ XCTAssertEqual(self.counter, 1);
+ [expectation fulfill];
+ });
+
+ [self waitForExpectationsWithTimeout:0.5 handler:nil];
+}
+
+@end
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/Shared/GNCUtilsTest.mm b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/Shared/GNCUtilsTest.mm
new file mode 100644
index 00000000000..6773f10f5d9
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/ios/Tests/Shared/GNCUtilsTest.mm
@@ -0,0 +1,46 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import <XCTest/XCTest.h>
+
+#include "internal/platform/byte_array.h"
+#include "internal/platform/implementation/ios/Source/Platform/utils.h"
+
+using location::nearby::ByteArray;
+using location::nearby::ByteArrayFromNSData;
+using location::nearby::CppStringFromObjCString;
+using location::nearby::ObjCStringFromCppString;
+
+@interface GNCUtilsTest : XCTestCase
+@end
+
+@implementation GNCUtilsTest
+
+// Tests that strings can be converted between C++ and Obj-C.
+- (void)testStrings {
+ XCTAssert([ObjCStringFromCppString(std::string("Hey")) isEqual:@"Hey"]);
+ XCTAssert(CppStringFromObjCString(@"Dude") == std::string("Dude"));
+}
+
+// Tests that data objects can be converted between C++ and Obj-C.
+- (void)testDataObjects {
+ uint8_t bytes[] = {0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef};
+ ByteArray byteArray = ByteArray{(const char *)bytes, sizeof(bytes)};
+ NSData *nsData = [NSData dataWithBytes:bytes length:sizeof(bytes)];
+
+ XCTAssert([NSDataFromByteArray(byteArray) isEqual:nsData]);
+ XCTAssert(memcmp(ByteArrayFromNSData(nsData).data(), bytes, sizeof(bytes)) == 0);
+}
+
+@end
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/listenable_future.h b/chromium/third_party/nearby/src/internal/platform/implementation/listenable_future.h
new file mode 100644
index 00000000000..f91a83dc34d
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/listenable_future.h
@@ -0,0 +1,45 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_API_LISTENABLE_FUTURE_H_
+#define PLATFORM_API_LISTENABLE_FUTURE_H_
+
+#include <functional>
+#include <memory>
+
+#include "internal/platform/implementation/executor.h"
+#include "internal/platform/implementation/future.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/runnable.h"
+
+namespace location {
+namespace nearby {
+namespace api {
+
+// A Future that accepts completion listeners.
+//
+// https://guava.dev/releases/20.0/api/docs/com/google/common/util/concurrent/ListenableFuture.html
+template <typename T>
+class ListenableFuture : public Future<T> {
+ public:
+ ~ListenableFuture() override = default;
+
+ virtual void AddListener(Runnable runnable, Executor* executor) = 0;
+};
+
+} // namespace api
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_API_LISTENABLE_FUTURE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/log_message.h b/chromium/third_party/nearby/src/internal/platform/implementation/log_message.h
index 3f43c0bc352..3f43c0bc352 100644
--- a/chromium/third_party/nearby/src/cpp/platform/api/log_message.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/log_message.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/mutex.h b/chromium/third_party/nearby/src/internal/platform/implementation/mutex.h
index 19c11adcf1b..19c11adcf1b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/api/mutex.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/mutex.h
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/output_file.h b/chromium/third_party/nearby/src/internal/platform/implementation/output_file.h
new file mode 100644
index 00000000000..9c21f9eca67
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/output_file.h
@@ -0,0 +1,36 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_API_OUTPUT_FILE_H_
+#define PLATFORM_API_OUTPUT_FILE_H_
+
+#include "internal/platform/byte_array.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/output_stream.h"
+
+namespace location {
+namespace nearby {
+namespace api {
+
+// An OutputFile represents a writable file on the system.
+class OutputFile : public OutputStream {
+ public:
+ ~OutputFile() override = default;
+};
+
+} // namespace api
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_API_OUTPUT_FILE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/platform.h b/chromium/third_party/nearby/src/internal/platform/implementation/platform.h
new file mode 100644
index 00000000000..2bd8a147ab8
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/platform.h
@@ -0,0 +1,115 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_API_PLATFORM_H_
+#define PLATFORM_API_PLATFORM_H_
+
+#include <cstdint>
+#include <memory>
+#include <string>
+
+#include "absl/strings/string_view.h"
+#include "internal/platform/implementation/atomic_boolean.h"
+#include "internal/platform/implementation/atomic_reference.h"
+#include "internal/platform/implementation/ble.h"
+#include "internal/platform/implementation/ble_v2.h"
+#include "internal/platform/implementation/bluetooth_adapter.h"
+#include "internal/platform/implementation/bluetooth_classic.h"
+#include "internal/platform/implementation/condition_variable.h"
+#include "internal/platform/implementation/count_down_latch.h"
+#include "internal/platform/implementation/crypto.h"
+#include "internal/platform/implementation/input_file.h"
+#include "internal/platform/implementation/log_message.h"
+#include "internal/platform/implementation/mutex.h"
+#include "internal/platform/implementation/output_file.h"
+#include "internal/platform/implementation/scheduled_executor.h"
+#include "internal/platform/implementation/server_sync.h"
+#include "internal/platform/implementation/settable_future.h"
+#include "internal/platform/implementation/submittable_executor.h"
+#include "internal/platform/implementation/system_clock.h"
+#ifndef NO_WEBRTC
+#include "internal/platform/implementation/webrtc.h"
+#endif
+#include "internal/platform/implementation/wifi.h"
+#include "internal/platform/implementation/wifi_lan.h"
+#include "internal/platform/payload_id.h"
+
+namespace location {
+namespace nearby {
+namespace api {
+
+// API rework notes:
+// https://docs.google.com/spreadsheets/d/1erZNkX7pX8s5jWTHdxgjntxTMor3BGiY2H_fC_ldtoQ/edit#gid=381357998
+class ImplementationPlatform {
+ public:
+ // General platform support:
+ // - atomic variables (boolean, and any other copyable type)
+ // - synchronization primitives:
+ // - mutex (regular, and recursive)
+ // - condition variable (must work with regular mutex only)
+ // - Future<T> : to synchronize on Callable<T> scheduled to execute.
+ // - CountDownLatch : to ensure at least N threads are waiting.
+ // - file I/O
+ // - Logging
+
+ // Atomics:
+ // =======
+
+ // Atomic boolean: special case. Uses native platform atomics.
+ // Does not use locking.
+ // Does not use dynamic memory allocations in operations.
+ static std::unique_ptr<AtomicBoolean> CreateAtomicBoolean(bool initial_value);
+
+ // Supports enums and integers up to 32-bit.
+ // Does not use locking, if platform supports 32-bit atimics natively.
+ // Does not use dynamic memory allocations in operations.
+ static std::unique_ptr<AtomicUint32> CreateAtomicUint32(std::uint32_t value);
+
+ static std::unique_ptr<CountDownLatch> CreateCountDownLatch(
+ std::int32_t count);
+ static std::unique_ptr<Mutex> CreateMutex(Mutex::Mode mode);
+ static std::unique_ptr<ConditionVariable> CreateConditionVariable(
+ Mutex* mutex);
+ static std::unique_ptr<InputFile> CreateInputFile(PayloadId payload_id,
+ std::int64_t total_size);
+ static std::unique_ptr<OutputFile> CreateOutputFile(PayloadId payload_id);
+ static std::unique_ptr<LogMessage> CreateLogMessage(
+ const char* file, int line, LogMessage::Severity severity);
+
+ // Java-like Executors
+ static std::unique_ptr<SubmittableExecutor> CreateSingleThreadExecutor();
+ static std::unique_ptr<SubmittableExecutor> CreateMultiThreadExecutor(
+ std::int32_t max_concurrency);
+ static std::unique_ptr<ScheduledExecutor> CreateScheduledExecutor();
+
+ // Protocol implementations, domain-specific support
+ static std::unique_ptr<BluetoothAdapter> CreateBluetoothAdapter();
+ static std::unique_ptr<BluetoothClassicMedium> CreateBluetoothClassicMedium(
+ BluetoothAdapter&);
+ static std::unique_ptr<BleMedium> CreateBleMedium(BluetoothAdapter&);
+ static std::unique_ptr<ble_v2::BleMedium> CreateBleV2Medium(
+ BluetoothAdapter&);
+ static std::unique_ptr<ServerSyncMedium> CreateServerSyncMedium();
+ static std::unique_ptr<WifiMedium> CreateWifiMedium();
+ static std::unique_ptr<WifiLanMedium> CreateWifiLanMedium();
+#ifndef NO_WEBRTC
+ static std::unique_ptr<WebRtcMedium> CreateWebRtcMedium();
+#endif
+};
+
+} // namespace api
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_API_PLATFORM_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/scheduled_executor.h b/chromium/third_party/nearby/src/internal/platform/implementation/scheduled_executor.h
new file mode 100644
index 00000000000..95676a119e4
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/scheduled_executor.h
@@ -0,0 +1,50 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_API_SCHEDULED_EXECUTOR_H_
+#define PLATFORM_API_SCHEDULED_EXECUTOR_H_
+
+#include <cstdint>
+#include <functional>
+#include <memory>
+
+#include "absl/time/time.h"
+#include "internal/platform/implementation/cancelable.h"
+#include "internal/platform/implementation/executor.h"
+#include "internal/platform/runnable.h"
+
+namespace location {
+namespace nearby {
+namespace api {
+
+// An Executor that can schedule commands to run after a given delay, or to
+// execute periodically.
+//
+// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html
+class ScheduledExecutor : public Executor {
+ public:
+ ~ScheduledExecutor() override = default;
+ // Cancelable is kept both in the executor context, and in the caller context.
+ // We want Cancelable to live until both caller and executor are done with it.
+ // Exclusive ownership model does not work for this case;
+ // using std:shared_ptr<> instead if std::unique_ptr<>.
+ virtual std::shared_ptr<Cancelable> Schedule(Runnable&& runnable,
+ absl::Duration duration) = 0;
+};
+
+} // namespace api
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_API_SCHEDULED_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/server_sync.h b/chromium/third_party/nearby/src/internal/platform/implementation/server_sync.h
new file mode 100644
index 00000000000..e51f6f891af
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/server_sync.h
@@ -0,0 +1,76 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_API_SERVER_SYNC_H_
+#define PLATFORM_API_SERVER_SYNC_H_
+
+#include <string>
+
+#include "absl/strings/string_view.h"
+#include "internal/platform/byte_array.h"
+
+namespace location {
+namespace nearby {
+namespace api {
+
+// Abstraction that represents a Nearby endpoint exchanging data through
+// ServerSync Medium.
+class ServerSyncDevice {
+ public:
+ virtual ~ServerSyncDevice() = default;
+
+ virtual std::string GetName() const = 0;
+ virtual std::string GetGuid() const = 0;
+ virtual std::string GetOwnGuid() const = 0;
+};
+
+// Container of operations that can be performed over the Chrome Sync medium.
+class ServerSyncMedium {
+ public:
+ virtual ~ServerSyncMedium() = default;
+
+ virtual bool StartAdvertising(absl::string_view service_id,
+ absl::string_view endpoint_id,
+ const ByteArray& endpoint_info) = 0;
+ virtual void StopAdvertising(absl::string_view service_id) = 0;
+
+ class DiscoveredDeviceCallback {
+ public:
+ virtual ~DiscoveredDeviceCallback() = default;
+
+ // Called on a new ServerSyncDevice discovery.
+ virtual void OnDeviceDiscovered(ServerSyncDevice* device,
+ absl::string_view service_id,
+ absl::string_view endpoint_id,
+ const ByteArray& endpoint_info) = 0;
+ // Called when ServerSyncDevice is no longer reachable.
+ virtual void OnDeviceLost(ServerSyncDevice* device,
+ absl::string_view service_id) = 0;
+ };
+
+ // Returns true once the Chrome Sync scan has been initiated.
+ virtual bool StartDiscovery(
+ absl::string_view service_id,
+ const DiscoveredDeviceCallback& discovered_device_callback) = 0;
+ // Returns true once Chrome Sync scan for service_id is well and truly
+ // stopped; after this returns, there must be no more invocations of the
+ // DiscoveredDeviceCallback passed in to startScanning() for service_id.
+ virtual void StopDiscovery(absl::string_view service_id) = 0;
+};
+
+} // namespace api
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_API_SERVER_SYNC_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/settable_future.h b/chromium/third_party/nearby/src/internal/platform/implementation/settable_future.h
new file mode 100644
index 00000000000..ee49d291215
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/settable_future.h
@@ -0,0 +1,49 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_API_SETTABLE_FUTURE_H_
+#define PLATFORM_API_SETTABLE_FUTURE_H_
+
+#include "internal/platform/implementation/listenable_future.h"
+#include "internal/platform/exception.h"
+
+namespace location {
+namespace nearby {
+namespace api {
+
+// A SettableFuture is a type of Future whose result can be set.
+//
+// https://google.github.io/guava/releases/20.0/api/docs/com/google/common/util/concurrent/SettableFuture.html
+template <typename T>
+class SettableFuture : public ListenableFuture<T> {
+ public:
+ ~SettableFuture() override = default;
+
+ // Completes the future successfully. The value is returned to any waiters.
+ // Returns true, if value was set.
+ // Returns false, if Future is already in "done" state.
+ virtual bool Set(T value) = 0;
+
+ // Completes the future unsuccessfully. The exception value is returned to any
+ // waiters.
+ // Returns true, if exception was set.
+ // Returns false, if Future is already in "done" state.
+ virtual bool SetException(Exception exception) = 0;
+};
+
+} // namespace api
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_API_SETTABLE_FUTURE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/shared/BUILD b/chromium/third_party/nearby/src/internal/platform/implementation/shared/BUILD
new file mode 100644
index 00000000000..0260d0d525b
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/shared/BUILD
@@ -0,0 +1,87 @@
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+licenses(["notice"])
+
+cc_library(
+ name = "posix_mutex",
+ srcs = [
+ "posix_mutex.cc",
+ ],
+ hdrs = [
+ "posix_mutex.h",
+ ],
+ visibility = [
+ "//internal/platform/implementation:__subpackages__",
+ ],
+ deps = ["//internal/platform/implementation:types"],
+)
+
+cc_library(
+ name = "posix_condition_variable",
+ srcs = [
+ "posix_condition_variable.cc",
+ ],
+ hdrs = [
+ "posix_condition_variable.h",
+ ],
+ deps = [
+ ":posix_mutex",
+ "//internal/platform/implementation:types",
+ ],
+)
+
+cc_library(
+ name = "file",
+ srcs = ["file.cc"],
+ hdrs = ["file.h"],
+ visibility = [
+ "//internal/platform/implementation:__subpackages__",
+ ],
+ deps = [
+ "//internal/platform:base",
+ "//internal/platform/implementation:types",
+ "@com_google_absl//absl/memory",
+ "@com_google_absl//absl/strings",
+ ],
+)
+
+cc_library(
+ name = "count_down_latch",
+ srcs = ["count_down_latch.cc"],
+ hdrs = ["count_down_latch.h"],
+ visibility = [
+ "//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
+ "//internal/platform/implementation:__subpackages__",
+ ],
+ deps = [
+ "//internal/platform/implementation:types",
+ "@com_google_absl//absl/base:core_headers",
+ "@com_google_absl//absl/strings",
+ "@com_google_absl//absl/synchronization",
+ "@com_google_absl//absl/time",
+ ],
+)
+
+cc_test(
+ name = "file_test",
+ srcs = ["file_test.cc"],
+ deps = [
+ ":file",
+ "//file/util:temp_path",
+ "//internal/platform:base",
+ "@com_github_protobuf_matchers//protobuf-matchers",
+ "@com_google_absl//absl/strings",
+ "@com_google_googletest//:gtest_main",
+ ],
+)
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/shared/count_down_latch.cc b/chromium/third_party/nearby/src/internal/platform/implementation/shared/count_down_latch.cc
new file mode 100644
index 00000000000..3a667152dbf
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/shared/count_down_latch.cc
@@ -0,0 +1,54 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/shared/count_down_latch.h"
+
+namespace location {
+namespace nearby {
+namespace shared {
+
+// A synchronization aid that allows one or more threads to wait until a set of
+// operations being performed in other threads completes.
+//
+// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html
+CountDownLatch::CountDownLatch(int count) : count_(count) {}
+
+ExceptionOr<bool> CountDownLatch::Await(absl::Duration timeout) {
+ absl::MutexLock lock(&mutex_);
+ absl::Time deadline = absl::Now() + timeout;
+ while (count_ > 0) {
+ if (cond_.WaitWithDeadline(&mutex_, deadline)) {
+ return ExceptionOr<bool>(false);
+ }
+ }
+ return ExceptionOr<bool>(true);
+}
+
+Exception CountDownLatch::Await() {
+ absl::MutexLock lock(&mutex_);
+ while (count_ > 0) {
+ cond_.Wait(&mutex_);
+ }
+ return {Exception::kSuccess};
+}
+void CountDownLatch::CountDown() {
+ absl::MutexLock lock(&mutex_);
+ if (count_ > 0 && --count_ == 0) {
+ cond_.SignalAll();
+ }
+}
+
+} // namespace shared
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/shared/count_down_latch.h b/chromium/third_party/nearby/src/internal/platform/implementation/shared/count_down_latch.h
new file mode 100644
index 00000000000..2a7db549ec3
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/shared/count_down_latch.h
@@ -0,0 +1,53 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_SHARED_COUNT_DOWN_LATCH_H_
+#define PLATFORM_IMPL_SHARED_COUNT_DOWN_LATCH_H_
+
+#include "absl/base/thread_annotations.h"
+#include "absl/synchronization/mutex.h"
+#include "absl/time/clock.h"
+#include "internal/platform/implementation/count_down_latch.h"
+
+namespace location {
+namespace nearby {
+namespace shared {
+
+// A synchronization aid that allows one or more threads to wait until a set of
+// operations being performed in other threads completes.
+//
+// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html
+class CountDownLatch final : public api::CountDownLatch {
+ public:
+ explicit CountDownLatch(int count);
+ CountDownLatch(const CountDownLatch&) = delete;
+ CountDownLatch& operator=(const CountDownLatch&) = delete;
+ CountDownLatch(CountDownLatch&&) = delete;
+ CountDownLatch& operator=(CountDownLatch&&) = delete;
+ ExceptionOr<bool> Await(absl::Duration timeout) override;
+ Exception Await() override;
+ void CountDown() override;
+
+ private:
+ absl::Mutex mutex_; // Mutex to be used with cond_.Wait...() method family.
+ absl::CondVar cond_; // Condition to synchronize up to N waiting threads.
+ int count_
+ ABSL_GUARDED_BY(mutex_); // When zero, latch should release all waiters.
+};
+
+} // namespace shared
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_G3_COUNT_DOWN_LATCH_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/shared/file.cc b/chromium/third_party/nearby/src/internal/platform/implementation/shared/file.cc
new file mode 100644
index 00000000000..12a5e8d1fe3
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/shared/file.cc
@@ -0,0 +1,101 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/shared/file.h"
+
+#include <cstddef>
+#include <memory>
+
+#include "absl/memory/memory.h"
+#include "absl/strings/string_view.h"
+#include "internal/platform/exception.h"
+
+namespace location {
+namespace nearby {
+namespace shared {
+
+// InputFile
+std::unique_ptr<IOFile> IOFile::CreateInputFile(const absl::string_view path,
+ size_t size) {
+ return absl::WrapUnique(new IOFile(path, size));
+}
+
+IOFile::IOFile(const absl::string_view path, size_t size)
+ : file_(std::string(path.data(), path.size()),
+ std::ios::binary | std::ios::in),
+ path_(path),
+ total_size_(size) {}
+
+std::unique_ptr<IOFile> IOFile::CreateOutputFile(const absl::string_view path) {
+ return std::unique_ptr<IOFile>(new IOFile(path));
+}
+
+IOFile::IOFile(const absl::string_view path)
+ : file_(std::string(path.data(), path.size()),
+ std::ios::binary | std::ios::out | std::ios::trunc),
+ total_size_(0) {}
+
+ExceptionOr<ByteArray> IOFile::Read(std::int64_t size) {
+ if (!file_.is_open()) {
+ return ExceptionOr<ByteArray>{Exception::kIo};
+ }
+
+ if (file_.peek() == EOF) {
+ return ExceptionOr<ByteArray>{ByteArray{}};
+ }
+
+ if (!file_.good()) {
+ return ExceptionOr<ByteArray>{Exception::kIo};
+ }
+
+ ByteArray bytes(size);
+ std::unique_ptr<char[]> read_bytes{new char[size]};
+ file_.read(read_bytes.get(), static_cast<ptrdiff_t>(size));
+ auto num_bytes_read = file_.gcount();
+ if (num_bytes_read == 0) {
+ return ExceptionOr<ByteArray>{Exception::kIo};
+ }
+
+ return ExceptionOr<ByteArray>(ByteArray(read_bytes.get(), num_bytes_read));
+}
+
+Exception IOFile::Close() {
+ if (file_.is_open()) {
+ file_.close();
+ }
+ return {Exception::kSuccess};
+}
+
+Exception IOFile::Write(const ByteArray& data) {
+ if (!file_.is_open()) {
+ return {Exception::kIo};
+ }
+
+ if (!file_.good()) {
+ return {Exception::kIo};
+ }
+
+ file_.write(data.data(), data.size());
+ file_.flush();
+ return {file_.good() ? Exception::kSuccess : Exception::kIo};
+}
+
+Exception IOFile::Flush() {
+ file_.flush();
+ return {file_.good() ? Exception::kSuccess : Exception::kIo};
+}
+
+} // namespace shared
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/shared/file.h b/chromium/third_party/nearby/src/internal/platform/implementation/shared/file.h
new file mode 100644
index 00000000000..cfd912f5419
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/shared/file.h
@@ -0,0 +1,58 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_SHARED_FILE_H_
+#define PLATFORM_IMPL_SHARED_FILE_H_
+
+#include <cstdint>
+#include <fstream>
+
+#include "absl/strings/string_view.h"
+#include "internal/platform/implementation/input_file.h"
+#include "internal/platform/implementation/output_file.h"
+#include "internal/platform/exception.h"
+
+namespace location {
+namespace nearby {
+namespace shared {
+
+class IOFile final : public api::InputFile, public api::OutputFile {
+ public:
+ static std::unique_ptr<IOFile> CreateInputFile(const absl::string_view path,
+ size_t size);
+ static std::unique_ptr<IOFile> CreateOutputFile(const absl::string_view path);
+
+ ExceptionOr<ByteArray> Read(std::int64_t size) override;
+ std::string GetFilePath() const override {
+ return std::string(path_.data(), path_.size());
+ }
+ std::int64_t GetTotalSize() const override { return total_size_; }
+ Exception Close() override;
+
+ Exception Write(const ByteArray& data) override;
+ Exception Flush() override;
+
+ private:
+ explicit IOFile(const absl::string_view path, size_t size);
+ explicit IOFile(const absl::string_view path);
+ std::fstream file_;
+ absl::string_view path_;
+ std::int64_t total_size_;
+};
+
+} // namespace shared
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_SHARED_FILE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/shared/file_test.cc b/chromium/third_party/nearby/src/internal/platform/implementation/shared/file_test.cc
new file mode 100644
index 00000000000..367e9ff011b
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/shared/file_test.cc
@@ -0,0 +1,149 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/shared/file.h"
+
+#include <cstring>
+#include <fstream>
+#include <memory>
+#include <ostream>
+
+#include "file/util/temp_path.h"
+#include "gtest/gtest.h"
+#include "absl/strings/string_view.h"
+#include "internal/platform/byte_array.h"
+
+namespace location {
+namespace nearby {
+namespace shared {
+
+class FileTest : public ::testing::Test {
+ protected:
+ void SetUp() override {
+ temp_path_ = std::make_unique<TempPath>(TempPath::Local);
+ path_ = temp_path_->path() + "/file.txt";
+ std::ofstream output_file(path_);
+ file_ = std::fstream(path_, std::fstream::in | std::fstream::out);
+ }
+
+ void WriteToFile(absl::string_view text) {
+ file_ << text;
+ file_.flush();
+ size_ += text.size();
+ }
+
+ size_t GetSize() const { return size_; }
+
+ void AssertEquals(const ExceptionOr<ByteArray>& bytes,
+ const std::string& expected) {
+ EXPECT_TRUE(bytes.ok());
+ EXPECT_EQ(std::string(bytes.result()), expected);
+ }
+
+ void AssertEmpty(const ExceptionOr<ByteArray>& bytes) {
+ EXPECT_TRUE(bytes.ok());
+ EXPECT_TRUE(bytes.result().Empty());
+ }
+
+ static constexpr int64_t kMaxSize = 3;
+
+ std::unique_ptr<TempPath> temp_path_;
+ std::string path_;
+ std::fstream file_;
+ size_t size_ = 0;
+};
+
+TEST_F(FileTest, IOFile_NonExistentPathInput) {
+ auto io_file =
+ shared::IOFile::CreateInputFile("/not/a/valid/path.txt", GetSize());
+ ExceptionOr<ByteArray> read_result = io_file->Read(kMaxSize);
+ EXPECT_FALSE(read_result.ok());
+ EXPECT_TRUE(read_result.GetException().Raised(Exception::kIo));
+}
+
+TEST_F(FileTest, IOFile_GetFilePath) {
+ auto io_file = shared::IOFile::CreateInputFile(path_, GetSize());
+ EXPECT_EQ(io_file->GetFilePath(), path_);
+}
+
+TEST_F(FileTest, IOFile_EmptyFileEOF) {
+ auto io_file = shared::IOFile::CreateInputFile(path_, GetSize());
+ AssertEmpty(io_file->Read(kMaxSize));
+}
+
+TEST_F(FileTest, IOFile_ReadWorks) {
+ WriteToFile("abc");
+ auto io_file = shared::IOFile::CreateInputFile(path_, GetSize());
+ io_file->Read(kMaxSize);
+ SUCCEED();
+}
+
+TEST_F(FileTest, IOFile_ReadUntilEOF) {
+ WriteToFile("abc");
+ auto io_file = shared::IOFile::CreateInputFile(path_, GetSize());
+ AssertEquals(io_file->Read(kMaxSize), "abc");
+ AssertEmpty(io_file->Read(kMaxSize));
+}
+
+TEST_F(FileTest, IOFile_ReadWithSize) {
+ WriteToFile("abc");
+ auto io_file = shared::IOFile::CreateInputFile(path_, GetSize());
+ AssertEquals(io_file->Read(2), "ab");
+ AssertEquals(io_file->Read(1), "c");
+ AssertEmpty(io_file->Read(kMaxSize));
+}
+
+TEST_F(FileTest, IOFile_GetTotalSize) {
+ WriteToFile("abc");
+ auto io_file = shared::IOFile::CreateInputFile(path_, GetSize());
+ EXPECT_EQ(io_file->GetTotalSize(), 3);
+ AssertEquals(io_file->Read(1), "a");
+ EXPECT_EQ(io_file->GetTotalSize(), 3);
+}
+
+TEST_F(FileTest, IOFile_CloseInput) {
+ WriteToFile("abc");
+ auto io_file = shared::IOFile::CreateInputFile(path_, GetSize());
+ io_file->Close();
+ ExceptionOr<ByteArray> read_result = io_file->Read(kMaxSize);
+ EXPECT_FALSE(read_result.ok());
+ EXPECT_TRUE(read_result.GetException().Raised(Exception::kIo));
+}
+
+TEST_F(FileTest, IOFile_NonExistentPathOutput) {
+ auto io_file = shared::IOFile::CreateOutputFile("/not/a/valid/path.txt");
+ ByteArray bytes("a", 1);
+ EXPECT_TRUE(io_file->Write(bytes).Raised(Exception::kIo));
+}
+
+TEST_F(FileTest, IOFile_Write) {
+ auto io_file_output = shared::IOFile::CreateOutputFile(path_);
+ ByteArray bytes1("a");
+ ByteArray bytes2("bc");
+ EXPECT_EQ(io_file_output->Write(bytes1), Exception{Exception::kSuccess});
+ EXPECT_EQ(io_file_output->Write(bytes2), Exception{Exception::kSuccess});
+ auto io_file_input = shared::IOFile::CreateInputFile(path_, GetSize());
+ AssertEquals(io_file_input->Read(kMaxSize), "abc");
+}
+
+TEST_F(FileTest, IOFile_CloseOutput) {
+ auto io_file = shared::IOFile::CreateOutputFile(path_);
+ io_file->Close();
+ ByteArray bytes("a");
+ EXPECT_EQ(io_file->Write(bytes), Exception{Exception::kIo});
+}
+
+} // namespace shared
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/shared/posix_condition_variable.cc b/chromium/third_party/nearby/src/internal/platform/implementation/shared/posix_condition_variable.cc
new file mode 100644
index 00000000000..97cabc8c16f
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/shared/posix_condition_variable.cc
@@ -0,0 +1,44 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/shared/posix_condition_variable.h"
+
+namespace location {
+namespace nearby {
+namespace posix {
+
+ConditionVariable::ConditionVariable(Mutex* mutex)
+ : mutex_(mutex), attr_(), cond_() {
+ pthread_condattr_init(&attr_);
+
+ pthread_cond_init(&cond_, &attr_);
+}
+
+ConditionVariable::~ConditionVariable() {
+ pthread_cond_destroy(&cond_);
+
+ pthread_condattr_destroy(&attr_);
+}
+
+void ConditionVariable::Notify() { pthread_cond_broadcast(&cond_); }
+
+Exception ConditionVariable::Wait() {
+ pthread_cond_wait(&cond_, &(mutex_->mutex_));
+
+ return {Exception::kSuccess};
+}
+
+} // namespace posix
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/shared/posix_condition_variable.h b/chromium/third_party/nearby/src/internal/platform/implementation/shared/posix_condition_variable.h
new file mode 100644
index 00000000000..69b10a854a7
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/shared/posix_condition_variable.h
@@ -0,0 +1,45 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_SHARED_POSIX_CONDITION_VARIABLE_H_
+#define PLATFORM_IMPL_SHARED_POSIX_CONDITION_VARIABLE_H_
+
+#include <pthread.h>
+
+#include "internal/platform/implementation/condition_variable.h"
+#include "internal/platform/implementation/shared/posix_mutex.h"
+
+namespace location {
+namespace nearby {
+namespace posix {
+
+class ConditionVariable : public api::ConditionVariable {
+ public:
+ explicit ConditionVariable(Mutex* mutex);
+ ~ConditionVariable() override;
+
+ void Notify() override;
+ Exception Wait() override;
+
+ private:
+ Mutex* mutex_;
+ pthread_condattr_t attr_;
+ pthread_cond_t cond_;
+};
+
+} // namespace posix
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_SHARED_POSIX_CONDITION_VARIABLE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/shared/posix_mutex.cc b/chromium/third_party/nearby/src/internal/platform/implementation/shared/posix_mutex.cc
new file mode 100644
index 00000000000..efd769f2f9e
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/shared/posix_mutex.cc
@@ -0,0 +1,40 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/shared/posix_mutex.h"
+
+namespace location {
+namespace nearby {
+namespace posix {
+
+Mutex::Mutex() : attr_(), mutex_() {
+ pthread_mutexattr_init(&attr_);
+ pthread_mutexattr_settype(&attr_, PTHREAD_MUTEX_RECURSIVE);
+
+ pthread_mutex_init(&mutex_, &attr_);
+}
+
+Mutex::~Mutex() {
+ pthread_mutex_destroy(&mutex_);
+
+ pthread_mutexattr_destroy(&attr_);
+}
+
+void Mutex::Lock() { pthread_mutex_lock(&mutex_); }
+
+void Mutex::Unlock() { pthread_mutex_unlock(&mutex_); }
+
+} // namespace posix
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/shared/posix_mutex.h b/chromium/third_party/nearby/src/internal/platform/implementation/shared/posix_mutex.h
new file mode 100644
index 00000000000..2de9bf7aaba
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/shared/posix_mutex.h
@@ -0,0 +1,45 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_SHARED_POSIX_MUTEX_H_
+#define PLATFORM_IMPL_SHARED_POSIX_MUTEX_H_
+
+#include <pthread.h>
+
+#include "internal/platform/implementation/mutex.h"
+
+namespace location {
+namespace nearby {
+namespace posix {
+
+class ABSL_LOCKABLE Mutex : public api::Mutex {
+ public:
+ Mutex();
+ ~Mutex() override;
+
+ void Lock() ABSL_EXCLUSIVE_LOCK_FUNCTION() override;
+ void Unlock() ABSL_UNLOCK_FUNCTION() override;
+
+ private:
+ friend class ConditionVariable;
+
+ pthread_mutexattr_t attr_;
+ pthread_mutex_t mutex_;
+};
+
+} // namespace posix
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_SHARED_POSIX_MUTEX_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/submittable_executor.h b/chromium/third_party/nearby/src/internal/platform/implementation/submittable_executor.h
new file mode 100644
index 00000000000..347d01531cc
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/submittable_executor.h
@@ -0,0 +1,47 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_API_SUBMITTABLE_EXECUTOR_H_
+#define PLATFORM_API_SUBMITTABLE_EXECUTOR_H_
+
+#include <functional>
+#include <memory>
+
+#include "internal/platform/implementation/executor.h"
+#include "internal/platform/implementation/future.h"
+#include "internal/platform/runnable.h"
+
+namespace location {
+namespace nearby {
+namespace api {
+
+// Main interface to be used by platform as a base class for
+// - MultiThreadExecutorWrapper
+// - SingleThreadExecutorWrapper
+// Platform must override bool submit(std::function<void()>) method.
+class SubmittableExecutor : public Executor {
+ public:
+ ~SubmittableExecutor() override = default;
+
+ // Submit a callable (with no delay).
+ // Returns true, if callable was submitted, false otherwise.
+ // Callable is not submitted if shutdown is in progress.
+ virtual bool DoSubmit(Runnable&& wrapped_callable) = 0;
+};
+
+} // namespace api
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_API_SUBMITTABLE_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/system_clock.h b/chromium/third_party/nearby/src/internal/platform/implementation/system_clock.h
new file mode 100644
index 00000000000..4e0e1a25f2b
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/system_clock.h
@@ -0,0 +1,37 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_API_SYSTEM_CLOCK_H_
+#define PLATFORM_API_SYSTEM_CLOCK_H_
+
+#include "absl/time/clock.h"
+#include "internal/platform/exception.h"
+
+namespace location {
+namespace nearby {
+
+class SystemClock final {
+ public:
+ // Initialize global system state.
+ static void Init();
+ // Returns current absolute time. It is guaranteed to be monotonic.
+ static absl::Time ElapsedRealtime();
+ // Pauses current thread for the specified duration.
+ static Exception Sleep(absl::Duration duration);
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_API_SYSTEM_CLOCK_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/webrtc.h b/chromium/third_party/nearby/src/internal/platform/implementation/webrtc.h
new file mode 100644
index 00000000000..723d682eae3
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/webrtc.h
@@ -0,0 +1,73 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_API_WEBRTC_H_
+#define PLATFORM_API_WEBRTC_H_
+
+#include <functional>
+#include <memory>
+#include <string>
+
+#include "absl/strings/string_view.h"
+#include "connections/implementation/proto/offline_wire_formats.pb.h"
+#include "internal/platform/byte_array.h"
+#include "webrtc/api/peer_connection_interface.h"
+
+namespace location {
+namespace nearby {
+namespace api {
+
+class WebRtcSignalingMessenger {
+ public:
+ using OnSignalingMessageCallback = std::function<void(const ByteArray&)>;
+ using OnSignalingCompleteCallback = std::function<void(bool)>;
+
+ virtual ~WebRtcSignalingMessenger() = default;
+
+ virtual bool SendMessage(absl::string_view peer_id,
+ const ByteArray& message) = 0;
+
+ virtual bool StartReceivingMessages(
+ OnSignalingMessageCallback on_message_callback,
+ OnSignalingCompleteCallback on_complete_callback) = 0;
+ virtual void StopReceivingMessages() = 0;
+};
+
+class WebRtcMedium {
+ public:
+ using PeerConnectionCallback =
+ std::function<void(rtc::scoped_refptr<webrtc::PeerConnectionInterface>)>;
+
+ virtual ~WebRtcMedium() = default;
+
+ // Gets the default two-letter country code associated with current locale.
+ // For example, en_US locale resolves to "US".
+ virtual const std::string GetDefaultCountryCode() = 0;
+
+ // Creates and returns a new webrtc::PeerConnectionInterface object via
+ // |callback|.
+ virtual void CreatePeerConnection(webrtc::PeerConnectionObserver* observer,
+ PeerConnectionCallback callback) = 0;
+
+ // Returns a signaling messenger for sending WebRTC signaling messages.
+ virtual std::unique_ptr<WebRtcSignalingMessenger> GetSignalingMessenger(
+ absl::string_view self_id,
+ const connections::LocationHint& location_hint) = 0;
+};
+
+} // namespace api
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_API_WEBRTC_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/api/wifi.h b/chromium/third_party/nearby/src/internal/platform/implementation/wifi.h
index 1f0f5b75cf1..1f0f5b75cf1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/api/wifi.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/wifi.h
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/wifi_lan.h b/chromium/third_party/nearby/src/internal/platform/implementation/wifi_lan.h
new file mode 100644
index 00000000000..4d32c7a1428
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/wifi_lan.h
@@ -0,0 +1,157 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_API_WIFI_LAN_H_
+#define PLATFORM_API_WIFI_LAN_H_
+
+#include <string>
+
+#include "internal/platform/cancellation_flag.h"
+#include "internal/platform/input_stream.h"
+#include "internal/platform/listeners.h"
+#include "internal/platform/nsd_service_info.h"
+#include "internal/platform/output_stream.h"
+
+namespace location {
+namespace nearby {
+namespace api {
+
+class WifiLanSocket {
+ public:
+ virtual ~WifiLanSocket() = default;
+
+ // Returns the InputStream of the WifiLanSocket.
+ // On error, returned stream will report Exception::kIo on any operation.
+ //
+ // The returned object is not owned by the caller, and can be invalidated once
+ // the WifiLanSocket object is destroyed.
+ virtual InputStream& GetInputStream() = 0;
+
+ // Returns the OutputStream of the WifiLanSocket.
+ // On error, returned stream will report Exception::kIo on any operation.
+ //
+ // The returned object is not owned by the caller, and can be invalidated once
+ // the WifiLanSocket object is destroyed.
+ virtual OutputStream& GetOutputStream() = 0;
+
+ // Returns Exception::kIo on error, Exception::kSuccess otherwise.
+ virtual Exception Close() = 0;
+};
+
+class WifiLanServerSocket {
+ public:
+ virtual ~WifiLanServerSocket() = default;
+
+ // Returns ip address.
+ virtual std::string GetIPAddress() const = 0;
+
+ // Returns port.
+ virtual int GetPort() const = 0;
+
+ // Blocks until either:
+ // - at least one incoming connection request is available, or
+ // - ServerSocket is closed.
+ // On success, returns connected socket, ready to exchange data.
+ // Returns nullptr on error.
+ // Once error is reported, it is permanent, and ServerSocket has to be closed.
+ virtual std::unique_ptr<WifiLanSocket> Accept() = 0;
+
+ // Returns Exception::kIo on error, Exception::kSuccess otherwise.
+ virtual Exception Close() = 0;
+};
+
+// Container of operations that can be performed over the WifiLan medium.
+class WifiLanMedium {
+ public:
+ virtual ~WifiLanMedium() = default;
+
+ // Starts WifiLan advertising.
+ //
+ // nsd_service_info - NsdServiceInfo data that's advertised through mDNS
+ // service.
+ // On success if the service is now advertising.
+ // On error if the service cannot start to advertise or the service type in
+ // NsdServiceInfo has been passed previously which StopAdvertising is not
+ // been called.
+ virtual bool StartAdvertising(const NsdServiceInfo& nsd_service_info) = 0;
+
+ // Stops WifiLan advertising.
+ //
+ // nsd_service_info - NsdServiceInfo data that's advertised through mDNS
+ // service.
+ // On success if the service stops advertising.
+ // On error if the service cannot stop advertising or the service type in
+ // NsdServiceInfo cannot be found.
+ virtual bool StopAdvertising(const NsdServiceInfo& nsd_service_info) = 0;
+
+ // Callback that is invoked when a discovered service is found or lost.
+ struct DiscoveredServiceCallback {
+ std::function<void(NsdServiceInfo service_info)> service_discovered_cb =
+ DefaultCallback<NsdServiceInfo>();
+ std::function<void(NsdServiceInfo service_info)> service_lost_cb =
+ DefaultCallback<NsdServiceInfo>();
+ };
+
+ // Starts the discovery of nearby WifiLan services.
+ //
+ // service_type - mDNS service type.
+ // callback - the instance of DiscoveredServiceCallback.
+ // Returns true once the WifiLan discovery has been initiated. The
+ // service_type is associated with callback.
+ virtual bool StartDiscovery(const std::string& service_type,
+ DiscoveredServiceCallback callback) = 0;
+
+ // Stops the discovery of nearby WifiLan services.
+ //
+ // service_type - The one assigned in StartDiscovery.
+ // On success if the service_type is matched to the callback and will be
+ // removed from the list. If list is empty then stops the WifiLan
+ // discovery service.
+ // On error if the service_type is not existed, then return immediately.
+ virtual bool StopDiscovery(const std::string& service_type) = 0;
+
+ // Connects to a WifiLan service.
+ // On success, returns a new WifiLanSocket.
+ // On error, returns nullptr.
+ virtual std::unique_ptr<WifiLanSocket> ConnectToService(
+ const NsdServiceInfo& remote_service_info,
+ CancellationFlag* cancellation_flag) = 0;
+
+ // Connects to a WifiLan service by ip address and port.
+ // On success, returns a new WifiLanSocket.
+ // On error, returns nullptr.
+ virtual std::unique_ptr<WifiLanSocket> ConnectToService(
+ const std::string& ip_address, int port,
+ CancellationFlag* cancellation_flag) = 0;
+
+ // Listens for incoming connection.
+ //
+ // port - A port number.
+ // 0 : use a random port.
+ // 1~65536 : open a server socket on that exact port.
+ // On success, returns a new WifiLanServerSocket.
+ // On error, returns nullptr.
+ virtual std::unique_ptr<WifiLanServerSocket> ListenForService(
+ int port = 0) = 0;
+
+ // Returns the port range as a pair of min and max port.
+ virtual absl::optional<std::pair<std::int32_t, std::int32_t>>
+ GetDynamicPortRange() = 0;
+};
+
+} // namespace api
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_API_WIFI_LAN_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/BUILD b/chromium/third_party/nearby/src/internal/platform/implementation/windows/BUILD
new file mode 100644
index 00000000000..1b6566ba8b5
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/BUILD
@@ -0,0 +1,172 @@
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+licenses(["notice"])
+
+cc_library(
+ name = "types",
+ srcs = [
+ "log_message.cc",
+ ],
+ hdrs = [
+ "atomic_boolean.h",
+ "atomic_reference.h",
+ "bluetooth_adapter.h",
+ "cancelable.h",
+ "condition_variable.h",
+ "executor.h",
+ "future.h",
+ "input_file.h",
+ "listenable_future.h",
+ "log_message.h",
+ "mutex.h",
+ "output_file.h",
+ "scheduled_executor.h",
+ "settable_future.h",
+ "submittable_executor.h",
+ "utils.h",
+ ],
+ deps = [
+ "//base",
+ "//base:stringprintf",
+ "//internal/platform:base",
+ "//internal/platform/implementation:types",
+ ],
+)
+
+cc_library(
+ name = "comm",
+ hdrs = [
+ "ble.h",
+ "bluetooth_adapter.h",
+ "bluetooth_classic.h",
+ "bluetooth_classic_device.h",
+ "bluetooth_classic_medium.h",
+ "bluetooth_classic_server_socket.h",
+ "bluetooth_classic_socket.h",
+ "condition_variable.h",
+ "executor.h",
+ "mutex.h",
+ "runner.h",
+ "scheduled_executor.h",
+ "server_sync.h",
+ "submittable_executor.h",
+ "thread_pool.h",
+ "webrtc.h",
+ "wifi.h",
+ "wifi_lan.h",
+ ],
+ visibility = ["//visibility:private"],
+ deps = [
+ "//internal/platform:base",
+ "//internal/platform/implementation:comm",
+ "//internal/platform/implementation/windows/generated:types",
+ ],
+)
+
+cc_library(
+ name = "crypto",
+ srcs = [
+ "crypto.cc",
+ ],
+ visibility = ["//visibility:private"],
+ deps = [
+ "//internal/platform:base",
+ "//internal/platform/implementation:types",
+ "@boringssl//:crypto",
+ "@com_google_absl//absl/strings",
+ ],
+)
+
+cc_library(
+ name = "windows",
+ srcs = [
+ "bluetooth_adapter.cc",
+ "bluetooth_classic_device.cc",
+ "bluetooth_classic_medium.cc",
+ "bluetooth_classic_server_socket.cc",
+ "bluetooth_classic_socket.cc",
+ "executor.cc",
+ "platform.cc",
+ "scheduled_executor.cc",
+ "submittable_executor.cc",
+ "system_clock.cc",
+ "thread_pool.cc",
+ "utils.cc",
+ "wifi_lan_medium.cc",
+ "wifi_lan_server_socket.cc",
+ "wifi_lan_socket.cc",
+ ],
+ copts = ["-Ithird_party/nearby/internal/platform/implementation/windows/generated"],
+ defines = ["_SILENCE_CLANG_COROUTINE_MESSAGE"],
+ visibility = [
+ "//connections/clients/windows:__subpackages__",
+ ],
+ deps = [
+ ":comm",
+ ":crypto", # build_cleaner: keep
+ ":types",
+ "//internal/platform:types",
+ "//internal/platform/implementation:comm",
+ "//internal/platform/implementation:platform",
+ "//internal/platform/implementation:types",
+ "//internal/platform/implementation/shared:count_down_latch",
+ "//internal/platform/implementation/shared:file",
+ "//internal/platform/implementation/windows/generated:types",
+ ],
+)
+
+cc_library(
+ name = "test_utils",
+ srcs = [
+ "test_utils.cc",
+ ],
+ hdrs = [
+ "test_data.h",
+ "test_utils.h",
+ ],
+ visibility = [
+ "//connections/clients/windows:__subpackages__",
+ ],
+ deps = [
+ "//internal/platform:base",
+ ],
+)
+
+cc_test(
+ name = "impl_test",
+ size = "small",
+ srcs = [
+ "atomic_boolean_test.cc",
+ "atomic_reference_test.cc",
+ "count_down_latch_test.cc",
+ "crypto_test.cc",
+ "executor_test.cc",
+ "scheduled_executor_test.cc",
+ "submittable_executor_test.cc",
+ ],
+ copts = ["-Iplatform/implementation/windows/generated -DCORE_ADAPTER_DLL"],
+ deps = [
+ ":comm",
+ ":crypto",
+ ":test_utils",
+ ":types",
+ "//internal/platform:base",
+ "//internal/platform:logging",
+ "//internal/platform/implementation:platform",
+ "//internal/platform/implementation/windows",
+ "//internal/platform/implementation/windows/generated:types",
+ "@com_github_protobuf_matchers//protobuf-matchers",
+ "@com_google_googletest//:gtest_main",
+ ],
+)
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/atomic_boolean.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/atomic_boolean.h
new file mode 100644
index 00000000000..142d17c1ab9
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/atomic_boolean.h
@@ -0,0 +1,45 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_ATOMIC_BOOLEAN_H_
+#define PLATFORM_IMPL_WINDOWS_ATOMIC_BOOLEAN_H_
+
+#include <atomic>
+
+#include "internal/platform/implementation/atomic_boolean.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+// A boolean value that may be updated atomically.
+class AtomicBoolean : public api::AtomicBoolean {
+ public:
+ ~AtomicBoolean() override = default;
+
+ // Atomically read and return current value.
+ bool Get() const override { return atomic_boolean_; };
+
+ // Atomically exchange original value with a new one. Return previous value.
+ bool Set(bool value) override { return atomic_boolean_.exchange(value); };
+
+ private:
+ std::atomic_bool atomic_boolean_;
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_WINDOWS_ATOMIC_BOOLEAN_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/atomic_boolean_test.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/atomic_boolean_test.cc
new file mode 100644
index 00000000000..7c20d6e2d89
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/atomic_boolean_test.cc
@@ -0,0 +1,32 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/windows/atomic_boolean.h"
+
+#include "gtest/gtest.h"
+
+TEST(atomic_boolean, SuccessfulCreation) {
+ // Arrange
+ location::nearby::windows::AtomicBoolean atomicBoolean;
+ bool oldValue = true;
+ bool result = false;
+
+ // Act
+ oldValue = atomicBoolean.Set(true);
+ result = atomicBoolean.Get();
+
+ // Assert
+ EXPECT_TRUE(result);
+ EXPECT_FALSE(oldValue);
+}
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/atomic_reference.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/atomic_reference.h
new file mode 100644
index 00000000000..1e83c2a77b6
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/atomic_reference.h
@@ -0,0 +1,45 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_ATOMIC_REFERENCE_H_
+#define PLATFORM_IMPL_WINDOWS_ATOMIC_REFERENCE_H_
+
+#include <atomic>
+
+#include "internal/platform/implementation/atomic_reference.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+// Type that allows 32-bit atomic reads and writes.
+class AtomicUint32 : public api::AtomicUint32 {
+ public:
+ ~AtomicUint32() override = default;
+
+ // Atomically reads and returns stored value.
+ std::uint32_t Get() const override { return atomic_uint32_; };
+
+ // Atomically stores value.
+ void Set(std::uint32_t value) override { atomic_uint32_ = value; }
+
+ private:
+ std::atomic_int32_t atomic_uint32_ = 0;
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_WINDOWS_ATOMIC_REFERENCE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/atomic_reference_test.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/atomic_reference_test.cc
new file mode 100644
index 00000000000..c5565b3abc4
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/atomic_reference_test.cc
@@ -0,0 +1,72 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/windows/atomic_reference.h"
+
+#include "gtest/gtest.h"
+
+TEST(atomic_reference, SuccessfulCreation) {
+ // Arrange
+ location::nearby::windows::AtomicUint32 atomicUint32;
+ uint32_t result = UINT32_MAX;
+ const uint32_t expected = 0;
+
+ // Act
+ result = atomicUint32.Get();
+
+ // Assert
+ EXPECT_EQ(result, expected);
+}
+
+TEST(atomic_reference, SuccessfulMaxSet) {
+ // Arrange
+ location::nearby::windows::AtomicUint32 atomicUint32;
+ uint32_t result = 0;
+ const uint32_t expected = UINT32_MAX;
+
+ // Act
+ atomicUint32.Set(UINT32_MAX);
+ result = atomicUint32.Get();
+
+ // Assert
+ EXPECT_EQ(result, expected);
+}
+
+TEST(atomic_reference, SuccessfulMinSet) {
+ // Arrange
+ location::nearby::windows::AtomicUint32 atomicUint32;
+ uint32_t result = UINT32_MAX;
+ const uint32_t expected = 0;
+
+ // Act
+ atomicUint32.Set(0);
+ result = atomicUint32.Get();
+
+ // Assert
+ EXPECT_EQ(result, expected);
+}
+
+TEST(atomic_reference, SetNegativeOneReturnsMAXUINT) {
+ // Arrange
+ location::nearby::windows::AtomicUint32 atomicUint32;
+ uint32_t result = 0;
+ const uint32_t expected = UINT32_MAX;
+
+ // Act
+ atomicUint32.Set(-1); // Try Set -1, should actually store UINT32_MAX
+ result = atomicUint32.Get();
+
+ // Assert
+ EXPECT_EQ(result, expected);
+}
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/ble.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/ble.h
new file mode 100644
index 00000000000..807b4e720ed
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/ble.h
@@ -0,0 +1,155 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_BLE_H_
+#define PLATFORM_IMPL_WINDOWS_BLE_H_
+
+#include "internal/platform/implementation/ble.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/input_stream.h"
+#include "internal/platform/output_stream.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+// Opaque wrapper over a BLE peripheral. Must contain enough data about a
+// particular BLE device to connect to its GATT server.
+class BlePeripheral : public api::BlePeripheral {
+ public:
+ // TODO(b/184975123): replace with real implementation.
+ ~BlePeripheral() override = default;
+
+ // TODO(b/184975123): replace with real implementation.
+ std::string GetName() const override { return std::string{""}; }
+ // TODO(b/184975123): replace with real implementation.
+ ByteArray GetAdvertisementBytes(
+ const std::string& service_id) const override {
+ return ByteArray{};
+ }
+};
+
+class BleSocket : public api::BleSocket {
+ public:
+ // TODO(b/184975123): replace with real implementation.
+ ~BleSocket() override;
+
+ // Returns the InputStream of the BleSocket.
+ // On error, returned stream will report Exception::kIo on any operation.
+ //
+ // The returned object is not owned by the caller, and can be invalidated once
+ // the BleSocket object is destroyed.
+ // TODO(b/184975123): replace with real implementation.
+ InputStream& GetInputStream() override { return fake_input_stream_; }
+
+ // Returns the OutputStream of the BleSocket.
+ // On error, returned stream will report Exception::kIo on any operation.
+ //
+ // The returned object is not owned by the caller, and can be invalidated once
+ // the BleSocket object is destroyed.
+ // TODO(b/184975123): replace with real implementation.
+ OutputStream& GetOutputStream() override { return fake_output_stream_; }
+
+ // Conforms to the same contract as
+ // https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#close().
+ //
+ // Returns Exception::kIo on error, Exception::kSuccess otherwise.
+ // TODO(b/184975123): replace with real implementation.
+ Exception Close() override { return Exception{}; }
+
+ // Returns valid BlePeripheral pointer if there is a connection, and
+ // nullptr otherwise.
+ // TODO(b/184975123): replace with real implementation.
+ BlePeripheral* GetRemotePeripheral() override { return nullptr; }
+
+ // Unhooked InputStream & OutputStream for empty implementation.
+ // TODO(b/184975123): replace with real implementation.
+ private:
+ class FakeInputStream : public InputStream {
+ ~FakeInputStream() override = default;
+ ExceptionOr<ByteArray> Read(std::int64_t size) override {
+ return ExceptionOr<ByteArray>(Exception::kFailed);
+ }
+ Exception Close() override { return {.value = Exception::kFailed}; }
+ };
+ class FakeOutputStream : public OutputStream {
+ ~FakeOutputStream() override = default;
+
+ Exception Write(const ByteArray& data) override {
+ return {.value = Exception::kFailed};
+ }
+ Exception Flush() override { return {.value = Exception::kFailed}; }
+ Exception Close() override { return {.value = Exception::kFailed}; }
+ };
+ FakeInputStream fake_input_stream_;
+ FakeOutputStream fake_output_stream_;
+};
+
+// Container of operations that can be performed over the BLE medium.
+class BleMedium : public api::BleMedium {
+ public:
+ // TODO(b/184975123): replace with real implementation.
+ ~BleMedium() override = default;
+
+ // TODO(b/184975123): replace with real implementation.
+ bool StartAdvertising(
+ const std::string& service_id, const ByteArray& advertisement_bytes,
+ const std::string& fast_advertisement_service_uuid) override {
+ return false;
+ }
+ // TODO(b/184975123): replace with real implementation.
+ bool StopAdvertising(const std::string& service_id) override { return false; }
+
+ // Returns true once the BLE scan has been initiated.
+ // TODO(b/184975123): replace with real implementation.
+ bool StartScanning(const std::string& service_id,
+ const std::string& fast_advertisement_service_uuid,
+ DiscoveredPeripheralCallback callback) override {
+ return false;
+ }
+
+ // Returns true once BLE scanning for service_id is well and truly stopped;
+ // after this returns, there must be no more invocations of the
+ // DiscoveredPeripheralCallback passed in to StartScanning() for service_id.
+ // TODO(b/184975123): replace with real implementation.
+ bool StopScanning(const std::string& service_id) override { return false; }
+
+ // Returns true once BLE socket connection requests to service_id can be
+ // accepted.
+ // TODO(b/184975123): replace with real implementation.
+ bool StartAcceptingConnections(const std::string& service_id,
+ AcceptedConnectionCallback callback) override {
+ return false;
+ }
+ // TODO(b/184975123): replace with real implementation.
+ bool StopAcceptingConnections(const std::string& service_id) override {
+ return false;
+ }
+
+ // Connects to a BLE peripheral.
+ // On success, returns a new BleSocket.
+ // On error, returns nullptr.
+ // TODO(b/184975123): replace with real implementation.
+ std::unique_ptr<api::BleSocket> Connect(
+ api::BlePeripheral& peripheral, const std::string& service_id,
+ CancellationFlag* cancellation_flag) override {
+ return nullptr;
+ }
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_WINDOWS_BLE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_adapter.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_adapter.cc
new file mode 100644
index 00000000000..6f92b5150bb
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_adapter.cc
@@ -0,0 +1,456 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/windows/bluetooth_adapter.h"
+
+#include <windows.h>
+#include <winioctl.h>
+#include <bthdef.h>
+#include <bthioctl.h>
+#include <cfgmgr32.h>
+#include <devguid.h>
+#include <initguid.h>
+#include <objbase.h>
+#include <setupapi.h>
+#include <stdio.h>
+#include <usbiodef.h>
+
+#include <string>
+
+#include "absl/strings/str_format.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Foundation.h"
+#include "internal/platform/implementation/windows/utils.h"
+#include "internal/platform/logging.h"
+
+typedef std::basic_string<TCHAR> tstring;
+
+// IOCTL to get local radio information
+#define BTH_GET_DEVICE_INFO_IOCTL 0x411008
+
+#define BUFFER_SIZE 64
+#define FILE_NAME_SIZE 1024
+
+#define REGISTRY_QUERY_FORMAT \
+ "SYSTEM\\ControlSet001\\Enum\\%s\\Device Parameters"
+
+#define BLUETOOTH_RADIO_REGISTRY_NAME_KEY "Local Name"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+BluetoothAdapter::BluetoothAdapter()
+ : windows_bluetooth_adapter_(winrt::Windows::Devices::Bluetooth::
+ BluetoothAdapter::GetDefaultAsync()
+ .get()) {
+ // Gets the radio represented by this Bluetooth adapter.
+ // https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.bluetoothadapter.getradioasync?view=winrt-20348
+ windows_bluetooth_radio_ = windows_bluetooth_adapter_.GetRadioAsync().get();
+}
+
+// Synchronously sets the status of the BluetoothAdapter to 'status', and
+// returns true if the operation was a success.
+bool BluetoothAdapter::SetStatus(Status status) {
+ if (status == Status::kDisabled) {
+ // An asynchronous operation that attempts to set the state of the radio
+ // represented by this object.
+ // https://docs.microsoft.com/en-us/uwp/api/windows.devices.radios.radio.setstateasync?view=winrt-20348
+ windows_bluetooth_radio_.SetStateAsync(RadioState::Off).get();
+ } else {
+ windows_bluetooth_radio_.SetStateAsync(RadioState::On).get();
+ }
+ return true;
+}
+
+// Returns true if the BluetoothAdapter's current status is
+// Status::Value::kEnabled.
+bool BluetoothAdapter::IsEnabled() const {
+ // Gets the current state of the radio represented by this object.
+ // https://docs.microsoft.com/en-us/uwp/api/windows.devices.radios.radio.state?view=winrt-20348
+ return windows_bluetooth_radio_.State() == RadioState::On;
+}
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getScanMode()
+//
+// Returns ScanMode::kUnknown on error.
+BluetoothAdapter::ScanMode BluetoothAdapter::GetScanMode() const {
+ return scan_mode_;
+}
+
+// Synchronously sets the scan mode of the adapter, and returns true if the
+// operation was a success.
+bool BluetoothAdapter::SetScanMode(ScanMode scan_mode) {
+ scan_mode_ = scan_mode;
+
+ if (scan_mode_changed_ != nullptr) {
+ scan_mode_changed_(scan_mode);
+ }
+
+ return true;
+}
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getName()
+// Returns an empty string on error
+std::string BluetoothAdapter::GetName() const {
+ char *instanceID = GetGenericBluetoothAdapterInstanceID();
+
+ if (instanceID == NULL) {
+ NEARBY_LOGS(ERROR)
+ << __func__ << ": Failed to get Generic Bluetooth Adapter InstanceID";
+ return std::string();
+ }
+ // Add 1 to length to get size (including null)
+ // Modify the InstanceID to the format that the Registry expects
+ char *instanceIDModified = new char[(strlen(instanceID) + 1) * sizeof(char)];
+ absl::SNPrintF(instanceIDModified,
+ size_t((strlen(instanceID) + 1) * sizeof(char)), "%s",
+ instanceID);
+ find_and_replace(instanceIDModified, "\\", "#");
+
+ // Change radio module local name in registry
+ HKEY hKey;
+ char rmLocalNameKey[FILE_NAME_SIZE] = {0};
+ LSTATUS ret;
+
+ absl::SNPrintF(rmLocalNameKey, sizeof(rmLocalNameKey), REGISTRY_QUERY_FORMAT,
+ instanceID);
+
+ // Opens the specified registry key.
+ // https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regopenkeyexa
+ ret = RegOpenKeyExA(
+ HKEY_LOCAL_MACHINE, // A handle to an open registry key, using
+ // predefined key for local machine
+ rmLocalNameKey, // The name of the registry subkey to be opened.
+ 0L, // Specifies the option to apply when opening the key.
+ KEY_QUERY_VALUE, // A mask that specifies the desired access rights to
+ // the key to be opened.
+ &hKey); // A pointer to a variable that receives a handle to the opened
+ // key
+
+ if (ret == ERROR_SUCCESS) {
+ BYTE rmLocalName[FILE_NAME_SIZE] = {0};
+ DWORD rmLocalNameSize = FILE_NAME_SIZE;
+ DWORD valueType;
+
+ LSTATUS status =
+ // Retrieves the type and data for the specified value name associated
+ // with an open registry key.
+ // https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regqueryvalueexa
+ RegQueryValueExA(
+ hKey, // A handle to an open registry key.
+ BLUETOOTH_RADIO_REGISTRY_NAME_KEY, // The name of the registry
+ // value.
+ nullptr, // This parameter is reserved and must be NULL.
+ &valueType, // A pointer to a variable that receives a code
+ // indicating the type of data stored in the
+ // specified value.
+ &rmLocalName[0], // A pointer to a buffer that receives the
+ // value's data.
+ &rmLocalNameSize); // A pointer to a variable that specifies the
+ // size of the buffer pointed to by the lpData
+ // parameter, in bytes.
+
+ // Closes a handle to the specified registry key.
+ // https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regclosekey
+ RegCloseKey(hKey);
+
+ if (status == ERROR_SUCCESS) {
+ char str[FILE_NAME_SIZE]{0};
+ memcpy(str, rmLocalName, rmLocalNameSize);
+ return std::string(str);
+ }
+ }
+
+ // The local name is not in the registry, return the machine name
+ char localName[FILE_NAME_SIZE];
+ DWORD nameSize = FILE_NAME_SIZE;
+
+ // Retrieves the NetBIOS name of the local computer.
+ // https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getcomputernamea
+ if (GetComputerNameA(localName, &nameSize)) {
+ return std::string(localName);
+ }
+
+ // If we're here, we couldn't get a local name, this should never happen
+ NEARBY_LOGS(ERROR) << __func__ << ": Failed to get any radio name";
+ return std::string();
+}
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#setName(java.lang.String)
+bool BluetoothAdapter::SetName(absl::string_view name) {
+ char *instanceID = GetGenericBluetoothAdapterInstanceID();
+
+ if (instanceID == NULL) {
+ NEARBY_LOGS(ERROR)
+ << __func__ << ": Failed to get Generic Bluetooth Adapter InstanceID";
+ return false;
+ }
+
+ // Add 1 to length to get size (including null)
+ char *instanceIDModified = new char[(strlen(instanceID) + 1) * sizeof(char)];
+
+ absl::SNPrintF(instanceIDModified,
+ size_t((strlen(instanceID) + 1) * sizeof(char)), "%s",
+ instanceID);
+
+ find_and_replace(instanceIDModified, "\\", "#");
+
+ HANDLE hDevice;
+ char fileName[FILE_NAME_SIZE] = {0};
+
+ // defined in usbiodef.h
+ const GUID guid = GUID_DEVINTERFACE_USB_DEVICE;
+
+ OLECHAR guidOleStr[BUFFER_SIZE];
+ int oleBufferLen = BUFFER_SIZE;
+
+ char guidStr[BUFFER_SIZE];
+ int bufferLen = BUFFER_SIZE;
+ BOOL defaultCharUsed;
+
+ // Converts a globally unique identifier (GUID) into a string of printable
+ // characters.
+ // https://docs.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-stringfromguid2
+ auto conversionResult = StringFromGUID2(guid, guidOleStr, bufferLen);
+
+ if (conversionResult == 0) {
+ NEARBY_LOGS(ERROR) << __func__ << ": Failed to convert guid to string";
+ return false;
+ }
+
+ // Maps a UTF-16 (wide character) string to a new character string. The new
+ // character string is not necessarily from a multibyte character set.
+ // https://docs.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-widechartomultibyte
+ conversionResult =
+ WideCharToMultiByte(CP_UTF8, 0, guidOleStr, oleBufferLen, guidStr,
+ bufferLen, NULL, &defaultCharUsed);
+
+ if (conversionResult == 0) {
+ const char *errorResult = {};
+ int errorMessageID = GetLastError();
+
+ switch (errorMessageID) {
+ case ERROR_INSUFFICIENT_BUFFER:
+ errorResult =
+ "A supplied buffer size was not large enough, or it was "
+ "incorrectly set to NULL.";
+ break;
+ case ERROR_INVALID_FLAGS:
+ errorResult = "The values supplied for flags were not valid.";
+ break;
+ case ERROR_INVALID_PARAMETER:
+ errorResult = "Any of the parameter values was invalid.";
+ break;
+ case ERROR_NO_UNICODE_TRANSLATION:
+ errorResult = "Invalid Unicode was found in a string.";
+ break;
+ default:
+ errorResult = "Unknown error.";
+ break;
+ }
+
+ NEARBY_LOGS(ERROR) << __func__ << ": Failed to convert guid to string "
+ << errorResult << " Error code:" << errorMessageID;
+ }
+
+ absl::SNPrintF(fileName, sizeof(fileName), "\\\\.\\%s%s#%s", fileName,
+ instanceIDModified, guidStr);
+
+ // Creates or opens a file or I/O device.
+ // https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea
+ hDevice = CreateFileA(
+ fileName, // The name of the file or device to be created or opened.
+ GENERIC_WRITE, // The requested access to the file or device.
+ 0, // The requested sharing mode of the file or device.
+ NULL, // A pointer to a SECURITY_ATTRIBUTES structure.
+ OPEN_EXISTING, // An action to take on a file or device that exists or
+ // does not exist.
+ 0, // The file or device attributes and flags.
+ NULL); // A valid handle to a template file with the GENERIC_READ access
+ // right. This parameter can be NULL.
+
+ delete[] instanceIDModified;
+
+ if (hDevice == INVALID_HANDLE_VALUE) {
+ NEARBY_LOGS(ERROR) << __func__ << ": Failed to open device. Error code: "
+ << GetLastError();
+ return false;
+ }
+
+ // Change radio module local name in registry
+ HKEY hKey;
+ char rmLocalNameKey[FILE_NAME_SIZE] = {0};
+ LSTATUS ret;
+
+ absl::SNPrintF(rmLocalNameKey, sizeof(rmLocalNameKey), REGISTRY_QUERY_FORMAT,
+ instanceID);
+
+ // Opens the specified registry key. Note that key names are not case
+ // sensitive.
+ // https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regopenkeyexa
+ ret = RegOpenKeyExA(
+ HKEY_LOCAL_MACHINE, // A handle to an open registry key.
+ rmLocalNameKey, // The name of the registry subkey to be opened.
+ 0L, // Specifies the option to apply when opening the key.
+ KEY_SET_VALUE, // A mask that specifies the desired access rights to the
+ // key to be opened.
+ &hKey); // A pointer to a variable that receives a handle to the opened
+ // key.
+
+ if (ret != ERROR_SUCCESS) {
+ NEARBY_LOGS(ERROR) << __func__
+ << ": Failed to open registry key. Error code: " << ret;
+ return false;
+ }
+
+ if (name != "") {
+ // Sets the data and type of a specified value under a registry key.
+ // https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regsetvalueexa
+ ret = RegSetValueExA(
+ hKey, // A handle to an open registry key
+ BLUETOOTH_RADIO_REGISTRY_NAME_KEY, // The name of the value to be set.
+ 0, // This parameter is reserved and must be zero.
+ REG_BINARY, // The type of data pointed to by the lpData parameter.
+ (LPBYTE)std::string(name).c_str(), // The data to be stored.
+ strlen(std::string(name)
+ .c_str())); // The size of the information pointed
+ // to by the lpData parameter, in bytes.
+ } else {
+ // If we are told to set the key to "", we treat this as a reset
+ // If we delete the key value the OS will default to the system
+ // name. If we just set it to blank, it will show as blank in all
+ // system dialogs, this is likely undesireable
+ ret = RegDeleteValueA(hKey, BLUETOOTH_RADIO_REGISTRY_NAME_KEY);
+ }
+
+ if (ret != ERROR_SUCCESS) {
+ NEARBY_LOGS(ERROR) << __func__
+ << ": Failed to set/delete registry key. Error code: "
+ << ret;
+ return false;
+ }
+
+ // Closes a handle to the specified registry key.
+ // https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regclosekey
+ RegCloseKey(hKey);
+
+ // tells the control function to reset or reload or similar...
+ int32 reload = 4;
+ // merely a placeholder
+ DWORD bytes = 0;
+
+ // Send radio module driver command to update device information
+ // Sends a control code directly to a specified device driver, causing the
+ // corresponding device to perform the corresponding operation.
+ // https://docs.microsoft.com/en-us/windows/win32/api/ioapiset/nf-ioapiset-deviceiocontrol
+ if (!DeviceIoControl(
+ hDevice, // A handle to the device on which the operation is to be
+ // performed.
+ BTH_GET_DEVICE_INFO_IOCTL, // The control code for the operation.
+ &reload, // A pointer to the input buffer that contains the data
+ // required to perform the operation.
+ sizeof(reload), // The size of the input buffer, in bytes.
+ NULL, // A pointer to the output buffer that is to receive the data
+ // returned by the operation.
+ 0, // The size of the output buffer, in bytes.
+ &bytes, // A pointer to a variable that receives the size of the data
+ // stored in the output buffer, in bytes.
+ NULL)) { // A pointer to an OVERLAPPED structure.
+ NEARBY_LOGS(ERROR)
+ << __func__
+ << ": Failed to update radio module local name. Error code: "
+ << GetLastError();
+
+ return false;
+ }
+
+ return true;
+}
+
+void BluetoothAdapter::find_and_replace(char *source, const char *strFind,
+ const char *strReplace) const {
+ std::string s = std::string(source);
+ std::string f = std::string(strFind);
+ std::string r = std::string(strReplace);
+ size_t j;
+
+ for (; (j = s.find(f)) != std::string::npos;) {
+ s.replace(j, f.length(), r);
+ }
+
+ memcpy(source, s.c_str(), s.size());
+}
+
+char *BluetoothAdapter::GetGenericBluetoothAdapterInstanceID(void) const {
+ unsigned i;
+ CONFIGRET r;
+ HDEVINFO hDevInfo;
+ SP_DEVINFO_DATA DeviceInfoData;
+ char *deviceInstanceID = new char[MAX_DEVICE_ID_LEN];
+
+ // Find all bluetooth radio modules
+ // The SetupDiGetClassDevs function returns a handle to a device information
+ // set that contains requested device information elements for a local
+ // computer.
+ // https://docs.microsoft.com/en-us/windows/win32/api/setupapi/nf-setupapi-setupdigetclassdevsa
+ hDevInfo =
+ SetupDiGetClassDevsA(&GUID_DEVCLASS_BLUETOOTH, NULL, NULL, DIGCF_PRESENT);
+
+ if (hDevInfo == INVALID_HANDLE_VALUE) {
+ NEARBY_LOGS(ERROR) << __func__
+ << ": Could not find BluetoothDevice on this machine";
+ return NULL;
+ }
+
+ // Get first Generic Bluetooth Adapter InstanceID
+ for (i = 0;; i++) {
+ DeviceInfoData.cbSize = sizeof(DeviceInfoData);
+
+ // The SetupDiEnumDeviceInfo function returns a SP_DEVINFO_DATA structure
+ // that specifies a device information element in a device information set.
+ // https://docs.microsoft.com/en-us/windows/win32/api/setupapi/nf-setupapi-setupdienumdeviceinfo
+ if (!SetupDiEnumDeviceInfo(hDevInfo, i, &DeviceInfoData)) break;
+
+ // The CM_Get_Device_ID function retrieves the device instance ID for a
+ // specified device instance on the local machine.
+ // https://docs.microsoft.com/en-us/windows/win32/api/cfgmgr32/nf-cfgmgr32-cm_get_device_ida
+ r = CM_Get_Device_IDA(DeviceInfoData.DevInst, deviceInstanceID,
+ MAX_DEVICE_ID_LEN, 0);
+
+ if (r != CR_SUCCESS) continue;
+
+ // With Windows, a Bluetooth radio can be packaged as an external dongle or
+ // embedded inside a computer but it must be connected to one of the
+ // computer's USB ports.
+ // https://docs.microsoft.com/en-us/windows-hardware/drivers/bluetooth/bluetooth-host-radio-support
+ if (strncmp("USB", deviceInstanceID, 3) == 0) {
+ return deviceInstanceID;
+ }
+ }
+
+ NEARBY_LOGS(ERROR) << __func__
+ << ": Failed to get the generic bluetooth adapter id";
+
+ return NULL;
+}
+
+// Returns BT MAC address assigned to this adapter.
+std::string BluetoothAdapter::GetMacAddress() const {
+ return uint64_to_mac_address_string(
+ windows_bluetooth_adapter_.BluetoothAddress());
+}
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_adapter.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_adapter.h
new file mode 100644
index 00000000000..90d1d12e615
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_adapter.h
@@ -0,0 +1,99 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_BLUETOOTH_ADAPTER_H_
+#define PLATFORM_IMPL_WINDOWS_BLUETOOTH_ADAPTER_H_
+
+#include <guiddef.h>
+
+#include <string>
+
+#include "internal/platform/implementation/bluetooth_adapter.h"
+#include "internal/platform/implementation/windows/generated/winrt/base.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Devices.Bluetooth.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Devices.Radios.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+// Represents a Bluetooth adapter.
+// https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.bluetoothadapter?view=winrt-20348
+using winrt::Windows::Devices::Bluetooth::IBluetoothAdapter;
+
+// Represents a radio device on the system.
+// https://docs.microsoft.com/en-us/uwp/api/windows.devices.radios.radio?view=winrt-20348
+using winrt::Windows::Devices::Radios::IRadio;
+
+// Enumeration that describes possible radio states.
+// https://docs.microsoft.com/en-us/uwp/api/windows.devices.radios.radiostate?view=winrt-20348
+using winrt::Windows::Devices::Radios::RadioState;
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html
+class BluetoothAdapter : public api::BluetoothAdapter {
+ public:
+ BluetoothAdapter();
+
+ ~BluetoothAdapter() override = default;
+
+ typedef std::function<void(api::BluetoothAdapter::ScanMode)> ScanModeCallback;
+
+ // Synchronously sets the status of the BluetoothAdapter to 'status', and
+ // returns true if the operation was a success.
+ bool SetStatus(Status status) override;
+
+ // Returns true if the BluetoothAdapter's current status is
+ // Status::Value::kEnabled.
+ bool IsEnabled() const override;
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getScanMode()
+ // Returns ScanMode::kUnknown on error.
+ ScanMode GetScanMode() const override;
+
+ // Synchronously sets the scan mode of the adapter, and returns true if the
+ // operation was a success.
+ bool SetScanMode(ScanMode scan_mode) override;
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getName()
+ // Returns an empty string on error
+ std::string GetName() const override;
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#setName(java.lang.String)
+ bool SetName(absl::string_view name) override;
+
+ // Returns BT MAC address assigned to this adapter.
+ std::string GetMacAddress() const override;
+
+ void SetOnScanModeChanged(ScanModeCallback callback) {
+ if (scan_mode_changed_ == nullptr) {
+ scan_mode_changed_ = callback;
+ }
+ }
+
+ private:
+ IBluetoothAdapter windows_bluetooth_adapter_;
+
+ IRadio windows_bluetooth_radio_;
+ char *GetGenericBluetoothAdapterInstanceID(void) const;
+ void find_and_replace(char *source, const char *strFind,
+ const char *strReplace) const;
+ ScanMode scan_mode_ = ScanMode::kNone;
+ ScanModeCallback scan_mode_changed_ = nullptr;
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_WINDOWS_BLUETOOTH_ADAPTER_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic.h
new file mode 100644
index 00000000000..730bf2c0c51
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic.h
@@ -0,0 +1,23 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_H_
+#define PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_H_
+
+#include "internal/platform/implementation/windows/bluetooth_classic_device.h"
+#include "internal/platform/implementation/windows/bluetooth_classic_medium.h"
+#include "internal/platform/implementation/windows/bluetooth_classic_server_socket.h"
+#include "internal/platform/implementation/windows/bluetooth_classic_socket.h"
+
+#endif // PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_device.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_device.cc
new file mode 100644
index 00000000000..7f4e124a6e3
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_device.cc
@@ -0,0 +1,65 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/windows/bluetooth_classic_device.h"
+
+#include <winstring.h>
+
+#include <codecvt>
+#include <locale>
+#include <string>
+
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Devices.Bluetooth.h"
+
+#include "internal/platform/implementation/windows/utils.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+BluetoothDevice::~BluetoothDevice() {}
+
+BluetoothDevice::BluetoothDevice(
+ const winrt::Windows::Devices::Bluetooth::BluetoothDevice& bluetoothDevice)
+ : windows_bluetooth_device_(bluetoothDevice) {
+ id_ = winrt::to_string(bluetoothDevice.DeviceId());
+
+ // Get the device address.
+ auto bluetoothAddress = bluetoothDevice.BluetoothAddress();
+
+ mac_address_ = uint64_to_mac_address_string(bluetoothAddress);
+}
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#getName()
+std::string BluetoothDevice::GetName() const {
+ return winrt::to_string(windows_bluetooth_device_.Name());
+}
+
+// Returns BT MAC address assigned to this device.
+std::string BluetoothDevice::GetMacAddress() const { return mac_address_; }
+
+// We are using Uncached because:
+// For the following APIs, Cached means only use values cached in the system
+// cached (if not cached then don't fall back to querying the device).
+// The device may be present, but not entered into the cache yet, so always
+// check the actual device.
+IAsyncOperation<RfcommDeviceServicesResult>
+BluetoothDevice::GetRfcommServicesForIdAsync(const RfcommServiceId serviceId) {
+ return windows_bluetooth_device_.GetRfcommServicesForIdAsync(
+ serviceId, BluetoothCacheMode::Uncached);
+}
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_device.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_device.h
new file mode 100644
index 00000000000..83dbe5133f7
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_device.h
@@ -0,0 +1,93 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_DEVICE_H_
+#define PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_DEVICE_H_
+
+#include <guiddef.h>
+
+#include <string>
+
+#include "internal/platform/implementation/bluetooth_classic.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/input_stream.h"
+#include "internal/platform/output_stream.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Devices.Bluetooth.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Devices.Enumeration.h"
+#include "internal/platform/implementation/windows/generated/winrt/base.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+// Represents an asynchronous operation, which returns a result upon completion.
+// https://docs.microsoft.com/en-us/uwp/api/windows.foundation.iasyncoperation-1?view=winrt-20348
+using winrt::Windows::Foundation::IAsyncOperation;
+
+// The result of an Rfcomm device service request.
+// https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.rfcomm.rfcommdeviceservicesresult?view=winrt-20348
+using winrt::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceServicesResult;
+
+// Represents an RFCOMM service ID.
+// https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.rfcomm.rfcommserviceid?view=winrt-20348
+using winrt::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId;
+
+// Indicates whether applicable Bluetooth API methods should operate on values
+// cached in the system, or whether they should retrieve those values from the
+// Bluetooth device.
+// https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.bluetoothcachemode?view=winrt-20348
+using winrt::Windows::Devices::Bluetooth::BluetoothCacheMode;
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html.
+class BluetoothDevice : public api::BluetoothDevice {
+ public:
+ BluetoothDevice(std::string mac_address)
+ : windows_bluetooth_device_(nullptr), mac_address_(mac_address) {}
+ BluetoothDevice(const winrt::Windows::Devices::Bluetooth::BluetoothDevice&
+ bluetoothDevice);
+
+ ~BluetoothDevice() override;
+ BluetoothDevice(BluetoothDevice&&) = default;
+ BluetoothDevice& operator=(BluetoothDevice&&) = default;
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#getName()
+ std::string GetName() const override;
+
+ // Returns BT MAC address assigned to this device.
+ std::string GetMacAddress() const override;
+
+ std::string GetId() { return id_; }
+
+ winrt::Windows::Foundation::IAsyncOperation<
+ winrt::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceServicesResult>
+ GetRfcommServicesForIdAsync(
+ const winrt::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId
+ serviceId);
+
+ private:
+ // https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.bluetoothdevice?view=winrt-20348
+ winrt::Windows::Devices::Bluetooth::BluetoothDevice windows_bluetooth_device_;
+
+ // Once the device is lost, we can no longer access it's id.
+ std::string id_;
+
+ // Once the device is lost, we can no longer access it's mac address.
+ std::string mac_address_;
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_DEVICE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_medium.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_medium.cc
new file mode 100644
index 00000000000..a90b01f6668
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_medium.cc
@@ -0,0 +1,475 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/windows/bluetooth_classic_medium.h"
+
+#include <windows.h>
+#include <stdio.h>
+
+#include <codecvt>
+#include <locale>
+#include <regex> // NOLINT
+#include <string>
+
+#include "internal/platform/cancellation_flag.h"
+#include "internal/platform/cancellation_flag_listener.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/implementation/windows/bluetooth_adapter.h"
+#include "internal/platform/implementation/windows/bluetooth_classic_device.h"
+#include "internal/platform/implementation/windows/bluetooth_classic_server_socket.h"
+#include "internal/platform/implementation/windows/bluetooth_classic_socket.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Devices.Bluetooth.Rfcomm.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Devices.Bluetooth.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Devices.Enumeration.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Foundation.Collections.h"
+#include "internal/platform/implementation/windows/generated/winrt/base.h"
+#include "internal/platform/implementation/windows/utils.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+BluetoothClassicMedium::BluetoothClassicMedium(
+ api::BluetoothAdapter& bluetoothAdapter)
+ : bluetooth_adapter_(dynamic_cast<BluetoothAdapter&>(bluetoothAdapter)) {
+ InitializeCriticalSection(&critical_section_);
+
+ InitializeDeviceWatcher();
+
+ bluetooth_adapter_.SetOnScanModeChanged(std::bind(
+ &BluetoothClassicMedium::OnScanModeChanged, this, std::placeholders::_1));
+}
+
+BluetoothClassicMedium::~BluetoothClassicMedium() {}
+
+void BluetoothClassicMedium::OnScanModeChanged(
+ BluetoothAdapter::ScanMode scanMode) {
+ scan_mode_ = scanMode;
+ bool radioDiscoverable = bluetooth_adapter_.GetScanMode() ==
+ BluetoothAdapter::ScanMode::kConnectableDiscoverable;
+
+ if (bluetooth_server_socket_ != nullptr) {
+ bluetooth_server_socket_->SetScanMode(radioDiscoverable);
+ }
+}
+
+bool BluetoothClassicMedium::StartDiscovery(
+ BluetoothClassicMedium::DiscoveryCallback discovery_callback) {
+ EnterCriticalSection(&critical_section_);
+
+ bool result = false;
+ discovery_callback_ = discovery_callback;
+
+ if (!IsWatcherStarted()) {
+ result = StartScanning();
+ }
+
+ LeaveCriticalSection(&critical_section_);
+
+ return result;
+}
+
+bool BluetoothClassicMedium::StopDiscovery() {
+ EnterCriticalSection(&critical_section_);
+
+ bool result = false;
+
+ if (IsWatcherStarted()) {
+ result = StopScanning();
+ }
+
+ LeaveCriticalSection(&critical_section_);
+
+ return result;
+}
+
+void BluetoothClassicMedium::InitializeDeviceWatcher() {
+ // create watcher
+ const winrt::param::iterable<winrt::hstring> RequestedProperties =
+ winrt::single_threaded_vector<winrt::hstring>(
+ {winrt::to_hstring("System.Devices.Aep.IsPresent")});
+
+ device_watcher_ = DeviceInformation::CreateWatcher(
+ BLUETOOTH_SELECTOR, // aqsFilter
+ RequestedProperties, // additionalProperties
+ DeviceInformationKind::AssociationEndpoint); // kind
+
+ // An app must subscribe to all of the added, removed, and updated events to
+ // be notified when there are device additions, removals or updates. If an
+ // app handles only the added event, it will not receive an update if a
+ // device is added to the system after the initial device enumeration
+ // completes. register event handlers before starting the watcher
+
+ // Event that is raised when a device is added to the collection enumerated
+ // by the DeviceWatcher.
+ // https://docs.microsoft.com/en-us/uwp/api/windows.devices.enumeration.devicewatcher.added?view=winrt-20348
+ device_watcher_.Added({this, &BluetoothClassicMedium::DeviceWatcher_Added});
+
+ // Event that is raised when a device is updated in the collection of
+ // enumerated devices.
+ // https://docs.microsoft.com/en-us/uwp/api/windows.devices.enumeration.devicewatcher.updated?view=winrt-20348
+ device_watcher_.Updated(
+ {this, &BluetoothClassicMedium::DeviceWatcher_Updated});
+
+ // Event that is raised when a device is removed from the collection of
+ // enumerated devices.
+ // https://docs.microsoft.com/en-us/uwp/api/windows.devices.enumeration.devicewatcher.removed?view=winrt-20348
+ device_watcher_.Removed(
+ {this, &BluetoothClassicMedium::DeviceWatcher_Removed});
+}
+
+std::unique_ptr<api::BluetoothSocket> BluetoothClassicMedium::ConnectToService(
+ api::BluetoothDevice& remote_device, const std::string& service_uuid,
+ CancellationFlag* cancellation_flag) {
+ if (service_uuid.empty()) {
+ NEARBY_LOGS(ERROR) << __func__ << ": service_uuid not specified.";
+ return nullptr;
+ }
+
+ const std::regex pattern(
+ "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]"
+ "{12}$");
+
+ // Must check for valid pattern as the guid constructor will throw on an
+ // invalid format
+ if (!regex_match(service_uuid, pattern)) {
+ NEARBY_LOGS(ERROR) << __func__
+ << ": invalid service_uuid: " << service_uuid;
+ return nullptr;
+ }
+
+ winrt::guid service(service_uuid);
+
+ if (cancellation_flag == nullptr) {
+ NEARBY_LOGS(ERROR) << __func__ << ": cancellation_flag not specified.";
+ return nullptr;
+ }
+
+ BluetoothDevice* currentDevice =
+ dynamic_cast<BluetoothDevice*>(&remote_device);
+
+ if (currentDevice == nullptr) {
+ NEARBY_LOGS(ERROR) << __func__ << ": Failed to get current device.";
+ return nullptr;
+ }
+
+ winrt::hstring deviceId = winrt::to_hstring(currentDevice->GetId());
+
+ if (!HaveAccess(deviceId)) {
+ NEARBY_LOGS(ERROR) << __func__ << ": Failed to gain access to device: "
+ << winrt::to_string(deviceId);
+ return nullptr;
+ }
+
+ RfcommDeviceService requestedService(
+ GetRequestedService(currentDevice, service));
+
+ if (!CheckSdp(requestedService)) {
+ NEARBY_LOGS(ERROR) << __func__ << ": Invalid SDP.";
+ return nullptr;
+ }
+
+ EnterCriticalSection(&critical_section_);
+
+ std::unique_ptr<BluetoothSocket> rfcommSocket =
+ std::make_unique<BluetoothSocket>();
+
+ location::nearby::CancellationFlagListener cancellationFlagListener(
+ cancellation_flag,
+ [&rfcommSocket]() { rfcommSocket.get()->CancelIOAsync().get(); });
+
+ try {
+ rfcommSocket->Connect(requestedService.ConnectionHostName(),
+ requestedService.ConnectionServiceName());
+ } catch (std::exception exception) {
+ // We will log and eat the exception since the caller
+ // expects nullptr if it fails
+ NEARBY_LOGS(ERROR) << __func__ << ": Exception connecting bluetooth async: "
+ << exception.what();
+
+ LeaveCriticalSection(&critical_section_);
+
+ return nullptr;
+ }
+
+ LeaveCriticalSection(&critical_section_);
+
+ return rfcommSocket;
+}
+
+bool BluetoothClassicMedium::HaveAccess(winrt::hstring deviceId) {
+ DeviceAccessStatus accessStatus =
+ DeviceAccessInformation::CreateFromId(deviceId).CurrentStatus();
+
+ if (accessStatus == DeviceAccessStatus::DeniedByUser ||
+ // This status is most likely caused by app permissions (did not declare
+ // the device in the app's package.appxmanifest)
+ // This status does not cover the case where the device is already opened
+ // by another app.
+ accessStatus == DeviceAccessStatus::DeniedBySystem ||
+ // Most likely the device is opened by another app, but cannot be sure
+ accessStatus == DeviceAccessStatus::Unspecified) {
+ return false;
+ }
+
+ return true;
+}
+
+RfcommDeviceService BluetoothClassicMedium::GetRequestedService(
+ BluetoothDevice* device, winrt::guid service) {
+ RfcommServiceId rfcommServiceId = RfcommServiceId::FromUuid(service);
+
+ // Retrieves all Rfcomm Services on the Remote Bluetooth Device matching the
+ // specified RfcommServiceId.
+ // https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.bluetoothdevice.getrfcommservicesforidasync?view=winrt-20348
+ IAsyncOperation<RfcommDeviceServicesResult> rfcommServices =
+ device->GetRfcommServicesForIdAsync(rfcommServiceId);
+
+ RfcommDeviceService requestedService(nullptr);
+
+ if (rfcommServices.get().Services().Size() > 0) {
+ requestedService = rfcommServices.get().Services().GetAt(0);
+ } else {
+ NEARBY_LOGS(ERROR) << __func__ << ": No services found.";
+ return nullptr;
+ }
+
+ return requestedService;
+}
+
+bool BluetoothClassicMedium::CheckSdp(RfcommDeviceService requestedService) {
+ // Do various checks of the SDP record to make sure you are talking to a
+ // device that actually supports the Bluetooth Rfcomm Service
+ // https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.rfcomm.rfcommdeviceservice.getsdprawattributesasync?view=winrt-20348
+ auto attributes = requestedService.GetSdpRawAttributesAsync().get();
+ if (!attributes.HasKey(Constants::SdpServiceNameAttributeId)) {
+ NEARBY_LOGS(ERROR) << __func__ << ": Missing SdpServiceNameAttributeId.";
+ return false;
+ }
+
+ auto attributeReader = DataReader::FromBuffer(
+ attributes.Lookup(Constants::SdpServiceNameAttributeId));
+
+ auto attributeType = attributeReader.ReadByte();
+
+ if (attributeType != Constants::SdpServiceNameAttributeType) {
+ NEARBY_LOGS(ERROR) << __func__ << ": Missing SdpServiceNameAttributeType.";
+ return false;
+ }
+
+ return true;
+}
+// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#listenUsingInsecureRfcommWithServiceRecord
+//
+// service_uuid is the canonical textual representation
+// (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format) of a
+// type 3 name-based
+// (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based))
+// UUID.
+//
+// Returns nullptr error.
+std::unique_ptr<api::BluetoothServerSocket>
+BluetoothClassicMedium::ListenForService(const std::string& service_name,
+ const std::string& service_uuid) {
+ if (service_uuid.empty()) {
+ NEARBY_LOGS(ERROR) << __func__ << ": service_uuid was empty.";
+ return nullptr;
+ }
+
+ if (service_name.empty()) {
+ NEARBY_LOGS(ERROR) << __func__ << ": service_name was empty.";
+ return nullptr;
+ }
+
+ auto bluetooth_server_socket =
+ std::make_unique<location::nearby::windows::BluetoothServerSocket>(
+ service_name, service_uuid);
+
+ if (bluetooth_server_socket == nullptr) {
+ NEARBY_LOGS(ERROR) << __func__ << ": Failed to create the server socket.";
+ return nullptr;
+ }
+
+ bool radioDiscoverable = bluetooth_adapter_.GetScanMode() ==
+ BluetoothAdapter::ScanMode::kConnectableDiscoverable;
+
+ Exception result = bluetooth_server_socket->StartListening(radioDiscoverable);
+
+ if (result.value != Exception::kSuccess) {
+ NEARBY_LOGS(ERROR) << __func__ << ": Failed to start listening.";
+ return nullptr;
+ }
+
+ return std::move(bluetooth_server_socket);
+}
+
+api::BluetoothDevice* BluetoothClassicMedium::GetRemoteDevice(
+ const std::string& mac_address) {
+ return new BluetoothDevice(mac_address);
+}
+
+bool BluetoothClassicMedium::StartScanning() {
+ if (!IsWatcherStarted()) {
+ discovered_devices_by_id_.clear();
+
+ // The Start method can only be called when the DeviceWatcher is in the
+ // Created, Stopped or Aborted state.
+ auto status = device_watcher_.Status();
+
+ if (status == DeviceWatcherStatus::Created ||
+ status == DeviceWatcherStatus::Stopped ||
+ status == DeviceWatcherStatus::Aborted) {
+ device_watcher_.Start();
+
+ return true;
+ }
+ }
+
+ NEARBY_LOGS(ERROR)
+ << __func__
+ << ": Attempted to start scanning when watcher already started.";
+ return false;
+}
+
+bool BluetoothClassicMedium::StopScanning() {
+ if (IsWatcherRunning()) {
+ device_watcher_.Stop();
+ return true;
+ }
+ NEARBY_LOGS(ERROR)
+ << __func__
+ << ": Attempted to stop scanning when watcher already stopped.";
+ return false;
+}
+
+winrt::fire_and_forget BluetoothClassicMedium::DeviceWatcher_Added(
+ DeviceWatcher sender, DeviceInformation deviceInfo) {
+ if (IsWatcherStarted()) {
+ // Represents a Bluetooth device.
+ // https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.bluetoothdevice?view=winrt-20348
+ std::unique_ptr<winrt::Windows::Devices::Bluetooth::BluetoothDevice>
+ windowsBluetoothDevice;
+
+ // Create an iterator for the internal list
+ std::map<winrt::hstring, std::unique_ptr<BluetoothDevice>>::const_iterator
+ it = discovered_devices_by_id_.find(deviceInfo.Id());
+
+ // Add to our internal list if necessary
+ if (it != discovered_devices_by_id_.end()) {
+ // We're already tracking this one
+ return winrt::fire_and_forget();
+ }
+
+ // Create a bluetooth device out of this id
+ winrt::Windows::Devices::Bluetooth::BluetoothDevice::FromIdAsync(
+ deviceInfo.Id())
+ .Completed([this, deviceInfo](
+ winrt::Windows::Foundation::IAsyncOperation<
+ winrt::Windows::Devices::Bluetooth::BluetoothDevice>
+ bluetoothDevice,
+ winrt::Windows::Foundation::AsyncStatus status) {
+ EnterCriticalSection(&critical_section_);
+
+ auto bluetoothDeviceP =
+ absl::WrapUnique(new BluetoothDevice(bluetoothDevice.get()));
+
+ discovered_devices_by_id_[deviceInfo.Id()] =
+ std::move(bluetoothDeviceP);
+
+ if (discovery_callback_.device_discovered_cb != nullptr) {
+ discovery_callback_.device_discovered_cb(
+ *discovered_devices_by_id_[deviceInfo.Id()]);
+ }
+
+ LeaveCriticalSection(&critical_section_);
+ });
+ }
+
+ return winrt::fire_and_forget();
+}
+
+winrt::fire_and_forget BluetoothClassicMedium::DeviceWatcher_Updated(
+ DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate) {
+ EnterCriticalSection(&critical_section_);
+
+ if (!IsWatcherStarted()) {
+ // Spurious call, watcher has stopped or wasn't started
+ LeaveCriticalSection(&critical_section_);
+ return winrt::fire_and_forget();
+ }
+
+ auto it = discovered_devices_by_id_.find(deviceInfoUpdate.Id());
+
+ if (it == discovered_devices_by_id_.end()) {
+ LeaveCriticalSection(&critical_section_);
+ // Not tracking this device
+ return winrt::fire_and_forget();
+ }
+
+ if (deviceInfoUpdate.Properties().HasKey(
+ winrt::to_hstring("System.ItemNameDisplay"))) {
+ discovery_callback_.device_name_changed_cb(
+ *discovered_devices_by_id_[deviceInfoUpdate.Id()]);
+ }
+
+ LeaveCriticalSection(&critical_section_);
+
+ return winrt::fire_and_forget();
+}
+
+winrt::fire_and_forget BluetoothClassicMedium::DeviceWatcher_Removed(
+ DeviceWatcher sender, DeviceInformationUpdate deviceInfo) {
+ EnterCriticalSection(&critical_section_);
+
+ if (!IsWatcherStarted()) {
+ return winrt::fire_and_forget();
+ }
+
+ if (discovery_callback_.device_lost_cb != nullptr) {
+ discovery_callback_.device_lost_cb(
+ *discovered_devices_by_id_[deviceInfo.Id()]);
+ }
+
+ discovered_devices_by_id_.erase(deviceInfo.Id());
+
+ LeaveCriticalSection(&critical_section_);
+
+ return winrt::fire_and_forget();
+}
+
+bool BluetoothClassicMedium::IsWatcherStarted() {
+ if (device_watcher_ == nullptr) {
+ return false;
+ }
+
+ DeviceWatcherStatus status = device_watcher_.Status();
+ return (status == DeviceWatcherStatus::Started) ||
+ (status == DeviceWatcherStatus::EnumerationCompleted);
+}
+
+bool BluetoothClassicMedium::IsWatcherRunning() {
+ if (device_watcher_ == nullptr) {
+ return false;
+ }
+
+ DeviceWatcherStatus status = device_watcher_.Status();
+ return (status == DeviceWatcherStatus::Started) ||
+ (status == DeviceWatcherStatus::EnumerationCompleted) ||
+ (status == DeviceWatcherStatus::Stopping);
+}
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_medium.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_medium.h
new file mode 100644
index 00000000000..d07d5e12002
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_medium.h
@@ -0,0 +1,192 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_MEDIUM_H_
+#define PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_MEDIUM_H_
+
+#include "internal/platform/implementation/bluetooth_classic.h"
+#include "internal/platform/implementation/windows/bluetooth_adapter.h"
+#include "internal/platform/implementation/windows/bluetooth_classic_device.h"
+#include "internal/platform/implementation/windows/bluetooth_classic_server_socket.h"
+#include "internal/platform/implementation/windows/bluetooth_classic_socket.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Devices.Enumeration.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Networking.Sockets.h"
+#include "internal/platform/implementation/windows/generated/winrt/base.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+// Represents a device. This class allows access to well-known device properties
+// as well as additional properties specified during device enumeration.
+// https://docs.microsoft.com/en-us/uwp/api/windows.devices.enumeration.deviceinformation?view=winrt-20348
+using winrt::Windows::Devices::Enumeration::DeviceInformation;
+
+// Represents the kind of DeviceInformation object.
+// https://docs.microsoft.com/en-us/uwp/api/windows.devices.enumeration.deviceinformationkind?view=winrt-20348
+using winrt::Windows::Devices::Enumeration::DeviceInformationKind;
+
+// Contains updated properties for a DeviceInformation object.
+// https://docs.microsoft.com/en-us/uwp/api/windows.devices.enumeration.deviceinformationupdate?view=winrt-20348
+using winrt::Windows::Devices::Enumeration::DeviceInformationUpdate;
+
+// Enumerates devices dynamically, so that the app receives notifications if
+// devices are added, removed, or changed after the initial enumeration is
+// complete.
+// https://docs.microsoft.com/en-us/uwp/api/windows.devices.enumeration.devicewatcher?view=winrt-20348
+using winrt::Windows::Devices::Enumeration::DeviceWatcher;
+
+// Describes the state of a DeviceWatcher object.
+// https://docs.microsoft.com/en-us/uwp/api/windows.devices.enumeration.devicewatcherstatus?view=winrt-20348
+using winrt::Windows::Devices::Enumeration::DeviceWatcherStatus;
+
+// Represents an instance of a service on a Bluetooth basic rate device.
+// https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.rfcomm.rfcommdeviceservice?view=winrt-20348
+using winrt::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService;
+
+// Indicates the status of the access to a device.
+// https://docs.microsoft.com/en-us/uwp/api/windows.devices.enumeration.deviceaccessstatus?view=winrt-20348
+using winrt::Windows::Devices::Enumeration::DeviceAccessStatus;
+
+// Contains the information about access to a device.
+// https://docs.microsoft.com/en-us/uwp/api/windows.devices.enumeration.deviceaccessinformation?view=winrt-20348
+using winrt::Windows::Devices::Enumeration::DeviceAccessInformation;
+
+// Represents an RFCOMM service ID.
+// https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.rfcomm.rfcommserviceid?view=winrt-20348
+using winrt::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId;
+
+// Reads data from an input stream.
+// https://docs.microsoft.com/en-us/uwp/api/windows.storage.streams.datareader?view=winrt-20348
+using winrt::Windows::Storage::Streams::DataReader;
+
+// Writes data to an output stream.
+// https://docs.microsoft.com/en-us/uwp/api/windows.storage.streams.datawriter?view=winrt-20348
+using winrt::Windows::Storage::Streams::DataWriter;
+
+// Bluetooth protocol ID = \"{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}\"
+// https://docs.microsoft.com/en-us/windows/uwp/devices-sensors/aep-service-class-ids
+#define BLUETOOTH_SELECTOR \
+ L"System.Devices.Aep.ProtocolId:=\"{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}\""
+
+// Container of operations that can be performed over the Bluetooth Classic
+// medium.
+class BluetoothClassicMedium : public api::BluetoothClassicMedium {
+ public:
+ BluetoothClassicMedium(api::BluetoothAdapter& bluetoothAdapter);
+
+ ~BluetoothClassicMedium() override;
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#startDiscovery()
+ bool StartDiscovery(DiscoveryCallback discovery_callback) override;
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#cancelDiscovery()
+ //
+ // Returns true once discovery is well and truly stopped; after this returns,
+ // there must be no more invocations of the DiscoveryCallback passed in to
+ // StartDiscovery().
+ bool StopDiscovery() override;
+
+ // A combination of
+ // https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#createInsecureRfcommSocketToServiceRecord
+ // followed by
+ // https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#connect().
+ //
+ // service_uuid is the canonical textual representation
+ // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format) of a
+ // type 3 name-based
+ // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based))
+ // UUID.
+ //
+ // On success, returns a new BluetoothSocket.
+ // On error, throw's an exception
+ std::unique_ptr<api::BluetoothSocket> ConnectToService(
+ api::BluetoothDevice& remote_device, const std::string& service_uuid,
+ CancellationFlag* cancellation_flag) override;
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#listenUsingInsecureRfcommWithServiceRecord
+ //
+ // service_uuid is the canonical textual representation
+ // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format) of a
+ // type 3 name-based
+ // (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based))
+ // UUID.
+ //
+ // Returns nullptr error.
+ std::unique_ptr<api::BluetoothServerSocket> ListenForService(
+ const std::string& service_name,
+ const std::string& service_uuid) override;
+
+ api::BluetoothDevice* GetRemoteDevice(
+ const std::string& mac_address) override;
+
+ private:
+ bool StartScanning();
+ bool StopScanning();
+ bool IsWatcherStarted();
+ bool IsWatcherRunning();
+ void InitializeDeviceWatcher();
+ void OnScanModeChanged(BluetoothAdapter::ScanMode scanMode);
+
+ // This is for a coroutine whose return type is winrt::fire_and_forget, which
+ // handles async operations which don't have any dependencies.
+ // https://docs.microsoft.com/en-us/uwp/cpp-ref-for-winrt/fire-and-forget
+ winrt::fire_and_forget DeviceWatcher_Added(DeviceWatcher sender,
+ DeviceInformation deviceInfo);
+
+ winrt::fire_and_forget DeviceWatcher_Updated(
+ DeviceWatcher sender, DeviceInformationUpdate deviceInfo);
+
+ winrt::fire_and_forget DeviceWatcher_Removed(
+ DeviceWatcher sender, DeviceInformationUpdate deviceInfo);
+
+ // Check to make sure we can connect if we try
+ bool HaveAccess(winrt::hstring deviceId);
+
+ // Get the service requested
+ RfcommDeviceService GetRequestedService(BluetoothDevice* device,
+ winrt::guid service);
+
+ // Check to see that the device actually handles the requested service
+ bool CheckSdp(RfcommDeviceService requestedService);
+
+ BluetoothClassicMedium::DiscoveryCallback discovery_callback_;
+
+ DeviceWatcher device_watcher_ = nullptr;
+
+ std::unique_ptr<BluetoothSocket> bluetooth_socket_;
+ std::unique_ptr<BluetoothServerSocket> bluetooth_server_socket_;
+
+ std::string service_name_;
+ std::string service_uuid_;
+
+ // hstring is the only type of string winrt understands.
+ // https://docs.microsoft.com/en-us/uwp/cpp-ref-for-winrt/hstring
+ std::map<winrt::hstring, std::unique_ptr<BluetoothDevice>>
+ discovered_devices_by_id_;
+
+ // CRITICAL_SECTION is a lightweight synchronization mechanism
+ // https://docs.microsoft.com/en-us/windows/win32/sync/critical-section-objects
+ CRITICAL_SECTION critical_section_;
+
+ BluetoothAdapter& bluetooth_adapter_;
+
+ BluetoothAdapter::ScanMode scan_mode_;
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_MEDIUM_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_medium_test.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_medium_test.cc
new file mode 100644
index 00000000000..5c7357006d6
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_medium_test.cc
@@ -0,0 +1,189 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/windows/bluetooth_classic_medium.h"
+
+#include <synchapi.h>
+#include <windows.h>
+
+#include <string>
+
+#include "absl/strings/str_format.h"
+#include "internal/platform/implementation/bluetooth_adapter.h"
+#include "internal/platform/implementation/bluetooth_classic.h"
+#include "internal/platform/implementation/windows/bluetooth_adapter.h"
+#include "internal/platform/implementation/windows/bluetooth_classic_device.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Devices.Bluetooth.Rfcomm.h"
+
+#include "gtest/gtest.h"
+
+// TODO(jfcarroll): Find a way to mock winrt components in order to properly
+// unit test this. Once that's done, unit tests can be written, in a later C/L.
+//
+// CAUTION: THIS IS NOT A REAL TEST, THIS EXERCISES THE SCANNER, IT MAY NOT
+// STOP/HANG AND IS INTENDED SOLELY FOR DEBUG AND DEMONSTRATION PURPOSES. DO NOT
+// ATTEMPT TO BUILD AND RUN THIS TEST ON GOOGLE3 YOU HAVE BEEN WARNED
+
+using location::nearby::windows::BluetoothDevice;
+
+typedef std::map<const std::string, location::nearby::api::BluetoothDevice*>
+ DeviceMap;
+
+class BluetoothClassicMediumTests : public testing::Test {
+ protected:
+ static void device_discovered_cb(
+ location::nearby::api::BluetoothDevice& device) {
+ const std::string address = device.GetMacAddress();
+
+ std::map<std::string,
+ location::nearby::api::BluetoothDevice*>::const_iterator it =
+ deviceList.find(address);
+
+ std::string buffer =
+ absl::StrFormat("processing device %s : ", address.c_str());
+
+ OutputDebugStringA(buffer.c_str());
+
+ if (it == deviceList.end()) {
+ buffer = absl::StrFormat("adding device %s\n", address.c_str());
+
+ OutputDebugStringA(buffer.c_str());
+ deviceList[device.GetMacAddress()] = &device;
+ }
+ }
+
+ static void device_name_changed_cb(
+ location::nearby::api::BluetoothDevice& device) {}
+
+ static void device_lost_cb(location::nearby::api::BluetoothDevice& device) {
+ deviceList.erase(device.GetMacAddress());
+ }
+
+ int callcount = 0;
+ static inline DeviceMap deviceList = {};
+};
+
+#ifdef TESTING_LOCALLY
+TEST_F(BluetoothClassicMediumTests, ManualTest) {
+ auto bluetoothAdapter = location::nearby::windows::BluetoothAdapter();
+
+ std::string bluetoothAdapterName = bluetoothAdapter.GetName();
+ bluetoothAdapter.SetName("BluetoothTestName");
+ bluetoothAdapterName = bluetoothAdapter.GetName();
+ bluetoothAdapter.SetName("");
+ bluetoothAdapterName = bluetoothAdapter.GetName();
+
+ std::unique_ptr<location::nearby::windows::BluetoothClassicMedium> bcm =
+ std::make_unique<location::nearby::windows::BluetoothClassicMedium>(
+ bluetoothAdapter);
+
+ bluetoothAdapter.SetScanMode(location::nearby::windows::BluetoothAdapter::
+ ScanMode::kConnectableDiscoverable);
+
+ auto mode = bluetoothAdapter.GetScanMode();
+
+ bcm->StartDiscovery(
+ location::nearby::api::BluetoothClassicMedium::DiscoveryCallback{
+ .device_discovered_cb = device_discovered_cb,
+ .device_name_changed_cb = device_name_changed_cb,
+ .device_lost_cb = device_lost_cb,
+ });
+
+ Sleep(30000);
+
+ auto currentDevice = deviceList["DC:DC:E2:F2:B5:99"];
+ auto serviceUuid = winrt::to_string(
+ winrt::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId::SerialPort()
+ .AsString());
+
+ location::nearby::CancellationFlag cancellationFlag;
+ bcm->ConnectToService(*currentDevice,
+ // "a82efa21-ae5c-3dde-9bbc-f16da7b16c5a",
+ "00001101-0000-1000-8000-00805F9B34FB",
+ &cancellationFlag);
+
+ EXPECT_EQ(1, 1);
+ EXPECT_TRUE(true);
+}
+#endif
+TEST_F(BluetoothClassicMediumTests, ConnectToServiceNullUuid) {
+ // Arrange
+ auto bluetoothAdapter = location::nearby::windows::BluetoothAdapter();
+
+ std::unique_ptr<location::nearby::windows::BluetoothClassicMedium>
+ bluetoothClassicMedium =
+ std::make_unique<location::nearby::windows::BluetoothClassicMedium>(
+ bluetoothAdapter);
+
+ location::nearby::windows::BluetoothDevice bluetoothDevice =
+ location::nearby::windows::BluetoothDevice(
+ std::string("1D:EA:DB:EE:B9:00"));
+ location::nearby::CancellationFlag cancellationFlag;
+
+ auto bluetoothClassicMediumImpl = bluetoothClassicMedium.get();
+
+ // Act
+ auto asyncResult = bluetoothClassicMediumImpl->ConnectToService(
+ bluetoothDevice, std::string(), &cancellationFlag);
+
+ // Assert
+ EXPECT_TRUE(asyncResult.get() == nullptr);
+}
+
+TEST_F(BluetoothClassicMediumTests, ConnectToServiceNullCancellationFlag) {
+ // Arrange
+ auto bluetoothAdapter = location::nearby::windows::BluetoothAdapter();
+
+ std::unique_ptr<location::nearby::windows::BluetoothClassicMedium>
+ bluetoothClassicMedium =
+ std::make_unique<location::nearby::windows::BluetoothClassicMedium>(
+ bluetoothAdapter);
+
+ location::nearby::windows::BluetoothDevice bluetoothDevice =
+ location::nearby::windows::BluetoothDevice(
+ std::string("1D:EA:DB:EE:B9:00"));
+
+ auto bluetoothClassicMediumImpl = bluetoothClassicMedium.get();
+
+ // Act
+ auto asyncResult = bluetoothClassicMediumImpl->ConnectToService(
+ bluetoothDevice, std::string("test service"), nullptr);
+
+ // Assert
+ EXPECT_TRUE(asyncResult.get() == nullptr);
+}
+
+TEST_F(BluetoothClassicMediumTests, ConnectToServiceWithInvalidServiceUuid) {
+ // Arrange
+ auto bluetoothAdapter = location::nearby::windows::BluetoothAdapter();
+
+ std::unique_ptr<location::nearby::windows::BluetoothClassicMedium>
+ bluetoothClassicMedium =
+ std::make_unique<location::nearby::windows::BluetoothClassicMedium>(
+ bluetoothAdapter);
+
+ location::nearby::windows::BluetoothDevice bluetoothDevice =
+ location::nearby::windows::BluetoothDevice(
+ std::string("1D:EA:DB:EE:B9:00"));
+ location::nearby::CancellationFlag cancellationFlag;
+
+ auto bluetoothClassicMediumImpl = bluetoothClassicMedium.get();
+
+ // Act
+ auto asyncResult = bluetoothClassicMediumImpl->ConnectToService(
+ bluetoothDevice, std::string("test service"), &cancellationFlag);
+
+ // Assert
+ EXPECT_TRUE(asyncResult.get() == nullptr);
+}
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_server_socket.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_server_socket.cc
new file mode 100644
index 00000000000..113ec647067
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_server_socket.cc
@@ -0,0 +1,196 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/windows/bluetooth_classic_server_socket.h"
+
+#include <codecvt>
+#include <locale>
+#include <string>
+
+#include "internal/platform/implementation/windows/bluetooth_classic_socket.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Foundation.Collections.h"
+#include "internal/platform/implementation/windows/utils.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+BluetoothServerSocket::BluetoothServerSocket(const std::string service_name,
+ const std::string service_uuid)
+ : radio_discoverable_(false),
+ service_name_(service_name),
+ service_uuid_(service_uuid),
+ rfcomm_provider_(nullptr) {
+ InitializeCriticalSection(&critical_section_);
+}
+
+BluetoothServerSocket::~BluetoothServerSocket() {}
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html#accept()
+//
+// Blocks until either:
+// - at least one incoming connection request is available, or
+// - ServerSocket is closed.
+// On success, returns connected socket, ready to exchange data.
+// Returns nullptr on error.
+// Once error is reported, it is permanent, and ServerSocket has to be closed.
+std::unique_ptr<api::BluetoothSocket> BluetoothServerSocket::Accept() {
+ while (bluetooth_sockets_.empty() && !closed_) {
+ Sleep(1000);
+ }
+
+ EnterCriticalSection(&critical_section_);
+ if (!closed_) {
+ std::unique_ptr<BluetoothSocket> bluetoothSocket =
+ std::move(bluetooth_sockets_.front());
+ bluetooth_sockets_.pop();
+ LeaveCriticalSection(&critical_section_);
+
+ return std::move(bluetoothSocket);
+ } else {
+ bluetooth_sockets_ = {};
+ LeaveCriticalSection(&critical_section_);
+ }
+
+ return nullptr;
+}
+
+Exception BluetoothServerSocket::StartListening(bool radioDiscoverable) {
+ EnterCriticalSection(&critical_section_);
+
+ radio_discoverable_ = radioDiscoverable;
+
+ // Create the StreamSocketListener
+ stream_socket_listener_ = StreamSocketListener();
+
+ // Configure control property
+ stream_socket_listener_.Control().QualityOfService(
+ SocketQualityOfService::LowLatency);
+
+ stream_socket_listener_.Control().KeepAlive(true);
+
+ // Note From the perspective of a StreamSocket, a Parallel Patterns Library
+ // (PPL) completion handler is done executing (and the socket is eligible for
+ // disposal) before the continuation body runs. So, to keep your socket from
+ // being disposed if you want to use it inside a continuation, you'll need to
+ // use one of the techniques described in References to StreamSockets in C++
+ // PPL continuations.
+ // Assign ConnectionReceived event to event handler on the server socket
+ stream_socket_listener_.ConnectionReceived(
+ [this](StreamSocketListener streamSocketListener,
+ StreamSocketListenerConnectionReceivedEventArgs args) {
+ EnterCriticalSection(&critical_section_);
+ if (!closed_) {
+ this->bluetooth_sockets_.push(
+ std::make_unique<BluetoothSocket>(args.Socket()));
+ }
+ LeaveCriticalSection(&critical_section_);
+ });
+
+ try {
+ auto rfcommProviderRef =
+ RfcommServiceProvider::CreateAsync(
+ RfcommServiceId::FromUuid(winrt::guid(service_uuid_)))
+ .get();
+
+ rfcomm_provider_ = rfcommProviderRef;
+
+ stream_socket_listener_
+ .BindServiceNameAsync(
+ winrt::to_hstring(rfcomm_provider_.ServiceId().AsString()),
+ SocketProtectionLevel::PlainSocket)
+ .get();
+
+ // Set the SDP attributes and start Bluetooth advertising
+ InitializeServiceSdpAttributes(rfcomm_provider_, service_name_);
+ } catch (std::exception exception) {
+ // We will log and eat the exception since the caller
+ // expects nullptr if it fails
+ NEARBY_LOGS(ERROR) << __func__ << ": Exception setting up for listen: "
+ << exception.what();
+
+ LeaveCriticalSection(&critical_section_);
+
+ return {Exception::kFailed};
+ }
+
+ StartAdvertising();
+
+ LeaveCriticalSection(&critical_section_);
+
+ return {Exception::kSuccess};
+}
+
+Exception BluetoothServerSocket::StartAdvertising() {
+ try {
+ rfcomm_provider_.StartAdvertising(stream_socket_listener_,
+ radio_discoverable_);
+ } catch (std::exception exception) {
+ // We will log and eat the exception since the caller
+ // expects nullptr if it fails
+ NEARBY_LOGS(ERROR) << __func__ << ": Exception calling StartAdvertising: "
+ << exception.what();
+
+ LeaveCriticalSection(&critical_section_);
+
+ return {Exception::kFailed};
+ }
+
+ return {Exception::kSuccess};
+}
+
+void BluetoothServerSocket::StopAdvertising() {
+ rfcomm_provider_.StopAdvertising();
+}
+
+void BluetoothServerSocket::InitializeServiceSdpAttributes(
+ RfcommServiceProvider rfcommProvider, std::string service_name) {
+ auto sdpWriter = DataWriter();
+
+ // Write the Service Name Attribute.
+ sdpWriter.WriteByte(Constants::SdpServiceNameAttributeType);
+
+ // The length of the UTF-8 encoded Service Name SDP Attribute.
+ sdpWriter.WriteByte(service_name.size());
+
+ // The UTF-8 encoded Service Name value.
+ sdpWriter.UnicodeEncoding(UnicodeEncoding::Utf8);
+ sdpWriter.WriteString(winrt::to_hstring(service_name));
+
+ // Set the SDP Attribute on the RFCOMM Service Provider.
+ rfcommProvider.SdpRawAttributes().Insert(Constants::SdpServiceNameAttributeId,
+ sdpWriter.DetachBuffer());
+}
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html#close()
+//
+// Returns Exception::kIo on error, Exception::kSuccess otherwise.
+Exception BluetoothServerSocket::Close() {
+ EnterCriticalSection(&critical_section_);
+ if (closed_) {
+ LeaveCriticalSection(&critical_section_);
+ return {Exception::kSuccess};
+ }
+
+ rfcomm_provider_.StopAdvertising();
+ closed_ = true;
+ bluetooth_sockets_ = {};
+ LeaveCriticalSection(&critical_section_);
+
+ return {Exception::kSuccess};
+}
+} // namespace windows
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_server_socket.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_server_socket.h
new file mode 100644
index 00000000000..6e9811e8cc6
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_server_socket.h
@@ -0,0 +1,129 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_SERVER_SOCKET_H_
+#define PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_SERVER_SOCKET_H_
+
+#include <Windows.h>
+
+#include <queue>
+
+#include "internal/platform/implementation/bluetooth_classic.h"
+#include "internal/platform/implementation/windows/bluetooth_classic_socket.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Devices.Bluetooth.Rfcomm.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Foundation.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Networking.Sockets.h"
+#include "internal/platform/implementation/windows/generated/winrt/base.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+// Supports listening for an incoming network connection using Bluetooth RFCOMM.
+// https://docs.microsoft.com/en-us/uwp/api/windows.networking.sockets.streamsocketlistener?view=winrt-20348
+using winrt::Windows::Networking::Sockets::StreamSocketListener;
+
+// Provides data for a ConnectionReceived event on a StreamSocketListener
+// object.
+// https://docs.microsoft.com/en-us/uwp/api/windows.networking.sockets.streamsocketlistenerconnectionreceivedeventargs?view=winrt-20348
+using winrt::Windows::Networking::Sockets::
+ StreamSocketListenerConnectionReceivedEventArgs;
+
+// Represents an asynchronous action.
+// https://docs.microsoft.com/en-us/uwp/api/windows.foundation.iasyncaction?view=winrt-20348
+using winrt::Windows::Foundation::IAsyncAction;
+
+// Specifies the quality of service for a StreamSocket object.
+// https://docs.microsoft.com/en-us/uwp/api/windows.networking.sockets.socketqualityofservice?view=winrt-20348
+using winrt::Windows::Networking::Sockets::SocketQualityOfService;
+
+// Represents an instance of a local RFCOMM service.
+// https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.rfcomm.rfcommserviceprovider?view=winrt-20348
+using winrt::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceProvider;
+
+// Represents an RFCOMM service ID.
+// https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.rfcomm.rfcommserviceid?view=winrt-20348
+using winrt::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId;
+
+// Writes data to an output stream.
+// https://docs.microsoft.com/en-us/uwp/api/windows.storage.streams.datawriter?view=winrt-20348
+using winrt::Windows::Storage::Streams::DataWriter;
+
+// Specifies the type of character encoding for a stream.
+// https://docs.microsoft.com/en-us/uwp/api/windows.storage.streams.unicodeencoding?view=winrt-20348
+using winrt::Windows::Storage::Streams::UnicodeEncoding;
+
+// Specifies the level of encryption to use on a StreamSocket object.
+// https://docs.microsoft.com/en-us/uwp/api/windows.networking.sockets.socketprotectionlevel?view=winrt-22000
+using winrt::Windows::Networking::Sockets::SocketProtectionLevel;
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html.
+class BluetoothServerSocket : public api::BluetoothServerSocket {
+ public:
+ BluetoothServerSocket(const std::string service_name,
+ const std::string service_uuid);
+
+ ~BluetoothServerSocket() override;
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html#accept()
+ //
+ // Blocks until either:
+ // - at least one incoming connection request is available, or
+ // - ServerSocket is closed.
+ // On success, returns connected socket, ready to exchange data.
+ // Returns nullptr on error.
+ // Once error is reported, it is permanent, and ServerSocket has to be closed.
+ std::unique_ptr<api::BluetoothSocket> Accept() override;
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html#close()
+ //
+ // Returns Exception::kIo on error, Exception::kSuccess otherwise.
+ Exception Close() override;
+
+ Exception StartListening(bool radioDiscoverable);
+
+ void SetScanMode(bool radioDiscoverable) {
+ StopAdvertising();
+ radio_discoverable_ = radioDiscoverable;
+ StartAdvertising();
+ }
+
+ private:
+ void InitializeServiceSdpAttributes(RfcommServiceProvider rfcommProvider,
+ std::string service_name);
+
+ Exception StartAdvertising();
+ void StopAdvertising();
+
+ // This is used to store sockets in case Accept hasn't been called. Once
+ // Accept has been called the socket is popped from the queue and returned to
+ // the caller
+ std::queue<std::unique_ptr<BluetoothSocket>> bluetooth_sockets_;
+
+ StreamSocketListener stream_socket_listener_;
+ winrt::event_token listener_token_;
+ CRITICAL_SECTION critical_section_;
+ bool closed_ = false;
+ bool radio_discoverable_;
+
+ const std::string service_name_;
+ const std::string service_uuid_;
+
+ RfcommServiceProvider rfcomm_provider_;
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+#endif // PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_SERVER_SOCKET_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_socket.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_socket.cc
new file mode 100644
index 00000000000..27659bfc421
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_socket.cc
@@ -0,0 +1,194 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/windows/bluetooth_classic_socket.h"
+
+#include "internal/platform/logging.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Networking.Sockets.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+BluetoothSocket::BluetoothSocket(StreamSocket streamSocket)
+ : windows_socket_(streamSocket) {
+ bluetooth_device_ = std::make_unique<BluetoothDevice>(
+ winrt::Windows::Devices::Bluetooth::BluetoothDevice::FromHostNameAsync(
+ windows_socket_.Information().RemoteHostName())
+ .get());
+ input_stream_ =
+ std::make_unique<BluetoothInputStream>(windows_socket_.InputStream());
+ output_stream_ =
+ std::make_unique<BluetoothOutputStream>(windows_socket_.OutputStream());
+}
+
+BluetoothSocket::BluetoothSocket() {}
+
+BluetoothSocket::~BluetoothSocket() {}
+
+// NOTE:
+// It is an undefined behavior if GetInputStream() or GetOutputStream() is
+// called for a not-connected BluetoothSocket, i.e. any object that is not
+// returned by BluetoothClassicMedium::ConnectToService() for client side or
+// BluetoothServerSocket::Accept() for server side of connection.
+// Returns the InputStream of this connected BluetoothSocket.
+InputStream& BluetoothSocket::GetInputStream() { return *input_stream_.get(); }
+
+// Returns the OutputStream of this connected BluetoothSocket.
+OutputStream& BluetoothSocket::GetOutputStream() {
+ return *output_stream_.get();
+}
+
+// Closes both input and output streams, marks Socket as closed.
+// After this call object should be treated as not connected.
+// Returns Exception::kIo on error, Exception::kSuccess otherwise.
+Exception BluetoothSocket::Close() {
+ // The Close method aborts any pending operations and releases all unmanaged
+ // resources associated with the StreamSocket object, including the Input and
+ // Output streams
+ windows_socket_.Close();
+ return {Exception::kSuccess};
+}
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#getRemoteDevice()
+// Returns valid BluetoothDevice pointer if there is a connection, and
+// nullptr otherwise.
+api::BluetoothDevice* BluetoothSocket::GetRemoteDevice() {
+ return bluetooth_device_.get();
+}
+
+// Starts an asynchronous operation on a StreamSocket object to connect to a
+// remote network destination specified by a remote hostname and a remote
+// service name.
+void BluetoothSocket::Connect(HostName connectionHostName,
+ winrt::hstring connectionServiceName) {
+ windows_socket_ = winrt::Windows::Networking::Sockets::StreamSocket();
+
+ // https://docs.microsoft.com/en-us/uwp/api/windows.networking.sockets.streamsocket.connectasync?view=winrt-20348
+ windows_socket_.ConnectAsync(connectionHostName, connectionServiceName).get();
+
+ auto info = windows_socket_.Information();
+ auto hostName = info.RemoteHostName();
+
+ bluetooth_device_ = std::make_unique<BluetoothDevice>(
+ winrt::Windows::Devices::Bluetooth::BluetoothDevice::FromHostNameAsync(
+ windows_socket_.Information().RemoteHostName())
+ .get());
+
+ input_stream_ =
+ std::make_unique<BluetoothInputStream>(windows_socket_.InputStream());
+ output_stream_ =
+ std::make_unique<BluetoothOutputStream>(windows_socket_.OutputStream());
+}
+
+BluetoothSocket::BluetoothInputStream::BluetoothInputStream(
+ IInputStream stream) {
+ winrt_stream_ = stream;
+}
+
+ExceptionOr<ByteArray> BluetoothSocket::BluetoothInputStream::Read(
+ std::int64_t size) {
+ if (winrt_stream_ == nullptr) {
+ return {Exception::kFailed};
+ }
+
+ Buffer buffer = Buffer(size);
+
+ winrt_stream_.ReadAsync(buffer, size, InputStreamOptions::Partial).get();
+
+ DataReader dataReader = DataReader::FromBuffer(buffer);
+
+ ByteArray data((char*)buffer.data(), buffer.Length());
+
+ return ExceptionOr(data);
+}
+
+IAsyncAction BluetoothSocket::CancelIOAsync() {
+ // Cancels pending reads and writes over a StreamSocket object.
+ // https://docs.microsoft.com/en-us/uwp/api/windows.networking.sockets.streamsocket.cancelioasync?view=winrt-20348
+ return windows_socket_.CancelIOAsync();
+}
+
+Exception BluetoothSocket::BluetoothInputStream::Close() {
+ if (winrt_stream_ == nullptr) {
+ return {Exception::kSuccess}; // Already closed, don't error out
+ }
+
+ try {
+ winrt_stream_.Close();
+ winrt_stream_ = nullptr;
+ } catch (std::exception exception) {
+ return {Exception::kFailed};
+ }
+
+ return {Exception::kSuccess};
+}
+
+BluetoothSocket::BluetoothOutputStream::BluetoothOutputStream(
+ IOutputStream stream) {
+ winrt_stream_ = stream;
+}
+
+Exception BluetoothSocket::BluetoothOutputStream::Write(const ByteArray& data) {
+ Buffer buffer = Buffer(data.size());
+ std::memcpy(buffer.data(), data.data(), data.size());
+ buffer.Length(data.size());
+ if (winrt_stream_ == nullptr) {
+ return {Exception::kFailed};
+ }
+
+ try {
+ auto hresult = winrt_stream_.WriteAsync(buffer).get();
+ } catch (winrt::hresult_error const& ex) {
+ NEARBY_LOGS(ERROR) << __func__ << ": winrt exception: " << ex.code() << ": "
+ << winrt::to_string(ex.message());
+
+ return {Exception::kFailed};
+ }
+
+ return {Exception::kSuccess};
+}
+
+Exception BluetoothSocket::BluetoothOutputStream::Flush() {
+ if (winrt_stream_ == nullptr) {
+ return {Exception::kFailed};
+ }
+
+ try {
+ winrt_stream_.FlushAsync().get();
+ } catch (std::exception exception) {
+ return {Exception::kFailed};
+ }
+
+ return {Exception::kSuccess};
+}
+
+Exception BluetoothSocket::BluetoothOutputStream::Close() {
+ if (winrt_stream_ == nullptr) {
+ return {Exception::kSuccess}; // Already closed, don't error out
+ }
+
+ try {
+ winrt_stream_.Close();
+ winrt_stream_ = nullptr;
+ } catch (std::exception exception) {
+ return {Exception::kFailed};
+ }
+
+ return {Exception::kSuccess};
+}
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_socket.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_socket.h
new file mode 100644
index 00000000000..1c48b0d2d80
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/bluetooth_classic_socket.h
@@ -0,0 +1,139 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_SOCKET_H_
+#define PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_SOCKET_H_
+
+#include "internal/platform/implementation/bluetooth_classic.h"
+#include "internal/platform/implementation/windows/bluetooth_classic_device.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Foundation.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Networking.Sockets.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Storage.Streams.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+// Provides data for a hostname or an IP address.
+// https://docs.microsoft.com/en-us/uwp/api/windows.networking.hostname?view=winrt-20348
+using winrt::Windows::Networking::HostName;
+
+// Supports network communication using a stream socket over Bluetooth RFCOMM.
+// https://docs.microsoft.com/en-us/uwp/api/windows.networking.sockets.streamsocket?view=winrt-20348
+using winrt::Windows::Networking::Sockets::IStreamSocket;
+using winrt::Windows::Networking::Sockets::StreamSocket;
+
+// Provides a default implementation of the IBuffer interface and its related
+// interfaces.
+// https://docs.microsoft.com/en-us/uwp/api/windows.storage.streams.buffer?view=winrt-20348
+using winrt::Windows::Storage::Streams::Buffer;
+
+// Represents a sequential stream of bytes to be read.
+// https://docs.microsoft.com/en-us/uwp/api/windows.storage.streams.iinputstream?view=winrt-20348
+using winrt::Windows::Storage::Streams::IInputStream;
+
+// Represents a sequential stream of bytes to be written.
+// https://docs.microsoft.com/en-us/uwp/api/windows.storage.streams.ioutputstream?view=winrt-20348
+using winrt::Windows::Storage::Streams::IOutputStream;
+
+// Specifies the read options for an input stream.
+// This enumeration has a FlagsAttribute attribute that allows a bitwise
+// combination of its member values.
+// https://docs.microsoft.com/en-us/uwp/api/windows.storage.streams.inputstreamoptions?view=winrt-20348
+using winrt::Windows::Storage::Streams::InputStreamOptions;
+
+// Reads data from an input stream.
+// https://docs.microsoft.com/en-us/uwp/api/windows.storage.streams.datareader?view=winrt-20348
+using winrt::Windows::Storage::Streams::DataReader;
+
+// Represents an asynchronous action.
+// https://docs.microsoft.com/en-us/uwp/api/windows.foundation.iasyncaction?view=winrt-20348
+using winrt::Windows::Foundation::IAsyncAction;
+
+// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html.
+class BluetoothSocket : public api::BluetoothSocket {
+ public:
+ BluetoothSocket();
+
+ BluetoothSocket(StreamSocket streamSocket);
+
+ ~BluetoothSocket() override;
+
+ // NOTE:
+ // It is an undefined behavior if GetInputStream() or GetOutputStream() is
+ // called for a not-connected BluetoothSocket, i.e. any object that is not
+ // returned by BluetoothClassicMedium::ConnectToService() for client side or
+ // BluetoothServerSocket::Accept() for server side of connection.
+
+ // Returns the InputStream of this connected BluetoothSocket.
+ InputStream& GetInputStream() override;
+
+ // Returns the OutputStream of this connected BluetoothSocket.
+ OutputStream& GetOutputStream() override;
+
+ // Closes both input and output streams, marks Socket as closed.
+ // After this call object should be treated as not connected.
+ // Returns Exception::kIo on error, Exception::kSuccess otherwise.
+ Exception Close() override;
+
+ // https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#getRemoteDevice()
+ // Returns valid BluetoothDevice pointer if there is a connection, and
+ // nullptr otherwise.
+ api::BluetoothDevice* GetRemoteDevice() override;
+
+ // Connect asynchronously to the target remote device
+ void Connect(HostName connectionHostName,
+ winrt::hstring connectionServiceName);
+
+ IAsyncAction CancelIOAsync();
+
+ private:
+ class BluetoothInputStream : public InputStream {
+ public:
+ BluetoothInputStream(IInputStream stream);
+ ~BluetoothInputStream() override = default;
+
+ ExceptionOr<ByteArray> Read(std::int64_t size) override;
+ Exception Close() override;
+
+ private:
+ IInputStream winrt_stream_;
+ };
+
+ class BluetoothOutputStream : public OutputStream {
+ public:
+ BluetoothOutputStream(IOutputStream stream);
+ ~BluetoothOutputStream() override = default;
+
+ Exception Write(const ByteArray& data) override;
+ Exception Flush() override;
+
+ Exception Close() override;
+
+ private:
+ IOutputStream winrt_stream_;
+ };
+
+ std::unique_ptr<BluetoothInputStream> input_stream_;
+ std::unique_ptr<BluetoothOutputStream> output_stream_;
+
+ StreamSocket windows_socket_;
+ std::unique_ptr<BluetoothDevice> bluetooth_device_;
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_WINDOWS_BLUETOOTH_CLASSIC_SOCKET_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/cancelable.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/cancelable.h
new file mode 100644
index 00000000000..d5e4b96072f
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/cancelable.h
@@ -0,0 +1,50 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_CANCELABLE_H_
+#define PLATFORM_IMPL_WINDOWS_CANCELABLE_H_
+
+#include <windows.h>
+
+#include "internal/platform/implementation/cancelable.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+// An interface to provide a cancellation mechanism for objects that represent
+// long-running operations.
+class Cancelable : public api::Cancelable {
+ public:
+ Cancelable(HANDLE handle) : handle_(handle) {}
+ ~Cancelable() override = default;
+
+ bool Cancel() override {
+ if (CancelWaitableTimer(handle_)) {
+ CloseHandle(handle_);
+ return true;
+ }
+
+ return false;
+ };
+
+ private:
+ HANDLE handle_;
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_WINDOWS_CANCELABLE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/condition_variable.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/condition_variable.h
new file mode 100644
index 00000000000..3a82fa666ab
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/condition_variable.h
@@ -0,0 +1,55 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+#ifndef PLATFORM_IMPL_WINDOWS_CONDITION_VARIABLE_H_
+#define PLATFORM_IMPL_WINDOWS_CONDITION_VARIABLE_H_
+#include <windows.h>
+#include <stdio.h>
+#include <synchapi.h>
+
+#include <mutex> // NOLINT
+
+#include "internal/platform/implementation/condition_variable.h"
+#include "internal/platform/implementation/windows/mutex.h"
+#include "internal/platform/mutex.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+class ConditionVariable : public api::ConditionVariable {
+ public:
+ explicit ConditionVariable(api::Mutex* mutex)
+ : mutex_(&(static_cast<windows::Mutex*>(mutex))->mutex_) {}
+ ~ConditionVariable() override = default;
+
+ Exception Wait() override {
+ cond_var_.Wait(mutex_);
+ return {Exception::kSuccess};
+ }
+
+ Exception Wait(absl::Duration timeout) override {
+ cond_var_.WaitWithTimeout(mutex_, timeout);
+ return {Exception::kSuccess};
+ }
+
+ void Notify() override { cond_var_.SignalAll(); }
+
+ private:
+ absl::Mutex* mutex_;
+ absl::CondVar cond_var_;
+};
+} // namespace windows
+} // namespace nearby
+} // namespace location
+#endif // PLATFORM_IMPL_WINDOWS_CONDITION_VARIABLE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/condition_variable_test.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/condition_variable_test.cc
new file mode 100644
index 00000000000..03626b5d0ee
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/condition_variable_test.cc
@@ -0,0 +1,104 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/windows/condition_variable.h"
+
+#include <future> // NOLINT
+
+#include "absl/time/clock.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/implementation/windows/mutex.h"
+
+#include "gtest/gtest.h"
+
+class ConditionVariableTests : public testing::Test {
+ public:
+ class ConditionVariableTest {
+ public:
+ ConditionVariableTest() {}
+
+ std::future<bool> WaitForEvent(bool timedWait, // NOLINT
+ const absl::Duration* timeout) {
+ return std::async(
+ std::launch::async,
+ [this, timedWait, timeout]() mutable {
+ std::thread::id currentThread = std::this_thread::get_id();
+
+ if (timedWait == true) {
+ auto result = this->condition_variable_actual_.Wait(*timeout);
+ if (result.value == location::nearby::Exception::kSuccess) {
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ this->condition_variable_actual_.Wait();
+ }
+ return true;
+ });
+ }
+
+ void PostEvent() {
+ absl::MutexLock::MutexLock(&mutex_actual_.GetMutex());
+ condition_variable_actual_.Notify();
+ }
+
+ private:
+ location::nearby::windows::Mutex mutex_actual_ =
+ location::nearby::windows::Mutex(
+ location::nearby::windows::Mutex::Mode::kRegular);
+ location::nearby::windows::Mutex& mutex_ = mutex_actual_;
+ location::nearby::windows::ConditionVariable condition_variable_actual_ =
+ location::nearby::windows::ConditionVariable(&mutex_);
+ location::nearby::windows::ConditionVariable& condition_variable_ =
+ condition_variable_actual_;
+ };
+};
+
+TEST_F(ConditionVariableTests, SuccessfulCreation) {
+ // Arrange
+ ConditionVariableTest conditionVariableTest;
+
+ auto result = conditionVariableTest.WaitForEvent(false, nullptr);
+
+ Sleep(1);
+
+ // Act
+ conditionVariableTest.PostEvent();
+
+ // Assert
+ ASSERT_TRUE(result.get());
+}
+
+TEST_F(ConditionVariableTests, TimedCreation) {
+ // Arrange
+ ConditionVariableTest conditionVariableTest;
+ const absl::Duration duration = absl::Milliseconds(100);
+
+ // Act
+ auto result = conditionVariableTest.WaitForEvent(true, &duration);
+
+ // Assert
+ ASSERT_FALSE(result.get()); // Timed out
+
+ // Act
+ result = conditionVariableTest.WaitForEvent(true, &duration);
+
+ Sleep(1);
+
+ conditionVariableTest.PostEvent();
+
+ // Assert
+ ASSERT_TRUE(result.get()); // Didn't timeout
+}
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/count_down_latch_test.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/count_down_latch_test.cc
new file mode 100644
index 00000000000..d3c3ddb11f7
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/count_down_latch_test.cc
@@ -0,0 +1,186 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/shared/count_down_latch.h"
+
+#include <Windows.h>
+
+#include "gtest/gtest.h"
+#include "internal/platform/implementation/platform.h"
+
+class CountDownLatchTests : public testing::Test {
+ public:
+ class TestData {
+ public:
+ std::unique_ptr<location::nearby::api::CountDownLatch>& countDownLatch;
+ LONG volatile& count;
+ };
+
+ class CountDownLatchTest {
+ public:
+ static DWORD ThreadProcCountDown(LPVOID lpParam) {
+ TestData* testData = static_cast<TestData*>(lpParam);
+
+ Sleep(1);
+
+ InterlockedIncrement(&testData->count);
+ testData->countDownLatch->CountDown();
+ return 0;
+ }
+
+ static DWORD ThreadProcAwait(LPVOID lpParam) {
+ TestData* testData = static_cast<TestData*>(lpParam);
+
+ Sleep(1);
+
+ testData->countDownLatch->Await();
+ InterlockedIncrement(&testData->count);
+
+ return 0;
+ }
+ };
+
+ CountDownLatchTests() {}
+};
+
+TEST_F(CountDownLatchTests, CountDownLatchAwaitSucceeds) {
+ // Arrange
+ LONG volatile count = 0;
+
+ std::unique_ptr<location::nearby::api::CountDownLatch> countDownLatch =
+ location::nearby::api::ImplementationPlatform::CreateCountDownLatch(3);
+
+ HANDLE hThreads[3];
+ DWORD dwThreadID;
+
+ TestData testData{countDownLatch, count};
+
+ // Setup 3 threads
+ for (int i = 0; i < 3; i++) {
+ // TODO: More complex scenarios may require use of a parameter
+ // to the thread procedure, such as an event per thread to
+ // be used for synchronization.
+ hThreads[i] = CreateThread(
+ NULL, // default security
+ 0, // default stack size
+ CountDownLatchTest::ThreadProcCountDown, // name of the thread function
+ &testData, // no thread parameters
+ 0, // default startup flags
+ &dwThreadID);
+
+ EXPECT_TRUE(hThreads[i] != NULL);
+ }
+
+ // Act
+ location::nearby::Exception result = countDownLatch->Await();
+
+ //
+ // Assert
+ EXPECT_EQ(result.value, location::nearby::Exception::kSuccess);
+ EXPECT_EQ(count, 3);
+}
+
+TEST_F(CountDownLatchTests, CountDownLatchAwaitTimeoutTimesOut) {
+ // Arrange
+ LONG volatile count = 0;
+
+ std::unique_ptr<location::nearby::api::CountDownLatch> countDownLatch =
+ location::nearby::api::ImplementationPlatform::CreateCountDownLatch(3);
+
+ // Act
+ location::nearby::ExceptionOr<bool> result =
+ countDownLatch->Await(absl::Milliseconds(5));
+
+ Sleep(40);
+
+ // Assert
+ EXPECT_FALSE(result.GetResult());
+ // TODO(jfcarroll)I think there's a bug in the shared version of this, it's
+ // not returning a timeout exception, need to look at it some more.
+ // EXPECT_EQ(result.GetException().value,
+ // location::nearby::Exception::kTimeout);
+}
+
+TEST_F(CountDownLatchTests, CountDownLatchAwaitNoTimeoutSucceeds) {
+ // Arrange
+ LONG volatile count = 0;
+
+ std::unique_ptr<location::nearby::api::CountDownLatch> countDownLatch =
+ location::nearby::api::ImplementationPlatform::CreateCountDownLatch(3);
+
+ TestData testData{countDownLatch, count};
+
+ HANDLE hThreads[3];
+ DWORD dwThreadID;
+
+ // Setup 3 threads
+ for (int i = 0; i < 3; i++) {
+ // TODO: More complex scenarios may require use of a parameter
+ // to the thread procedure, such as an event per thread to
+ // be used for synchronization.
+ hThreads[i] = CreateThread(
+ NULL, // default security
+ 0, // default stack size
+ CountDownLatchTest::ThreadProcCountDown, // name of the thread function
+ &testData, // no thread parameters
+ 0, // default startup flags
+ &dwThreadID);
+
+ EXPECT_TRUE(hThreads[i] != NULL);
+ }
+
+ WaitForMultipleObjects(3, hThreads, true, INFINITE);
+ // Act
+ location::nearby::ExceptionOr<bool> result =
+ countDownLatch->Await(absl::Milliseconds(100));
+
+ // Assert
+ EXPECT_TRUE(result.GetResult());
+ EXPECT_EQ(result.GetException().value, location::nearby::Exception::kSuccess);
+ EXPECT_EQ(count, 3);
+}
+
+TEST_F(CountDownLatchTests, CountDownLatchCountDownBeforeAwaitSucceeds) {
+ // Arrange
+ LONG volatile count = 0;
+ std::unique_ptr<location::nearby::api::CountDownLatch> countDownLatch =
+ location::nearby::api::ImplementationPlatform::CreateCountDownLatch(1);
+
+ HANDLE hThread;
+ DWORD dwThreadID;
+
+ TestData testData{countDownLatch, count};
+
+ hThread = CreateThread(
+ NULL, // default security
+ 0, // default stack size
+ CountDownLatchTest::ThreadProcAwait, // name of the thread function
+ &testData, // no thread parameters
+ 0, // default startup flags
+ &dwThreadID);
+
+ EXPECT_TRUE(hThread != NULL);
+
+ // Act
+ countDownLatch->CountDown(); // This countdown occurs before the thread has a
+ // chance to run
+
+ if (hThread != NULL) {
+ WaitForSingleObject(hThread,
+ INFINITE); // This will wait till the thread exits
+ }
+
+ // Assert
+ EXPECT_EQ(count, 1);
+}
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/crypto.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/crypto.cc
new file mode 100644
index 00000000000..deafea99c31
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/crypto.cc
@@ -0,0 +1,58 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/crypto.h"
+
+#include <cstdint>
+#include <string>
+
+#include "absl/strings/string_view.h"
+#include "internal/platform/byte_array.h"
+#if defined NEARBY_WINDOWS_DLL
+#include "third_party/openssl/boringssl/src/include/openssl/digest.h"
+#else
+#include "src/include/openssl/digest.h"
+#endif
+
+// Function implementations for platform/api/crypto.h.
+namespace location {
+namespace nearby {
+
+// Initialize global crypto state.
+void Crypto::Init() {}
+
+static ByteArray Hash(absl::string_view input, const EVP_MD* algo) {
+ unsigned int md_out_size = EVP_MAX_MD_SIZE;
+ uint8_t digest_buffer[EVP_MAX_MD_SIZE];
+ if (input.empty()) return {};
+
+ if (!EVP_Digest(input.data(), input.size(), digest_buffer, &md_out_size, algo,
+ nullptr))
+ return {};
+
+ return ByteArray{reinterpret_cast<char*>(digest_buffer), md_out_size};
+}
+
+// Return MD5 hash of input.
+ByteArray Crypto::Md5(absl::string_view input) {
+ return Hash(input, EVP_md5());
+}
+
+// Return SHA256 hash of input.
+ByteArray Crypto::Sha256(absl::string_view input) {
+ return Hash(input, EVP_sha256());
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/crypto_test.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/crypto_test.cc
new file mode 100644
index 00000000000..55f65dc35e4
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/crypto_test.cc
@@ -0,0 +1,50 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/crypto.h"
+
+#include "gtest/gtest.h"
+
+namespace location {
+namespace nearby {
+namespace {
+
+TEST(CryptoTest, Md5Hash) {
+ const std::string input{"Hello Nearby Connection"};
+ const ByteArray expected_md5(
+ "\x94\xa3\xbe\xc1\x8d\x30\xe3\x24\x5f\xa1\x4c\xee\xe7\x52\xe9\x36");
+ ByteArray md5_hash = Crypto::Md5(input);
+ EXPECT_EQ(md5_hash, expected_md5);
+}
+
+TEST(CryptoTest, Md5HashOnEmptyInput) {
+ EXPECT_EQ(Crypto::Md5(""), ByteArray{});
+}
+
+TEST(CryptoTest, Sha256Hash) {
+ const std::string input("Hello Nearby Connection");
+ const ByteArray expected_sha256(
+ "\xb4\x24\xd3\xc0\x58\x12\x9a\x42\xcb\x81\xa0\x4b\x6e\x9d\xfe\x45\x45\x9f"
+ "\x15\xf7\xc0\xa9\x32\x2f\xfb\x9\x45\xf0\xf9\xbe\x75\xb");
+ ByteArray sha256_hash = Crypto::Sha256(input);
+ EXPECT_EQ(sha256_hash, expected_sha256);
+}
+
+TEST(CryptoTest, Sha256HashOnEmptyInput) {
+ EXPECT_EQ(Crypto::Sha256(""), ByteArray{});
+}
+
+} // namespace
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/executor.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/executor.cc
new file mode 100644
index 00000000000..e5b3e046866
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/executor.cc
@@ -0,0 +1,80 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/windows/executor.h"
+
+#include "internal/platform/implementation/windows/generated/winrt/Windows.System.Threading.Core.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.System.Threading.h"
+#include "internal/platform/implementation/windows/runner.h"
+#include "internal/platform/implementation/windows/thread_pool.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+Executor::Executor() : Executor(1) {
+ // Call thread pool creator
+}
+
+Executor::Executor(int32_t max_concurrency)
+ : thread_pool_(std::make_unique<ThreadPool>(max_concurrency, false)),
+ executor_state_(ExecutorState::NotReady),
+ max_concurrency_(max_concurrency) {
+ if (max_concurrency_ < 1) {
+ throw(std::invalid_argument("max_concurrency"));
+ }
+
+ InitializeThreadPool();
+}
+
+bool Executor::InitializeThreadPool() {
+ if (executor_state_ != ExecutorState::NotReady) {
+ // To create a new pool, destroy the existing one first
+ return false;
+ }
+
+ thread_pool_->SetPoolSize(max_concurrency_);
+ thread_pool_->Create();
+ executor_state_ = ExecutorState::Ready;
+
+ return true;
+}
+
+// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-
+void Executor::Execute(Runnable&& runnable) {
+ if (shut_down_) {
+ NEARBY_LOGS(VERBOSE) << "Warning: " << __func__
+ << ": Attempt to execute on a shut down pool.";
+ return;
+ }
+
+ if (runnable == nullptr) {
+ NEARBY_LOGS(VERBOSE) << "Error: " << __func__ << "Runnable was null.";
+ return;
+ }
+
+ std::unique_ptr<Runner> runner = std::make_unique<Runner>(runnable);
+ thread_pool_->Run(std::move(runner));
+}
+
+// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#shutdown--
+void Executor::Shutdown() {
+ shut_down_ = true;
+ thread_pool_ = nullptr;
+}
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/executor.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/executor.h
new file mode 100644
index 00000000000..14472eecc58
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/executor.h
@@ -0,0 +1,60 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_EXECUTOR_H_
+#define PLATFORM_IMPL_WINDOWS_EXECUTOR_H_
+
+#include <atomic>
+
+#include "internal/platform/implementation/executor.h"
+#include "internal/platform/implementation/windows/thread_pool.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+enum class ExecutorState {
+ Ready, // has been created and initialized
+ NotReady // Executor has not been initialized
+};
+
+// This abstract class is the superclass of all classes representing an
+// Executor.
+class Executor : public api::Executor {
+ public:
+ Executor();
+ Executor(int32_t maxConcurrency);
+
+ // Before returning from destructor, executor must wait for all pending
+ // jobs to finish.
+ ~Executor() override {}
+ // https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-
+ void Execute(Runnable&& runnable) override;
+
+ // https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#shutdown--
+ void Shutdown() override;
+
+ private:
+ bool InitializeThreadPool();
+ std::unique_ptr<ThreadPool> thread_pool_;
+
+ std::atomic<bool> shut_down_;
+ ExecutorState executor_state_;
+ int32_t max_concurrency_;
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_WINDOWS_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/executor_test.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/executor_test.cc
new file mode 100644
index 00000000000..b378d54134a
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/executor_test.cc
@@ -0,0 +1,348 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/windows/executor.h"
+
+#include <algorithm>
+#include <utility>
+
+#include "internal/platform/implementation/windows/test_data.h"
+
+#include "gtest/gtest.h"
+
+TEST(ExecutorTests, SingleThreadedExecutorSucceeds) {
+ // Arrange
+ std::string expected(RUNNABLE_0_TEXT.c_str());
+
+ std::unique_ptr<location::nearby::windows::Executor> executor =
+ std::make_unique<location::nearby::windows::Executor>();
+ std::string output = std::string();
+ // Container to note threads that ran
+ std::unique_ptr<std::vector<DWORD>> threadIds =
+ std::make_unique<std::vector<DWORD>>();
+
+ threadIds->push_back(GetCurrentThreadId());
+
+ // Act
+ executor->Execute([&output, &threadIds]() {
+ threadIds->push_back(GetCurrentThreadId());
+ output.append(RUNNABLE_0_TEXT.c_str());
+ });
+
+ executor->Shutdown();
+
+ // Assert
+ // We should've run 1 time on the main thread, and 5 times on the
+ // workerThread
+ ASSERT_EQ(threadIds->size(), 2);
+ // We should still be on the main thread
+ ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
+ // We should've run all runnables on the worker thread
+ ASSERT_EQ(output, expected);
+}
+
+TEST(ExecutorTests, SingleThreadedExecutorAfterShutdownFails) {
+ // Arrange
+ std::string expected("");
+
+ std::unique_ptr<location::nearby::windows::Executor> executor =
+ std::make_unique<location::nearby::windows::Executor>();
+ std::unique_ptr<std::string> output = std::make_unique<std::string>();
+ // Container to note threads that ran
+ std::unique_ptr<std::vector<DWORD>> threadIds =
+ std::make_unique<std::vector<DWORD>>();
+
+ threadIds->push_back(GetCurrentThreadId());
+ executor->Shutdown();
+
+ // Act
+ executor->Execute([&output, &threadIds]() {
+ threadIds->push_back(GetCurrentThreadId());
+ output->append(RUNNABLE_0_TEXT.c_str());
+ });
+
+ // Assert
+ // We should've run 1 time on the main thread, and 5 times on the
+ // workerThread
+ ASSERT_EQ(threadIds->size(), 1);
+ // We should still be on the main thread
+ ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
+ // We should've run all runnables on the worker thread
+ ASSERT_EQ(*output.get(), expected);
+}
+
+TEST(ExecutorTests, SingleThreadedExecutorExecuteNullSucceeds) {
+ // Arrange
+ std::string expected(RUNNABLE_0_TEXT.c_str());
+
+ std::unique_ptr<location::nearby::windows::Executor> executor =
+ std::make_unique<location::nearby::windows::Executor>();
+ std::string output = std::string();
+ // Container to note threads that ran
+ std::unique_ptr<std::vector<DWORD>> threadIds =
+ std::make_unique<std::vector<DWORD>>();
+
+ threadIds->push_back(GetCurrentThreadId());
+
+ // Act
+ executor->Execute(nullptr);
+ executor->Execute([&output, &threadIds]() {
+ threadIds->push_back(GetCurrentThreadId());
+ output.append(RUNNABLE_0_TEXT.c_str());
+ });
+ executor->Execute(nullptr);
+
+ executor->Shutdown();
+
+ // Assert
+ // We should've run 1 time on the main thread, and 5 times on the
+ // workerThread
+ ASSERT_EQ(threadIds->size(), 2);
+ // We should still be on the main thread
+ ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
+ // We should've run all runnables on the worker thread
+ ASSERT_EQ(output, expected);
+}
+
+TEST(ExecutorTests, SingleThreadedExecutorMultipleTasksSucceeds) {
+ // Arrange
+ std::string expected(RUNNABLE_ALL_TEXT.c_str());
+
+ std::unique_ptr<location::nearby::windows::Executor> executor =
+ std::make_unique<location::nearby::windows::Executor>();
+ std::string output = std::string();
+ // Container to note threads that ran
+ std::unique_ptr<std::vector<DWORD>> threadIds =
+ std::make_unique<std::vector<DWORD>>();
+
+ threadIds->push_back(GetCurrentThreadId());
+
+ // Act
+ for (int index = 0; index < 5; index++) {
+ executor->Execute([&output, &threadIds, index]() {
+ threadIds->push_back(GetCurrentThreadId());
+ char buffer[128];
+ snprintf(buffer, sizeof(buffer), "%s%d, ", RUNNABLE_TEXT.c_str(), index);
+ output.append(std::string(buffer));
+ });
+ }
+
+ executor->Shutdown();
+
+ // Assert
+ // We should've run 1 time on the main thread, and 5 times on the
+ // workerThread
+ ASSERT_EQ(threadIds->size(), 6);
+ // We should still be on the main thread
+ ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
+ // We should've run all runnables on the worker thread
+ auto workerThreadId = threadIds->at(1);
+ for (int index = 1; index < threadIds->size(); index++) {
+ ASSERT_EQ(threadIds->at(index), workerThreadId);
+ }
+
+ // We should of run them in the order submitted
+ ASSERT_EQ(output, expected);
+}
+
+TEST(ExecutorTests, MultiThreadedExecutorSingleTaskSucceeds) {
+ // Arrange
+ std::string expected(RUNNABLE_0_TEXT.c_str());
+
+ std::unique_ptr<location::nearby::windows::Executor> executor =
+ std::make_unique<location::nearby::windows::Executor>(2);
+
+ // Container to note threads that ran
+ std::unique_ptr<std::vector<DWORD>> threadIds =
+ std::make_unique<std::vector<DWORD>>();
+
+ std::shared_ptr<std::string> output = std::make_shared<std::string>();
+
+ threadIds->push_back(GetCurrentThreadId());
+
+ // Act
+ executor->Execute([output, &threadIds]() {
+ threadIds->push_back(GetCurrentThreadId());
+ output->append(RUNNABLE_0_TEXT.c_str());
+ });
+
+ executor->Shutdown();
+
+ // Assert
+ // We should've run 1 time on the main thread, and 5 times on the
+ // workerThread
+ ASSERT_EQ(threadIds->size(), 2);
+ // We should still be on the main thread
+ ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
+ // We should've run the task
+ ASSERT_EQ(*output.get(), expected);
+}
+
+TEST(ExecutorTests, MultiThreadedExecutorMultipleTasksSucceeds) {
+ // Arrange
+ std::unique_ptr<location::nearby::windows::Executor> executor =
+ std::make_unique<location::nearby::windows::Executor>(2);
+
+ // Container to note threads that ran
+ std::unique_ptr<std::vector<DWORD>> threadIds =
+ std::make_unique<std::vector<DWORD>>();
+
+ std::shared_ptr<std::string> output = std::make_shared<std::string>();
+
+ threadIds->push_back(GetCurrentThreadId());
+
+ // Act
+ for (int index = 0; index < 5; index++) {
+ executor->Execute([&output, &threadIds, index]() {
+ threadIds->push_back(GetCurrentThreadId());
+ char buffer[128];
+ snprintf(buffer, sizeof(buffer), "%s %d, ", RUNNABLE_TEXT.c_str(), index);
+ output->append(std::string(buffer));
+ });
+ }
+
+ executor->Shutdown();
+
+ // Assert
+ // We should've run 1 time on the main thread, and 5 times on the
+ // workerThread
+ ASSERT_EQ(threadIds->size(), 6);
+ // We should still be on the main thread
+ ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
+}
+
+TEST(ExecutorTests, MultiThreadedExecutorSingleTaskAfterShutdownFails) {
+ // Arrange
+ std::string expected("");
+
+ std::unique_ptr<location::nearby::windows::Executor> executor =
+ std::make_unique<location::nearby::windows::Executor>(2);
+
+ // Container to note threads that ran
+ std::unique_ptr<std::vector<DWORD>> threadIds =
+ std::make_unique<std::vector<DWORD>>();
+
+ std::shared_ptr<std::string> output = std::make_shared<std::string>();
+
+ threadIds->push_back(GetCurrentThreadId());
+
+ executor->Shutdown();
+
+ // Act
+ executor->Execute([output, &threadIds]() {
+ threadIds->push_back(GetCurrentThreadId());
+ output->append(RUNNABLE_0_TEXT.c_str());
+ });
+
+ // Assert
+ // We should've run 1 time on the main thread, and 5 times on the
+ // workerThread
+ ASSERT_EQ(threadIds->size(), 1);
+ // We should still be on the main thread
+ ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
+ // We should've run the task
+ ASSERT_EQ(*output.get(), expected);
+}
+
+TEST(ExecutorTests, MultiThreadedExecutorNegativeThreadsThrows) {
+ // Arrange
+ // Act
+ // Assert
+ EXPECT_THROW(
+ {
+ try {
+ auto result =
+ std::make_unique<location::nearby::windows::Executor>(-1);
+ } catch (const std::invalid_argument::exception& e) {
+ // and this tests that it has the correct message
+ EXPECT_STREQ(INVALID_ARGUMENT_TEXT, e.what());
+ throw;
+ }
+ },
+ std::invalid_argument);
+}
+
+TEST(ExecutorTests, MultiThreadedExecutorTooManyThreadsThrows) {
+ // Arrange
+ // Act
+ // Assert
+ EXPECT_THROW(
+ {
+ try {
+ auto result =
+ std::make_unique<location::nearby::windows::Executor>(65);
+ } catch (const location::nearby::windows::ThreadPoolException& e) {
+ // and this tests that it has the correct message
+ EXPECT_STREQ(THREADPOOL_MAX_SIZE_TEXT, e.what());
+ throw;
+ }
+ },
+ location::nearby::windows::ThreadPoolException);
+}
+
+TEST(ExecutorTests,
+ MultiThreadedExecutorMultipleTasksLargeNumberOfThreadsSucceeds) {
+ // Arrange
+ std::unique_ptr<location::nearby::windows::Executor> executor =
+ std::make_unique<location::nearby::windows::Executor>(
+ MAXIMUM_WAIT_OBJECTS - 1);
+
+ // Container to note threads that ran
+ std::vector<DWORD> threadIds = std::vector<DWORD>();
+
+ std::shared_ptr<std::string> output = std::make_shared<std::string>();
+
+ threadIds.push_back(GetCurrentThreadId());
+
+ CRITICAL_SECTION testCriticalSection;
+ InitializeCriticalSection(&testCriticalSection);
+
+ // Act
+ for (int index = 0; index < 250; index++) {
+ executor->Execute(
+ [output, &threadIds, index, &testCriticalSection]() mutable {
+ DWORD id = GetCurrentThreadId();
+
+ EnterCriticalSection(&testCriticalSection);
+
+ threadIds.push_back(id);
+ output->append(RUNNABLE_TEXT);
+ output->append(std::to_string(index));
+ output->append(RUNNABLE_SEPARATOR_TEXT);
+
+ LeaveCriticalSection(&testCriticalSection);
+ // Using rand since this is in a critical section
+ // and windows doesn't have a rand_r anyway
+ auto sleepTime = (std::rand() % 101) + 1; // NOLINT
+
+ Sleep(sleepTime);
+ });
+ }
+
+ executor->Shutdown();
+ DeleteCriticalSection(&testCriticalSection);
+
+ // Assert
+ // We should still be on the main thread
+ ASSERT_EQ(GetCurrentThreadId(), threadIds.at(0));
+
+ std::sort(threadIds.begin(), threadIds.end());
+ int64_t uniqueIds =
+ std::unique(threadIds.begin(), threadIds.end()) - threadIds.begin();
+
+ ASSERT_EQ(uniqueIds, 64);
+ // We should've run 1 time on the main thread, and 200 times on the
+ // workerThreads
+ ASSERT_EQ(threadIds.size(), 251);
+}
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/future.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/future.h
new file mode 100644
index 00000000000..5d7a034e2f8
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/future.h
@@ -0,0 +1,50 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_FUTURE_H_
+#define PLATFORM_IMPL_WINDOWS_FUTURE_H_
+
+#include "internal/platform/implementation/future.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+// A Future represents the result of an asynchronous computation.
+//
+// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html
+template <typename T>
+class Future : public api::Future<T> {
+ public:
+ // TODO(b/184975123): replace with real implementation.
+ ~Future() override = default;
+
+ // throws Exception::kInterrupted, Exception::kExecution
+ // TODO(b/184975123): replace with real implementation.
+ ExceptionOr<T> Get() override { return ExceptionOr<T>{Exception::kFailed}; }
+
+ // throws Exception::kInterrupted, Exception::kExecution
+ // throws Exception::kTimeout if timeout is exceeded while waiting for
+ // result.
+ // TODO(b/184975123): replace with real implementation.
+ ExceptionOr<T> Get(absl::Duration timeout) override {
+ return ExceptionOr<T>{Exception::kFailed};
+ }
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_WINDOWS_FUTURE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/BUILD b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/BUILD
new file mode 100644
index 00000000000..441241c7625
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/BUILD
@@ -0,0 +1,42 @@
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+licenses(["notice"])
+
+cc_library(
+ name = "types",
+ linkopts = [
+ "advapi32.lib",
+ "comdlg32.lib",
+ "gdi32.lib",
+ "kernel32.lib",
+ "odbc32.lib",
+ "odbccp32.lib",
+ "ole32.lib",
+ "oleaut32.lib",
+ "shell32.lib",
+ "user32.lib",
+ "uuid.lib",
+ "winmm.lib",
+ "winspool.lib",
+ "comsuppwd.lib",
+ "setupapi.lib",
+ "dnsapi.lib",
+ ],
+ textual_hdrs = glob(["**/*.h"]),
+ visibility = [
+ "//location/nearby/cpp/sharing/implementation/internal:__subpackages__",
+ "//connections/windows:__subpackages__",
+ "//internal/platform/implementation/windows:__subpackages__",
+ ],
+)
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.AI.MachineLearning.Preview.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.AI.MachineLearning.Preview.h
index 5000b4ee50c..5000b4ee50c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.AI.MachineLearning.Preview.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.AI.MachineLearning.Preview.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.AI.MachineLearning.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.AI.MachineLearning.h
index c2b31115c42..c2b31115c42 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.AI.MachineLearning.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.AI.MachineLearning.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Activation.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Activation.h
index 641ab01e7d7..641ab01e7d7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Activation.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Activation.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.AppExtensions.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.AppExtensions.h
index ab05835d8c6..ab05835d8c6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.AppExtensions.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.AppExtensions.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.AppService.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.AppService.h
index b97aa523424..b97aa523424 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.AppService.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.AppService.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Appointments.AppointmentsProvider.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Appointments.AppointmentsProvider.h
index b5a0983ba5b..b5a0983ba5b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Appointments.AppointmentsProvider.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Appointments.AppointmentsProvider.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Appointments.DataProvider.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Appointments.DataProvider.h
index 0308d751e62..0308d751e62 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Appointments.DataProvider.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Appointments.DataProvider.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Appointments.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Appointments.h
index 05f28a31b70..05f28a31b70 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Appointments.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Appointments.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Background.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Background.h
index cbb37098763..cbb37098763 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Background.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Background.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Calls.Background.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Calls.Background.h
index ae31e800e2c..ae31e800e2c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Calls.Background.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Calls.Background.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Calls.Provider.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Calls.Provider.h
index 072e37ba1c2..072e37ba1c2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Calls.Provider.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Calls.Provider.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Calls.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Calls.h
index c9240bbe4b9..c9240bbe4b9 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Calls.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Calls.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Chat.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Chat.h
index 17a811ed66a..17a811ed66a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Chat.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Chat.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.CommunicationBlocking.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.CommunicationBlocking.h
index af1df87aa3d..af1df87aa3d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.CommunicationBlocking.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.CommunicationBlocking.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Contacts.DataProvider.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Contacts.DataProvider.h
index f79b41682f2..f79b41682f2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Contacts.DataProvider.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Contacts.DataProvider.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Contacts.Provider.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Contacts.Provider.h
index cb8e210577f..cb8e210577f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Contacts.Provider.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Contacts.Provider.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Contacts.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Contacts.h
index 58c907a14b9..58c907a14b9 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Contacts.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Contacts.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.ConversationalAgent.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.ConversationalAgent.h
index 4fddfc62b42..4fddfc62b42 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.ConversationalAgent.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.ConversationalAgent.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Core.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Core.h
index 126d565c857..126d565c857 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Core.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Core.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.DataTransfer.DragDrop.Core.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.DataTransfer.DragDrop.Core.h
index 5274165f44d..5274165f44d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.DataTransfer.DragDrop.Core.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.DataTransfer.DragDrop.Core.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.DataTransfer.DragDrop.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.DataTransfer.DragDrop.h
index 176557a70ba..176557a70ba 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.DataTransfer.DragDrop.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.DataTransfer.DragDrop.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.DataTransfer.ShareTarget.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.DataTransfer.ShareTarget.h
index 568f89c2bad..568f89c2bad 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.DataTransfer.ShareTarget.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.DataTransfer.ShareTarget.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.DataTransfer.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.DataTransfer.h
index a1397becd12..a1397becd12 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.DataTransfer.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.DataTransfer.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Email.DataProvider.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Email.DataProvider.h
index 3418ea8872d..3418ea8872d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Email.DataProvider.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Email.DataProvider.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Email.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Email.h
index 313cd3dc8d1..313cd3dc8d1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Email.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Email.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.ExtendedExecution.Foreground.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.ExtendedExecution.Foreground.h
index 7c281800d77..7c281800d77 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.ExtendedExecution.Foreground.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.ExtendedExecution.Foreground.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.ExtendedExecution.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.ExtendedExecution.h
index f6a7ec8731d..f6a7ec8731d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.ExtendedExecution.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.ExtendedExecution.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Holographic.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Holographic.h
index eb75a92367e..eb75a92367e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Holographic.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Holographic.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.LockScreen.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.LockScreen.h
index e45e67e5bb4..e45e67e5bb4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.LockScreen.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.LockScreen.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Payments.Provider.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Payments.Provider.h
index 50f15b05483..50f15b05483 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Payments.Provider.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Payments.Provider.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Payments.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Payments.h
index e3b3cdddb14..e3b3cdddb14 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Payments.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Payments.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Preview.Holographic.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Preview.Holographic.h
index 5139c41b38c..5139c41b38c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Preview.Holographic.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Preview.Holographic.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Preview.InkWorkspace.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Preview.InkWorkspace.h
index c90949273e9..c90949273e9 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Preview.InkWorkspace.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Preview.InkWorkspace.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Preview.Notes.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Preview.Notes.h
index 750c93f8ed9..750c93f8ed9 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Preview.Notes.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Preview.Notes.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Resources.Core.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Resources.Core.h
index b9f8d8bdd0f..b9f8d8bdd0f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Resources.Core.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Resources.Core.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Resources.Management.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Resources.Management.h
index a017ac5935b..a017ac5935b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Resources.Management.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Resources.Management.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Resources.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Resources.h
index 194df637741..194df637741 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Resources.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Resources.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Search.Core.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Search.Core.h
index 20a523f3c30..20a523f3c30 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Search.Core.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Search.Core.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Search.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Search.h
index 144cce0bbbc..144cce0bbbc 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Search.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Search.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.SocialInfo.Provider.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.SocialInfo.Provider.h
index b495d51937a..b495d51937a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.SocialInfo.Provider.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.SocialInfo.Provider.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.SocialInfo.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.SocialInfo.h
index ea9df91266a..ea9df91266a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.SocialInfo.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.SocialInfo.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Store.LicenseManagement.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Store.LicenseManagement.h
index b061c3ceb46..b061c3ceb46 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Store.LicenseManagement.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Store.LicenseManagement.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Store.Preview.InstallControl.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Store.Preview.InstallControl.h
index 6295a04cb79..6295a04cb79 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Store.Preview.InstallControl.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Store.Preview.InstallControl.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Store.Preview.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Store.Preview.h
index ff9f4145c9f..ff9f4145c9f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Store.Preview.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Store.Preview.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Store.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Store.h
index 0b5dc49c98b..0b5dc49c98b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Store.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Store.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.UserActivities.Core.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.UserActivities.Core.h
index 105a26d6295..105a26d6295 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.UserActivities.Core.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.UserActivities.Core.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.UserActivities.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.UserActivities.h
index 00cae3bdefc..00cae3bdefc 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.UserActivities.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.UserActivities.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.UserDataAccounts.Provider.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.UserDataAccounts.Provider.h
index ddae502b25e..ddae502b25e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.UserDataAccounts.Provider.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.UserDataAccounts.Provider.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.UserDataAccounts.SystemAccess.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.UserDataAccounts.SystemAccess.h
index 2be506fba1f..2be506fba1f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.UserDataAccounts.SystemAccess.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.UserDataAccounts.SystemAccess.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.UserDataAccounts.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.UserDataAccounts.h
index fc97f59e23b..fc97f59e23b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.UserDataAccounts.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.UserDataAccounts.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.UserDataTasks.DataProvider.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.UserDataTasks.DataProvider.h
index 75055ca7d4b..75055ca7d4b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.UserDataTasks.DataProvider.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.UserDataTasks.DataProvider.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.UserDataTasks.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.UserDataTasks.h
index dbfff210a6e..dbfff210a6e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.UserDataTasks.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.UserDataTasks.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.VoiceCommands.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.VoiceCommands.h
index 363790b8a66..363790b8a66 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.VoiceCommands.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.VoiceCommands.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Wallet.System.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Wallet.System.h
index ea912d75c80..ea912d75c80 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Wallet.System.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Wallet.System.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Wallet.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Wallet.h
index 78eb8ef7459..78eb8ef7459 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.Wallet.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.Wallet.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.h
index 7cb182363b3..7cb182363b3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.ApplicationModel.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.ApplicationModel.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Data.Html.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Data.Html.h
index 28e6024213c..28e6024213c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Data.Html.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Data.Html.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Data.Json.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Data.Json.h
index 00d33264a3e..00d33264a3e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Data.Json.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Data.Json.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Data.Pdf.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Data.Pdf.h
index 090dbbe2163..090dbbe2163 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Data.Pdf.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Data.Pdf.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Data.Text.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Data.Text.h
index 440d7f36778..440d7f36778 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Data.Text.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Data.Text.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Data.Xml.Dom.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Data.Xml.Dom.h
index 583cd136e4c..583cd136e4c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Data.Xml.Dom.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Data.Xml.Dom.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Data.Xml.Xsl.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Data.Xml.Xsl.h
index 8ae25ebce0d..8ae25ebce0d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Data.Xml.Xsl.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Data.Xml.Xsl.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Adc.Provider.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Adc.Provider.h
index da9fc1f98a7..da9fc1f98a7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Adc.Provider.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Adc.Provider.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Adc.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Adc.h
index c43f4e9582f..c43f4e9582f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Adc.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Adc.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.AllJoyn.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.AllJoyn.h
index a4ad480f9d6..a4ad480f9d6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.AllJoyn.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.AllJoyn.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Background.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Background.h
index 35b964cffca..35b964cffca 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Background.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Background.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Bluetooth.Advertisement.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Bluetooth.Advertisement.h
index d29158d290c..d29158d290c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Bluetooth.Advertisement.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Bluetooth.Advertisement.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Bluetooth.Background.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Bluetooth.Background.h
index d7a6ef705d5..d7a6ef705d5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Bluetooth.Background.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Bluetooth.Background.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Bluetooth.GenericAttributeProfile.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Bluetooth.GenericAttributeProfile.h
index af18224cfec..af18224cfec 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Bluetooth.GenericAttributeProfile.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Bluetooth.GenericAttributeProfile.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Bluetooth.Rfcomm.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Bluetooth.Rfcomm.h
index 41016076e12..41016076e12 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Bluetooth.Rfcomm.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Bluetooth.Rfcomm.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Bluetooth.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Bluetooth.h
index 79f8ddf91e5..79f8ddf91e5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Bluetooth.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Bluetooth.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Custom.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Custom.h
index 9251db7b101..9251db7b101 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Custom.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Custom.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Display.Core.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Display.Core.h
index a72c2ef767a..a72c2ef767a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Display.Core.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Display.Core.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Display.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Display.h
index 57f7aac93e2..57f7aac93e2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Display.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Display.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Enumeration.Pnp.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Enumeration.Pnp.h
index e33efc35eaa..e33efc35eaa 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Enumeration.Pnp.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Enumeration.Pnp.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Enumeration.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Enumeration.h
index d3bcd21b381..d3bcd21b381 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Enumeration.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Enumeration.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Geolocation.Geofencing.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Geolocation.Geofencing.h
index f65fd614c4d..f65fd614c4d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Geolocation.Geofencing.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Geolocation.Geofencing.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Geolocation.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Geolocation.h
index 2aeeb742a29..2aeeb742a29 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Geolocation.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Geolocation.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Gpio.Provider.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Gpio.Provider.h
index e805b876c30..e805b876c30 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Gpio.Provider.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Gpio.Provider.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Gpio.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Gpio.h
index a0d8ad014de..a0d8ad014de 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Gpio.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Gpio.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Haptics.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Haptics.h
index c66e0250ecc..c66e0250ecc 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Haptics.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Haptics.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.HumanInterfaceDevice.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.HumanInterfaceDevice.h
index 8a8c14566cd..8a8c14566cd 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.HumanInterfaceDevice.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.HumanInterfaceDevice.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.I2c.Provider.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.I2c.Provider.h
index 27a48fd6fa3..27a48fd6fa3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.I2c.Provider.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.I2c.Provider.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.I2c.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.I2c.h
index 135e403b90c..135e403b90c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.I2c.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.I2c.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Input.Preview.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Input.Preview.h
index f4da9f3a45b..f4da9f3a45b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Input.Preview.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Input.Preview.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Input.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Input.h
index 3c0dc91952a..3c0dc91952a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Input.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Input.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Lights.Effects.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Lights.Effects.h
index 98dd9e0f32a..98dd9e0f32a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Lights.Effects.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Lights.Effects.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Lights.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Lights.h
index cb99c385c7f..cb99c385c7f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Lights.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Lights.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Midi.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Midi.h
index 002d84fc8ac..002d84fc8ac 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Midi.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Midi.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Perception.Provider.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Perception.Provider.h
index 806c9a0ba2d..806c9a0ba2d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Perception.Provider.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Perception.Provider.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Perception.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Perception.h
index 86a1959608a..86a1959608a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Perception.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Perception.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.PointOfService.Provider.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.PointOfService.Provider.h
index 2c9a8aed180..2c9a8aed180 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.PointOfService.Provider.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.PointOfService.Provider.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.PointOfService.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.PointOfService.h
index 731794ab842..731794ab842 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.PointOfService.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.PointOfService.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Portable.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Portable.h
index 62e8681801b..62e8681801b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Portable.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Portable.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Power.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Power.h
index a43926ddbdc..a43926ddbdc 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Power.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Power.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Printers.Extensions.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Printers.Extensions.h
index 19cd8f157b2..19cd8f157b2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Printers.Extensions.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Printers.Extensions.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Printers.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Printers.h
index 1333a1130aa..1333a1130aa 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Printers.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Printers.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Pwm.Provider.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Pwm.Provider.h
index ab8e7fca3b0..ab8e7fca3b0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Pwm.Provider.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Pwm.Provider.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Pwm.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Pwm.h
index 694f589dd9b..694f589dd9b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Pwm.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Pwm.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Radios.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Radios.h
index b6d004cc33d..b6d004cc33d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Radios.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Radios.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Scanners.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Scanners.h
index 698f42c8e5c..698f42c8e5c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Scanners.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Scanners.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Sensors.Custom.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Sensors.Custom.h
index bb270c6282a..bb270c6282a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Sensors.Custom.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Sensors.Custom.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Sensors.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Sensors.h
index a6a5c05742a..a6a5c05742a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Sensors.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Sensors.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.SerialCommunication.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.SerialCommunication.h
index a003a58549e..a003a58549e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.SerialCommunication.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.SerialCommunication.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.SmartCards.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.SmartCards.h
index f1ff01dc27f..f1ff01dc27f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.SmartCards.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.SmartCards.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Sms.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Sms.h
index 1baa042a897..1baa042a897 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Sms.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Sms.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Spi.Provider.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Spi.Provider.h
index 27d9f9cbaf0..27d9f9cbaf0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Spi.Provider.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Spi.Provider.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Spi.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Spi.h
index b28f360c0d4..b28f360c0d4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Spi.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Spi.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Usb.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Usb.h
index d44e4fe9e31..d44e4fe9e31 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.Usb.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.Usb.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.WiFi.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.WiFi.h
index 4447c849ddc..4447c849ddc 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.WiFi.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.WiFi.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.WiFiDirect.Services.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.WiFiDirect.Services.h
index eff24de41dd..eff24de41dd 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.WiFiDirect.Services.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.WiFiDirect.Services.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.WiFiDirect.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.WiFiDirect.h
index cd43e46f092..cd43e46f092 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.WiFiDirect.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.WiFiDirect.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.h
index fcf3dcfecc4..fcf3dcfecc4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Devices.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Devices.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Embedded.DeviceLockdown.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Embedded.DeviceLockdown.h
index 9f1d9beba9d..9f1d9beba9d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Embedded.DeviceLockdown.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Embedded.DeviceLockdown.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Foundation.Collections.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Foundation.Collections.h
index 4ba15a0cff2..4ba15a0cff2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Foundation.Collections.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Foundation.Collections.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Foundation.Diagnostics.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Foundation.Diagnostics.h
index 5c783969600..5c783969600 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Foundation.Diagnostics.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Foundation.Diagnostics.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Foundation.Metadata.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Foundation.Metadata.h
index d608d6f6699..d608d6f6699 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Foundation.Metadata.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Foundation.Metadata.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Foundation.Numerics.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Foundation.Numerics.h
index 66067b3fc8d..66067b3fc8d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Foundation.Numerics.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Foundation.Numerics.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Foundation.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Foundation.h
index 321c5d4d212..321c5d4d212 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Foundation.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Foundation.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Gaming.Input.Custom.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Gaming.Input.Custom.h
index ce266d7979d..ce266d7979d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Gaming.Input.Custom.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Gaming.Input.Custom.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Gaming.Input.ForceFeedback.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Gaming.Input.ForceFeedback.h
index bb250344549..bb250344549 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Gaming.Input.ForceFeedback.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Gaming.Input.ForceFeedback.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Gaming.Input.Preview.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Gaming.Input.Preview.h
index d8696b16ebb..d8696b16ebb 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Gaming.Input.Preview.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Gaming.Input.Preview.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Gaming.Input.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Gaming.Input.h
index 961e11e14da..961e11e14da 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Gaming.Input.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Gaming.Input.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Gaming.Preview.GamesEnumeration.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Gaming.Preview.GamesEnumeration.h
index 42577105ee8..42577105ee8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Gaming.Preview.GamesEnumeration.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Gaming.Preview.GamesEnumeration.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Gaming.UI.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Gaming.UI.h
index 9b7c80f4e2c..9b7c80f4e2c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Gaming.UI.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Gaming.UI.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Gaming.XboxLive.Storage.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Gaming.XboxLive.Storage.h
index 6f6ec4213ec..6f6ec4213ec 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Gaming.XboxLive.Storage.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Gaming.XboxLive.Storage.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Globalization.Collation.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Globalization.Collation.h
index 1a83cb9988f..1a83cb9988f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Globalization.Collation.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Globalization.Collation.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Globalization.DateTimeFormatting.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Globalization.DateTimeFormatting.h
index c2ed37bd795..c2ed37bd795 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Globalization.DateTimeFormatting.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Globalization.DateTimeFormatting.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Globalization.Fonts.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Globalization.Fonts.h
index 92202804f3c..92202804f3c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Globalization.Fonts.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Globalization.Fonts.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Globalization.NumberFormatting.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Globalization.NumberFormatting.h
index 49cbd959a57..49cbd959a57 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Globalization.NumberFormatting.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Globalization.NumberFormatting.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Globalization.PhoneNumberFormatting.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Globalization.PhoneNumberFormatting.h
index 44b9652f4b2..44b9652f4b2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Globalization.PhoneNumberFormatting.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Globalization.PhoneNumberFormatting.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Globalization.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Globalization.h
index 10adb3a7322..10adb3a7322 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Globalization.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Globalization.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Capture.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Capture.h
index 26996828dcf..26996828dcf 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Capture.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Capture.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.DirectX.Direct3D11.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.DirectX.Direct3D11.h
index ecf331d51aa..ecf331d51aa 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.DirectX.Direct3D11.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.DirectX.Direct3D11.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.DirectX.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.DirectX.h
index 275faeed47f..275faeed47f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.DirectX.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.DirectX.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Display.Core.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Display.Core.h
index 5d4655032f3..5d4655032f3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Display.Core.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Display.Core.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Display.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Display.h
index 169dafc6288..169dafc6288 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Display.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Display.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Effects.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Effects.h
index 911401ae609..911401ae609 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Effects.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Effects.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Holographic.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Holographic.h
index 8b560af8529..8b560af8529 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Holographic.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Holographic.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Imaging.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Imaging.h
index c68a9e5fd66..c68a9e5fd66 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Imaging.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Imaging.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Printing.OptionDetails.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Printing.OptionDetails.h
index e831641dcc7..e831641dcc7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Printing.OptionDetails.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Printing.OptionDetails.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Printing.PrintTicket.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Printing.PrintTicket.h
index ef15dd2c0b0..ef15dd2c0b0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Printing.PrintTicket.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Printing.PrintTicket.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Printing.Workflow.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Printing.Workflow.h
index feaff3c671d..feaff3c671d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Printing.Workflow.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Printing.Workflow.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Printing.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Printing.h
index 252e40714aa..252e40714aa 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Printing.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Printing.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Printing3D.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Printing3D.h
index f5e5af9ee2d..f5e5af9ee2d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.Printing3D.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.Printing3D.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.h
index 26ca2ec33dd..26ca2ec33dd 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Graphics.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Graphics.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Management.Core.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Management.Core.h
index f37fe0b1b42..f37fe0b1b42 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Management.Core.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Management.Core.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Management.Deployment.Preview.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Management.Deployment.Preview.h
index 20a070a2e5f..20a070a2e5f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Management.Deployment.Preview.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Management.Deployment.Preview.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Management.Deployment.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Management.Deployment.h
index b6132273b9d..b6132273b9d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Management.Deployment.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Management.Deployment.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Management.Policies.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Management.Policies.h
index 10abd0c4b67..10abd0c4b67 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Management.Policies.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Management.Policies.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Management.Update.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Management.Update.h
index 5298010e35d..5298010e35d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Management.Update.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Management.Update.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Management.Workplace.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Management.Workplace.h
index af8ba124c52..af8ba124c52 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Management.Workplace.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Management.Workplace.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Management.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Management.h
index 194ccc6858c..194ccc6858c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Management.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Management.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.AppBroadcasting.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.AppBroadcasting.h
index 9ed1d728274..9ed1d728274 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.AppBroadcasting.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.AppBroadcasting.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.AppRecording.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.AppRecording.h
index f405fef73a0..f405fef73a0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.AppRecording.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.AppRecording.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Audio.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Audio.h
index 99c2faf13f0..99c2faf13f0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Audio.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Audio.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Capture.Core.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Capture.Core.h
index 6ddeffae0ec..6ddeffae0ec 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Capture.Core.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Capture.Core.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Capture.Frames.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Capture.Frames.h
index e8903972df9..e8903972df9 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Capture.Frames.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Capture.Frames.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Capture.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Capture.h
index 6ec53392636..6ec53392636 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Capture.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Capture.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Casting.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Casting.h
index b4895f8aab1..b4895f8aab1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Casting.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Casting.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.ClosedCaptioning.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.ClosedCaptioning.h
index f6945eac92a..f6945eac92a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.ClosedCaptioning.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.ClosedCaptioning.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.ContentRestrictions.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.ContentRestrictions.h
index 4731433a1c0..4731433a1c0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.ContentRestrictions.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.ContentRestrictions.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Control.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Control.h
index 770f0e61f67..770f0e61f67 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Control.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Control.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Core.Preview.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Core.Preview.h
index c276cb2c43e..c276cb2c43e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Core.Preview.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Core.Preview.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Core.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Core.h
index b6c39ba932e..b6c39ba932e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Core.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Core.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Devices.Core.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Devices.Core.h
index 2ab8878fe0b..2ab8878fe0b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Devices.Core.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Devices.Core.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Devices.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Devices.h
index 502ae31c75f..502ae31c75f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Devices.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Devices.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.DialProtocol.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.DialProtocol.h
index 6fa660ad458..6fa660ad458 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.DialProtocol.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.DialProtocol.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Editing.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Editing.h
index a59d5ddf7d1..a59d5ddf7d1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Editing.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Editing.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Effects.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Effects.h
index f8a3031c7d8..f8a3031c7d8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Effects.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Effects.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.FaceAnalysis.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.FaceAnalysis.h
index fd5a4529832..fd5a4529832 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.FaceAnalysis.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.FaceAnalysis.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Import.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Import.h
index 60fd6bdc88d..60fd6bdc88d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Import.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Import.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.MediaProperties.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.MediaProperties.h
index 7ed7bcd9107..7ed7bcd9107 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.MediaProperties.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.MediaProperties.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Miracast.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Miracast.h
index f171855d482..f171855d482 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Miracast.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Miracast.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Ocr.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Ocr.h
index 2ddfa0d8593..2ddfa0d8593 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Ocr.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Ocr.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.PlayTo.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.PlayTo.h
index 4568b6af7db..4568b6af7db 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.PlayTo.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.PlayTo.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Playback.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Playback.h
index b21146d6b64..b21146d6b64 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Playback.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Playback.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Playlists.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Playlists.h
index 29627537ac3..29627537ac3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Playlists.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Playlists.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Protection.PlayReady.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Protection.PlayReady.h
index 95ad96094b4..95ad96094b4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Protection.PlayReady.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Protection.PlayReady.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Protection.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Protection.h
index 28872e8de39..28872e8de39 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Protection.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Protection.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Render.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Render.h
index 41e0601775d..41e0601775d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Render.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Render.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.SpeechRecognition.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.SpeechRecognition.h
index 3369859273f..3369859273f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.SpeechRecognition.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.SpeechRecognition.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.SpeechSynthesis.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.SpeechSynthesis.h
index 133d7601888..133d7601888 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.SpeechSynthesis.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.SpeechSynthesis.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Streaming.Adaptive.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Streaming.Adaptive.h
index 6d2017908cf..6d2017908cf 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Streaming.Adaptive.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Streaming.Adaptive.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Transcoding.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Transcoding.h
index a0ec7047c3c..a0ec7047c3c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.Transcoding.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.Transcoding.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.h
index bb78faab76e..bb78faab76e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Media.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Media.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.BackgroundTransfer.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.BackgroundTransfer.h
index 6df645bd0db..6df645bd0db 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.BackgroundTransfer.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.BackgroundTransfer.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.Connectivity.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.Connectivity.h
index 4962b755fb7..4962b755fb7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.Connectivity.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.Connectivity.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.NetworkOperators.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.NetworkOperators.h
index 3430f7b2a91..3430f7b2a91 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.NetworkOperators.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.NetworkOperators.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.Proximity.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.Proximity.h
index 48bd0f536f6..48bd0f536f6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.Proximity.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.Proximity.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.PushNotifications.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.PushNotifications.h
index 7a43c9caecb..7a43c9caecb 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.PushNotifications.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.PushNotifications.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.ServiceDiscovery.Dnssd.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.ServiceDiscovery.Dnssd.h
index edf469019ee..edf469019ee 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.ServiceDiscovery.Dnssd.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.ServiceDiscovery.Dnssd.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.Sockets.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.Sockets.h
index c2b3e86f3c4..c2b3e86f3c4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.Sockets.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.Sockets.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.Vpn.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.Vpn.h
index 2ee535b3c70..2ee535b3c70 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.Vpn.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.Vpn.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.XboxLive.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.XboxLive.h
index 736e54ea7cc..736e54ea7cc 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.XboxLive.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.XboxLive.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.h
index c572754fb77..c572754fb77 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Networking.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Networking.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Perception.Automation.Core.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Perception.Automation.Core.h
index bc5ff9fa870..bc5ff9fa870 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Perception.Automation.Core.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Perception.Automation.Core.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Perception.People.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Perception.People.h
index db3957ea9a6..db3957ea9a6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Perception.People.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Perception.People.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Perception.Spatial.Preview.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Perception.Spatial.Preview.h
index 173608c9347..173608c9347 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Perception.Spatial.Preview.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Perception.Spatial.Preview.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Perception.Spatial.Surfaces.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Perception.Spatial.Surfaces.h
index 5f83e5350cd..5f83e5350cd 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Perception.Spatial.Surfaces.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Perception.Spatial.Surfaces.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Perception.Spatial.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Perception.Spatial.h
index c3d2658cfc4..c3d2658cfc4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Perception.Spatial.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Perception.Spatial.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Perception.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Perception.h
index 6714a1d54b6..6714a1d54b6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Perception.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Perception.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.ApplicationModel.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.ApplicationModel.h
index 8fb8f8d244f..8fb8f8d244f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.ApplicationModel.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.ApplicationModel.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.Devices.Notification.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.Devices.Notification.h
index 97288dd1db8..97288dd1db8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.Devices.Notification.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.Devices.Notification.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.Devices.Power.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.Devices.Power.h
index a86bb90ab8b..a86bb90ab8b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.Devices.Power.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.Devices.Power.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.Management.Deployment.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.Management.Deployment.h
index 5c1db0ac68d..5c1db0ac68d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.Management.Deployment.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.Management.Deployment.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.Media.Devices.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.Media.Devices.h
index 48be32f02e5..48be32f02e5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.Media.Devices.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.Media.Devices.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.Notification.Management.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.Notification.Management.h
index a769accc6d0..a769accc6d0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.Notification.Management.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.Notification.Management.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.PersonalInformation.Provisioning.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.PersonalInformation.Provisioning.h
index e0505255960..e0505255960 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.PersonalInformation.Provisioning.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.PersonalInformation.Provisioning.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.PersonalInformation.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.PersonalInformation.h
index c678edadcf0..c678edadcf0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.PersonalInformation.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.PersonalInformation.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.Speech.Recognition.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.Speech.Recognition.h
index 8af6ff9c146..8af6ff9c146 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.Speech.Recognition.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.Speech.Recognition.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.StartScreen.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.StartScreen.h
index 8a9e72ae404..8a9e72ae404 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.StartScreen.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.StartScreen.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.System.Power.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.System.Power.h
index 063c24acc2d..063c24acc2d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.System.Power.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.System.Power.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.System.Profile.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.System.Profile.h
index 1afd3459f55..1afd3459f55 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.System.Profile.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.System.Profile.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.System.UserProfile.GameServices.Core.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.System.UserProfile.GameServices.Core.h
index 6b5ba59e316..6b5ba59e316 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.System.UserProfile.GameServices.Core.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.System.UserProfile.GameServices.Core.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.System.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.System.h
index 6da1589d0e4..6da1589d0e4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.System.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.System.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.UI.Input.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.UI.Input.h
index a3735ec02d1..a3735ec02d1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Phone.UI.Input.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Phone.UI.Input.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Authentication.Identity.Core.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Authentication.Identity.Core.h
index 51f8d0a1bd5..51f8d0a1bd5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Authentication.Identity.Core.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Authentication.Identity.Core.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Authentication.Identity.Provider.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Authentication.Identity.Provider.h
index 9ec2b46cfe8..9ec2b46cfe8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Authentication.Identity.Provider.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Authentication.Identity.Provider.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Authentication.Identity.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Authentication.Identity.h
index 94cc9cbb779..94cc9cbb779 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Authentication.Identity.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Authentication.Identity.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Authentication.OnlineId.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Authentication.OnlineId.h
index bc50045bfcf..bc50045bfcf 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Authentication.OnlineId.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Authentication.OnlineId.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Authentication.Web.Core.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Authentication.Web.Core.h
index 91dbbddcff0..91dbbddcff0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Authentication.Web.Core.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Authentication.Web.Core.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Authentication.Web.Provider.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Authentication.Web.Provider.h
index 5c353da58d9..5c353da58d9 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Authentication.Web.Provider.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Authentication.Web.Provider.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Authentication.Web.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Authentication.Web.h
index c5d508c1ac4..c5d508c1ac4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Authentication.Web.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Authentication.Web.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Authorization.AppCapabilityAccess.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Authorization.AppCapabilityAccess.h
index 86e3dae1fee..86e3dae1fee 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Authorization.AppCapabilityAccess.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Authorization.AppCapabilityAccess.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Credentials.UI.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Credentials.UI.h
index 54642b872f7..54642b872f7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Credentials.UI.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Credentials.UI.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Credentials.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Credentials.h
index d3832ffa795..d3832ffa795 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Credentials.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Credentials.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Cryptography.Certificates.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Cryptography.Certificates.h
index 484c927a749..484c927a749 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Cryptography.Certificates.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Cryptography.Certificates.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Cryptography.Core.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Cryptography.Core.h
index 87e6b13b2bf..87e6b13b2bf 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Cryptography.Core.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Cryptography.Core.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Cryptography.DataProtection.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Cryptography.DataProtection.h
index 500f17a639c..500f17a639c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Cryptography.DataProtection.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Cryptography.DataProtection.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Cryptography.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Cryptography.h
index ce0e0e1c663..ce0e0e1c663 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Cryptography.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Cryptography.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.DataProtection.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.DataProtection.h
index f4dd6134245..f4dd6134245 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.DataProtection.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.DataProtection.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.EnterpriseData.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.EnterpriseData.h
index 85760613b3a..85760613b3a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.EnterpriseData.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.EnterpriseData.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.ExchangeActiveSyncProvisioning.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.ExchangeActiveSyncProvisioning.h
index 7b936ba4419..7b936ba4419 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.ExchangeActiveSyncProvisioning.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.ExchangeActiveSyncProvisioning.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Isolation.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Isolation.h
index 7d5b48898d2..7d5b48898d2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Security.Isolation.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Security.Isolation.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Services.Cortana.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Services.Cortana.h
index 65ef65a612c..65ef65a612c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Services.Cortana.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Services.Cortana.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Services.Maps.Guidance.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Services.Maps.Guidance.h
index 82c108ac75a..82c108ac75a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Services.Maps.Guidance.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Services.Maps.Guidance.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Services.Maps.LocalSearch.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Services.Maps.LocalSearch.h
index c68d05d7c4b..c68d05d7c4b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Services.Maps.LocalSearch.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Services.Maps.LocalSearch.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Services.Maps.OfflineMaps.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Services.Maps.OfflineMaps.h
index 947f3997840..947f3997840 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Services.Maps.OfflineMaps.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Services.Maps.OfflineMaps.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Services.Maps.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Services.Maps.h
index 41d41fd3ac3..41d41fd3ac3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Services.Maps.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Services.Maps.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Services.Store.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Services.Store.h
index 23e927c2f96..23e927c2f96 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Services.Store.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Services.Store.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Services.TargetedContent.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Services.TargetedContent.h
index 15977b4e29c..15977b4e29c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Services.TargetedContent.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Services.TargetedContent.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.AccessCache.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.AccessCache.h
index d4395b2d826..d4395b2d826 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.AccessCache.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.AccessCache.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.BulkAccess.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.BulkAccess.h
index 7d31d9815b8..7d31d9815b8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.BulkAccess.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.BulkAccess.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.Compression.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.Compression.h
index d73a65c9b0f..d73a65c9b0f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.Compression.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.Compression.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.FileProperties.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.FileProperties.h
index b440c15af2c..b440c15af2c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.FileProperties.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.FileProperties.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.Pickers.Provider.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.Pickers.Provider.h
index 5954c7c2d70..5954c7c2d70 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.Pickers.Provider.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.Pickers.Provider.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.Pickers.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.Pickers.h
index 1d5a07a5b95..1d5a07a5b95 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.Pickers.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.Pickers.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.Provider.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.Provider.h
index 739a13ffb13..739a13ffb13 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.Provider.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.Provider.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.Search.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.Search.h
index 58d53c49202..58d53c49202 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.Search.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.Search.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.Streams.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.Streams.h
index 1e06ded9dda..1e06ded9dda 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.Streams.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.Streams.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.h
index 4e0947a36d6..4e0947a36d6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Storage.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Storage.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Diagnostics.DevicePortal.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Diagnostics.DevicePortal.h
index 0bd40f5495f..0bd40f5495f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Diagnostics.DevicePortal.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Diagnostics.DevicePortal.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Diagnostics.Telemetry.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Diagnostics.Telemetry.h
index e76b9f93a69..e76b9f93a69 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Diagnostics.Telemetry.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Diagnostics.Telemetry.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Diagnostics.TraceReporting.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Diagnostics.TraceReporting.h
index 835fbcbf7a7..835fbcbf7a7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Diagnostics.TraceReporting.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Diagnostics.TraceReporting.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Diagnostics.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Diagnostics.h
index 8c963fda1a3..8c963fda1a3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Diagnostics.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Diagnostics.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Display.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Display.h
index b98eb2de1af..b98eb2de1af 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Display.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Display.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Implementation.FileExplorer.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Implementation.FileExplorer.h
index 12b238349d3..12b238349d3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Implementation.FileExplorer.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Implementation.FileExplorer.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Inventory.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Inventory.h
index f6a60cf32e4..f6a60cf32e4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Inventory.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Inventory.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Power.Diagnostics.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Power.Diagnostics.h
index 0f5aa201017..0f5aa201017 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Power.Diagnostics.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Power.Diagnostics.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Power.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Power.h
index 3dde95a3173..3dde95a3173 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Power.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Power.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Preview.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Preview.h
index 1e229a0fc4f..1e229a0fc4f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Preview.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Preview.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Profile.SystemManufacturers.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Profile.SystemManufacturers.h
index a17e466e639..a17e466e639 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Profile.SystemManufacturers.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Profile.SystemManufacturers.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Profile.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Profile.h
index 8fcd8305c4e..8fcd8305c4e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Profile.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Profile.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.RemoteDesktop.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.RemoteDesktop.h
index e82092679c3..e82092679c3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.RemoteDesktop.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.RemoteDesktop.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.RemoteSystems.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.RemoteSystems.h
index 6ebc8d3b5cd..6ebc8d3b5cd 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.RemoteSystems.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.RemoteSystems.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Threading.Core.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Threading.Core.h
index 89e6cdae8c5..89e6cdae8c5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Threading.Core.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Threading.Core.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Threading.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Threading.h
index 39c6873ed8a..39c6873ed8a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Threading.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Threading.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Update.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Update.h
index 634e43f8970..634e43f8970 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.Update.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.Update.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.UserProfile.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.UserProfile.h
index 0b5d871e290..0b5d871e290 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.UserProfile.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.UserProfile.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.h
index c26638db278..c26638db278 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.System.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.System.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Accessibility.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Accessibility.h
index b6d784bffc7..b6d784bffc7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Accessibility.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Accessibility.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.ApplicationSettings.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.ApplicationSettings.h
index 20664ce7961..20664ce7961 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.ApplicationSettings.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.ApplicationSettings.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Composition.Core.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Composition.Core.h
index 999492ec041..999492ec041 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Composition.Core.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Composition.Core.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Composition.Desktop.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Composition.Desktop.h
index 2d855fa6ed1..2d855fa6ed1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Composition.Desktop.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Composition.Desktop.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Composition.Diagnostics.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Composition.Diagnostics.h
index c69585fe76e..c69585fe76e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Composition.Diagnostics.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Composition.Diagnostics.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Composition.Effects.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Composition.Effects.h
index a355401b748..a355401b748 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Composition.Effects.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Composition.Effects.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Composition.Interactions.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Composition.Interactions.h
index 583a1db2d3d..583a1db2d3d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Composition.Interactions.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Composition.Interactions.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Composition.Scenes.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Composition.Scenes.h
index be9452d392d..be9452d392d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Composition.Scenes.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Composition.Scenes.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Composition.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Composition.h
index 54fc933cc34..54fc933cc34 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Composition.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Composition.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Core.AnimationMetrics.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Core.AnimationMetrics.h
index 7bc83faeb41..7bc83faeb41 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Core.AnimationMetrics.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Core.AnimationMetrics.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Core.Preview.Communications.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Core.Preview.Communications.h
index 3780429bd4e..3780429bd4e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Core.Preview.Communications.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Core.Preview.Communications.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Core.Preview.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Core.Preview.h
index 6b0ff9c0074..6b0ff9c0074 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Core.Preview.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Core.Preview.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Core.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Core.h
index 623dca5e9c7..623dca5e9c7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Core.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Core.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.Core.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.Core.h
index e7e419f5f10..e7e419f5f10 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.Core.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.Core.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.Inking.Analysis.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.Inking.Analysis.h
index d80d2734394..d80d2734394 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.Inking.Analysis.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.Inking.Analysis.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.Inking.Core.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.Inking.Core.h
index d0818b1f37f..d0818b1f37f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.Inking.Core.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.Inking.Core.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.Inking.Preview.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.Inking.Preview.h
index 58c8bf29ce8..58c8bf29ce8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.Inking.Preview.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.Inking.Preview.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.Inking.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.Inking.h
index 3dc19206a9b..3dc19206a9b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.Inking.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.Inking.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.Preview.Injection.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.Preview.Injection.h
index 64b3db5beea..64b3db5beea 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.Preview.Injection.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.Preview.Injection.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.Preview.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.Preview.h
index 75d4eb4b0a3..75d4eb4b0a3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.Preview.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.Preview.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.Spatial.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.Spatial.h
index 42e91a9b9ec..42e91a9b9ec 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.Spatial.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.Spatial.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.h
index 9bf4d3d08ef..9bf4d3d08ef 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Input.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Input.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Notifications.Management.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Notifications.Management.h
index 4f4de6990d4..4f4de6990d4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Notifications.Management.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Notifications.Management.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Notifications.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Notifications.h
index f9b50147eb8..f9b50147eb8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Notifications.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Notifications.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Popups.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Popups.h
index bb59f81ce6b..bb59f81ce6b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Popups.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Popups.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Shell.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Shell.h
index a6fb29afb47..a6fb29afb47 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Shell.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Shell.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.StartScreen.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.StartScreen.h
index 8eab4d28681..8eab4d28681 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.StartScreen.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.StartScreen.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Text.Core.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Text.Core.h
index 210034ef9d0..210034ef9d0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Text.Core.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Text.Core.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Text.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Text.h
index 79a1b787bab..79a1b787bab 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Text.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Text.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.UIAutomation.Core.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.UIAutomation.Core.h
index 110947e9e75..110947e9e75 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.UIAutomation.Core.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.UIAutomation.Core.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.UIAutomation.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.UIAutomation.h
index d0d4436c713..d0d4436c713 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.UIAutomation.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.UIAutomation.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.ViewManagement.Core.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.ViewManagement.Core.h
index 7858f5cd209..7858f5cd209 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.ViewManagement.Core.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.ViewManagement.Core.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.ViewManagement.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.ViewManagement.h
index ea349deb5ac..ea349deb5ac 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.ViewManagement.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.ViewManagement.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.WebUI.Core.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.WebUI.Core.h
index 680c15aecbc..680c15aecbc 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.WebUI.Core.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.WebUI.Core.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.WebUI.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.WebUI.h
index 9384a313bf1..9384a313bf1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.WebUI.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.WebUI.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.WindowManagement.Preview.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.WindowManagement.Preview.h
index 479cefd381c..479cefd381c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.WindowManagement.Preview.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.WindowManagement.Preview.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.WindowManagement.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.WindowManagement.h
index 761fcc56316..761fcc56316 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.WindowManagement.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.WindowManagement.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Automation.Peers.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Automation.Peers.h
index 30e70e76973..30e70e76973 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Automation.Peers.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Automation.Peers.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Automation.Provider.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Automation.Provider.h
index 377f984ac38..377f984ac38 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Automation.Provider.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Automation.Provider.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Automation.Text.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Automation.Text.h
index dd1c60a4630..dd1c60a4630 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Automation.Text.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Automation.Text.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Automation.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Automation.h
index f3dff4e436d..f3dff4e436d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Automation.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Automation.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Controls.Maps.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Controls.Maps.h
index 78c9e44a983..78c9e44a983 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Controls.Maps.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Controls.Maps.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Controls.Primitives.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Controls.Primitives.h
index 7183276e782..7183276e782 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Controls.Primitives.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Controls.Primitives.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Controls.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Controls.h
index 0f84e8f18c3..0f84e8f18c3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Controls.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Controls.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Core.Direct.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Core.Direct.h
index d5dac4d4470..d5dac4d4470 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Core.Direct.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Core.Direct.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Data.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Data.h
index 0726072d210..0726072d210 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Data.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Data.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Documents.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Documents.h
index db2abd404e4..db2abd404e4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Documents.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Documents.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Hosting.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Hosting.h
index 0bb2a36212e..0bb2a36212e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Hosting.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Hosting.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Input.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Input.h
index 09544677859..09544677859 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Input.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Input.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Interop.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Interop.h
index ba6ca4c5ea5..ba6ca4c5ea5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Interop.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Interop.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Markup.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Markup.h
index fb13205902a..fb13205902a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Markup.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Markup.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Media.Animation.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Media.Animation.h
index e7cba2b0561..e7cba2b0561 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Media.Animation.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Media.Animation.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Media.Imaging.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Media.Imaging.h
index 84008d6e0c4..84008d6e0c4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Media.Imaging.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Media.Imaging.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Media.Media3D.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Media.Media3D.h
index 1541395cad7..1541395cad7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Media.Media3D.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Media.Media3D.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Media.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Media.h
index 7164a8f1c08..7164a8f1c08 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Media.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Media.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Navigation.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Navigation.h
index 89561e03e8f..89561e03e8f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Navigation.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Navigation.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Printing.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Printing.h
index afd38a7dacf..afd38a7dacf 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Printing.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Printing.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Resources.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Resources.h
index 41f2d84c63a..41f2d84c63a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Resources.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Resources.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Shapes.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Shapes.h
index 49282c78232..49282c78232 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.Shapes.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.Shapes.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.h
index cd21051e894..cd21051e894 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.Xaml.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.Xaml.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.h
index 67082295bfb..67082295bfb 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.UI.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.UI.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.AtomPub.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.AtomPub.h
index 2cc0e49c507..2cc0e49c507 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.AtomPub.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.AtomPub.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.Http.Diagnostics.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.Http.Diagnostics.h
index 89d69f20ded..89d69f20ded 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.Http.Diagnostics.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.Http.Diagnostics.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.Http.Filters.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.Http.Filters.h
index f5d95941235..f5d95941235 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.Http.Filters.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.Http.Filters.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.Http.Headers.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.Http.Headers.h
index 7c931d3c4cf..7c931d3c4cf 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.Http.Headers.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.Http.Headers.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.Http.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.Http.h
index 50ece6278e9..50ece6278e9 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.Http.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.Http.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.Syndication.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.Syndication.h
index f9bc7219ef5..f9bc7219ef5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.Syndication.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.Syndication.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.UI.Interop.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.UI.Interop.h
index 1f2a40bf90f..1f2a40bf90f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.UI.Interop.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.UI.Interop.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.UI.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.UI.h
index 48e1bc52cf2..48e1bc52cf2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.UI.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.UI.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.h
index 2ade92388e5..2ade92388e5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/Windows.Web.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/Windows.Web.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/base.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/base.h
index 2d1eb4507d2..2d1eb4507d2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/base.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/base.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.AI.MachineLearning.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.AI.MachineLearning.0.h
index 252552fbe4b..252552fbe4b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.AI.MachineLearning.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.AI.MachineLearning.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.AI.MachineLearning.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.AI.MachineLearning.1.h
index b867ed53d59..b867ed53d59 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.AI.MachineLearning.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.AI.MachineLearning.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.AI.MachineLearning.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.AI.MachineLearning.2.h
index 859f8baf9f1..859f8baf9f1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.AI.MachineLearning.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.AI.MachineLearning.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.AI.MachineLearning.Preview.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.AI.MachineLearning.Preview.0.h
index 0d5b97b06d9..0d5b97b06d9 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.AI.MachineLearning.Preview.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.AI.MachineLearning.Preview.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.AI.MachineLearning.Preview.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.AI.MachineLearning.Preview.1.h
index 4894c0facab..4894c0facab 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.AI.MachineLearning.Preview.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.AI.MachineLearning.Preview.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.AI.MachineLearning.Preview.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.AI.MachineLearning.Preview.2.h
index 3b27257549a..3b27257549a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.AI.MachineLearning.Preview.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.AI.MachineLearning.Preview.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.0.h
index 06167009351..06167009351 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.1.h
index 897f809d1a0..897f809d1a0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.2.h
index 0e04d1ea954..0e04d1ea954 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Activation.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Activation.0.h
index 5b13173168e..5b13173168e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Activation.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Activation.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Activation.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Activation.1.h
index 48df8e66012..48df8e66012 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Activation.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Activation.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Activation.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Activation.2.h
index 4aadb004fbb..4aadb004fbb 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Activation.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Activation.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.AppExtensions.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.AppExtensions.0.h
index cd7c71c0fb4..cd7c71c0fb4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.AppExtensions.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.AppExtensions.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.AppExtensions.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.AppExtensions.1.h
index 9e7369c92bd..9e7369c92bd 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.AppExtensions.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.AppExtensions.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.AppExtensions.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.AppExtensions.2.h
index 00264d851b7..00264d851b7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.AppExtensions.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.AppExtensions.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.AppService.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.AppService.0.h
index 3bc8eaff471..3bc8eaff471 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.AppService.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.AppService.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.AppService.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.AppService.1.h
index c98facf8ca1..c98facf8ca1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.AppService.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.AppService.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.AppService.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.AppService.2.h
index ffed0c376e6..ffed0c376e6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.AppService.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.AppService.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.0.h
index 1035b21451d..1035b21451d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.1.h
index b64169bb2c5..b64169bb2c5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.2.h
index a942db8cdff..a942db8cdff 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.AppointmentsProvider.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.AppointmentsProvider.0.h
index 172e170d5f9..172e170d5f9 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.AppointmentsProvider.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.AppointmentsProvider.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.AppointmentsProvider.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.AppointmentsProvider.1.h
index 023ac8eeca7..023ac8eeca7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.AppointmentsProvider.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.AppointmentsProvider.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.AppointmentsProvider.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.AppointmentsProvider.2.h
index 5466f36ac59..5466f36ac59 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.AppointmentsProvider.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.AppointmentsProvider.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.DataProvider.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.DataProvider.0.h
index 3ae6465a79d..3ae6465a79d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.DataProvider.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.DataProvider.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.DataProvider.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.DataProvider.1.h
index e1fa857faac..e1fa857faac 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.DataProvider.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.DataProvider.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.DataProvider.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.DataProvider.2.h
index affce542a6c..affce542a6c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.DataProvider.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Appointments.DataProvider.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Background.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Background.0.h
index 3e3accda296..3e3accda296 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Background.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Background.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Background.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Background.1.h
index d374dfb57dc..d374dfb57dc 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Background.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Background.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Background.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Background.2.h
index b16add87843..b16add87843 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Background.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Background.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.0.h
index 3f103537ec8..3f103537ec8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.1.h
index 12384059a9e..12384059a9e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.2.h
index 32782b9fcb5..32782b9fcb5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Background.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Background.0.h
index a6f041db72e..a6f041db72e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Background.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Background.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Background.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Background.1.h
index 336a2e7d309..336a2e7d309 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Background.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Background.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Background.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Background.2.h
index 9d8fb9abb3e..9d8fb9abb3e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Background.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Background.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Provider.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Provider.0.h
index ea83f07189e..ea83f07189e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Provider.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Provider.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Provider.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Provider.1.h
index 617e5487aea..617e5487aea 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Provider.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Provider.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Provider.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Provider.2.h
index b2fa2a4b14c..b2fa2a4b14c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Provider.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Calls.Provider.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Chat.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Chat.0.h
index 0beaf12c315..0beaf12c315 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Chat.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Chat.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Chat.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Chat.1.h
index 07b7258698f..07b7258698f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Chat.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Chat.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Chat.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Chat.2.h
index 17ba32f1a17..17ba32f1a17 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Chat.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Chat.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.CommunicationBlocking.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.CommunicationBlocking.0.h
index 2e662163a94..2e662163a94 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.CommunicationBlocking.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.CommunicationBlocking.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.CommunicationBlocking.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.CommunicationBlocking.1.h
index f4226659ac6..f4226659ac6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.CommunicationBlocking.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.CommunicationBlocking.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.CommunicationBlocking.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.CommunicationBlocking.2.h
index 01dcd002556..01dcd002556 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.CommunicationBlocking.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.CommunicationBlocking.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.0.h
index 211fbfbf25c..211fbfbf25c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.1.h
index 9ea46646c21..9ea46646c21 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.2.h
index 4c3050382a2..4c3050382a2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.DataProvider.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.DataProvider.0.h
index a15b9fb8ba4..a15b9fb8ba4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.DataProvider.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.DataProvider.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.DataProvider.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.DataProvider.1.h
index b17e000baa2..b17e000baa2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.DataProvider.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.DataProvider.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.DataProvider.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.DataProvider.2.h
index 212242145e2..212242145e2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.DataProvider.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.DataProvider.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.Provider.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.Provider.0.h
index 7f40744b490..7f40744b490 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.Provider.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.Provider.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.Provider.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.Provider.1.h
index 0b040420bbb..0b040420bbb 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.Provider.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.Provider.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.Provider.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.Provider.2.h
index 9787e4782fc..9787e4782fc 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.Provider.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Contacts.Provider.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ConversationalAgent.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ConversationalAgent.0.h
index a602e113f95..a602e113f95 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ConversationalAgent.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ConversationalAgent.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ConversationalAgent.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ConversationalAgent.1.h
index c81bea4f463..c81bea4f463 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ConversationalAgent.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ConversationalAgent.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ConversationalAgent.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ConversationalAgent.2.h
index 0721a3e1e53..0721a3e1e53 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ConversationalAgent.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ConversationalAgent.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Core.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Core.0.h
index 1445c921e23..1445c921e23 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Core.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Core.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Core.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Core.1.h
index 61451bd7a6d..61451bd7a6d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Core.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Core.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Core.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Core.2.h
index fa600a1a0fb..fa600a1a0fb 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Core.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Core.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.0.h
index e1bd4ec471b..e1bd4ec471b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.1.h
index b7d962dda61..b7d962dda61 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.2.h
index 8efe9f05258..8efe9f05258 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.0.h
index e4a06006671..e4a06006671 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.1.h
index 7a797dcdbc5..7a797dcdbc5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.2.h
index ac98e0ca787..ac98e0ca787 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.Core.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.Core.0.h
index 095aa316536..095aa316536 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.Core.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.Core.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.Core.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.Core.1.h
index 04dff2f65ea..04dff2f65ea 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.Core.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.Core.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.Core.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.Core.2.h
index 535a2eebc4f..535a2eebc4f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.Core.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.DragDrop.Core.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.ShareTarget.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.ShareTarget.0.h
index fd6883ad0f8..fd6883ad0f8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.ShareTarget.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.ShareTarget.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.ShareTarget.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.ShareTarget.1.h
index f7c13de5012..f7c13de5012 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.ShareTarget.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.ShareTarget.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.ShareTarget.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.ShareTarget.2.h
index 4ed377591fe..4ed377591fe 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.ShareTarget.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.DataTransfer.ShareTarget.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Email.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Email.0.h
index 6bce33ff5c6..6bce33ff5c6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Email.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Email.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Email.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Email.1.h
index 6c19adbf2f3..6c19adbf2f3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Email.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Email.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Email.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Email.2.h
index eb127bc8663..eb127bc8663 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Email.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Email.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Email.DataProvider.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Email.DataProvider.0.h
index 6104c46e289..6104c46e289 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Email.DataProvider.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Email.DataProvider.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Email.DataProvider.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Email.DataProvider.1.h
index 1b5082093e2..1b5082093e2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Email.DataProvider.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Email.DataProvider.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Email.DataProvider.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Email.DataProvider.2.h
index 10b0432ff38..10b0432ff38 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Email.DataProvider.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Email.DataProvider.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.0.h
index 9ac89465abf..9ac89465abf 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.1.h
index ca4b9357767..ca4b9357767 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.2.h
index c300a36e733..c300a36e733 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.Foreground.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.Foreground.0.h
index 61e4553890f..61e4553890f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.Foreground.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.Foreground.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.Foreground.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.Foreground.1.h
index cae1be94122..cae1be94122 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.Foreground.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.Foreground.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.Foreground.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.Foreground.2.h
index aeb64697206..aeb64697206 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.Foreground.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.ExtendedExecution.Foreground.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Holographic.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Holographic.0.h
index 393f0b610a2..393f0b610a2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Holographic.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Holographic.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Holographic.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Holographic.1.h
index 520a3f7bf35..520a3f7bf35 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Holographic.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Holographic.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Holographic.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Holographic.2.h
index 47d20ebbde2..47d20ebbde2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Holographic.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Holographic.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.LockScreen.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.LockScreen.0.h
index efca615f956..efca615f956 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.LockScreen.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.LockScreen.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.LockScreen.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.LockScreen.1.h
index 1dc5e8628b2..1dc5e8628b2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.LockScreen.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.LockScreen.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.LockScreen.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.LockScreen.2.h
index 1f9cc1f869b..1f9cc1f869b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.LockScreen.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.LockScreen.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.0.h
index 9f86f940a30..9f86f940a30 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.1.h
index cbc531ee3b1..cbc531ee3b1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.2.h
index 2350ac03e15..2350ac03e15 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.Provider.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.Provider.0.h
index 126cebaf2e9..126cebaf2e9 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.Provider.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.Provider.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.Provider.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.Provider.1.h
index b9bdb5479cb..b9bdb5479cb 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.Provider.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.Provider.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.Provider.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.Provider.2.h
index ef718464779..ef718464779 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.Provider.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Payments.Provider.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Holographic.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Holographic.0.h
index dbc4c81bfd5..dbc4c81bfd5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Holographic.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Holographic.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Holographic.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Holographic.1.h
index 8ea1ac7b038..8ea1ac7b038 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Holographic.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Holographic.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Holographic.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Holographic.2.h
index 7074065b742..7074065b742 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Holographic.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Holographic.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.InkWorkspace.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.InkWorkspace.0.h
index e1673425b30..e1673425b30 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.InkWorkspace.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.InkWorkspace.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.InkWorkspace.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.InkWorkspace.1.h
index 033fa08c92c..033fa08c92c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.InkWorkspace.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.InkWorkspace.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.InkWorkspace.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.InkWorkspace.2.h
index c3ca44c0e90..c3ca44c0e90 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.InkWorkspace.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.InkWorkspace.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Notes.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Notes.0.h
index bc5b87c148e..bc5b87c148e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Notes.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Notes.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Notes.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Notes.1.h
index ae6aa718111..ae6aa718111 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Notes.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Notes.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Notes.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Notes.2.h
index 7a466c5f9ef..7a466c5f9ef 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Notes.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Preview.Notes.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.0.h
index 96c11ac029b..96c11ac029b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.1.h
index 711f621d190..711f621d190 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.2.h
index 4923db14a16..4923db14a16 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Core.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Core.0.h
index 368ae26b63f..368ae26b63f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Core.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Core.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Core.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Core.1.h
index 7b50e22aa46..7b50e22aa46 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Core.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Core.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Core.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Core.2.h
index 41b5388d0eb..41b5388d0eb 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Core.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Core.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Management.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Management.0.h
index 61d4563ed24..61d4563ed24 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Management.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Management.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Management.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Management.1.h
index 6ba401cc8bc..6ba401cc8bc 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Management.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Management.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Management.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Management.2.h
index 531c7c93ecc..531c7c93ecc 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Management.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Resources.Management.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Search.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Search.0.h
index b39b6f544aa..b39b6f544aa 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Search.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Search.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Search.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Search.1.h
index cbf1828c412..cbf1828c412 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Search.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Search.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Search.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Search.2.h
index 93cd5f488a3..93cd5f488a3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Search.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Search.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Search.Core.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Search.Core.0.h
index b55a81dcff0..b55a81dcff0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Search.Core.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Search.Core.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Search.Core.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Search.Core.1.h
index 2b94d37772b..2b94d37772b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Search.Core.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Search.Core.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Search.Core.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Search.Core.2.h
index 93c6b709f7d..93c6b709f7d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Search.Core.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Search.Core.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.0.h
index 94835f0e8ca..94835f0e8ca 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.1.h
index 0696f83b10d..0696f83b10d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.2.h
index 316a3951d8b..316a3951d8b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.Provider.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.Provider.0.h
index bdbabfa3188..bdbabfa3188 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.Provider.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.Provider.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.Provider.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.Provider.1.h
index 1b9b7bf8ce8..1b9b7bf8ce8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.Provider.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.Provider.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.Provider.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.Provider.2.h
index 2d214b09e46..2d214b09e46 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.Provider.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.SocialInfo.Provider.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.0.h
index 583f62ed860..583f62ed860 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.1.h
index 14ac67c677d..14ac67c677d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.2.h
index 4cf45d5bb34..4cf45d5bb34 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.LicenseManagement.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.LicenseManagement.0.h
index d7dcd5fd149..d7dcd5fd149 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.LicenseManagement.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.LicenseManagement.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.LicenseManagement.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.LicenseManagement.1.h
index 656f8a80a4c..656f8a80a4c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.LicenseManagement.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.LicenseManagement.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.LicenseManagement.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.LicenseManagement.2.h
index 652973572d1..652973572d1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.LicenseManagement.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.LicenseManagement.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.0.h
index 7f75aa246e4..7f75aa246e4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.1.h
index 98eacafbacd..98eacafbacd 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.2.h
index 4265a8cee9d..4265a8cee9d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.InstallControl.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.InstallControl.0.h
index b9a4f1aae99..b9a4f1aae99 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.InstallControl.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.InstallControl.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.InstallControl.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.InstallControl.1.h
index 294156d57c0..294156d57c0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.InstallControl.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.InstallControl.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.InstallControl.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.InstallControl.2.h
index 3992435175b..3992435175b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.InstallControl.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Store.Preview.InstallControl.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.0.h
index 8ce5baf0672..8ce5baf0672 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.1.h
index f9c333fa55c..f9c333fa55c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.2.h
index 162513071f1..162513071f1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.Core.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.Core.0.h
index 283d2b23e3a..283d2b23e3a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.Core.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.Core.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.Core.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.Core.1.h
index 341c89384ef..341c89384ef 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.Core.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.Core.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.Core.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.Core.2.h
index e168a5d1eda..e168a5d1eda 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.Core.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserActivities.Core.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.0.h
index e0c5c272f01..e0c5c272f01 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.1.h
index f7a14f7d360..f7a14f7d360 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.2.h
index 9009dbdbcdd..9009dbdbcdd 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.Provider.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.Provider.0.h
index 689c93340bf..689c93340bf 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.Provider.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.Provider.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.Provider.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.Provider.1.h
index d07ac46276e..d07ac46276e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.Provider.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.Provider.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.Provider.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.Provider.2.h
index 9c97ef89426..9c97ef89426 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.Provider.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.Provider.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.SystemAccess.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.SystemAccess.0.h
index fa312eb8b11..fa312eb8b11 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.SystemAccess.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.SystemAccess.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.SystemAccess.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.SystemAccess.1.h
index dc53a104e05..dc53a104e05 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.SystemAccess.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.SystemAccess.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.SystemAccess.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.SystemAccess.2.h
index 99adfda99f2..99adfda99f2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.SystemAccess.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataAccounts.SystemAccess.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.0.h
index 6719adabfee..6719adabfee 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.1.h
index 489672df866..489672df866 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.2.h
index 83a616975a2..83a616975a2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.DataProvider.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.DataProvider.0.h
index 357823ac49e..357823ac49e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.DataProvider.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.DataProvider.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.DataProvider.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.DataProvider.1.h
index bf2d76958fe..bf2d76958fe 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.DataProvider.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.DataProvider.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.DataProvider.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.DataProvider.2.h
index 8d12011532c..8d12011532c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.DataProvider.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.UserDataTasks.DataProvider.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.VoiceCommands.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.VoiceCommands.0.h
index 774125a4a65..774125a4a65 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.VoiceCommands.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.VoiceCommands.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.VoiceCommands.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.VoiceCommands.1.h
index b483a20055b..b483a20055b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.VoiceCommands.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.VoiceCommands.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.VoiceCommands.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.VoiceCommands.2.h
index 5c5a024ba22..5c5a024ba22 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.VoiceCommands.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.VoiceCommands.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.0.h
index f578aa7d7b4..f578aa7d7b4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.1.h
index ef861c35e77..ef861c35e77 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.2.h
index e41101b27ea..e41101b27ea 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.System.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.System.0.h
index 23d49e1c70b..23d49e1c70b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.System.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.System.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.System.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.System.1.h
index 7abfe4cdfaa..7abfe4cdfaa 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.System.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.System.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.System.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.System.2.h
index d516351e1b0..d516351e1b0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.System.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.ApplicationModel.Wallet.System.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Html.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Html.0.h
index 705f36295dc..705f36295dc 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Html.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Html.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Html.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Html.1.h
index 37d3b795804..37d3b795804 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Html.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Html.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Html.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Html.2.h
index 68d0829a6d7..68d0829a6d7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Html.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Html.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Json.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Json.0.h
index 0fdab2c59f6..0fdab2c59f6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Json.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Json.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Json.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Json.1.h
index 69037ec497c..69037ec497c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Json.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Json.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Json.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Json.2.h
index 78314d6b50e..78314d6b50e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Json.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Json.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Pdf.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Pdf.0.h
index 92fde42970d..92fde42970d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Pdf.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Pdf.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Pdf.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Pdf.1.h
index 8a268bb97b4..8a268bb97b4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Pdf.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Pdf.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Pdf.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Pdf.2.h
index f658c899512..f658c899512 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Pdf.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Pdf.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Text.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Text.0.h
index b9537df7007..b9537df7007 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Text.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Text.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Text.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Text.1.h
index 63b8edb18f6..63b8edb18f6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Text.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Text.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Text.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Text.2.h
index e5948466791..e5948466791 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Text.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Text.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Xml.Dom.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Xml.Dom.0.h
index 1b8b9a4d54a..1b8b9a4d54a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Xml.Dom.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Xml.Dom.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Xml.Dom.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Xml.Dom.1.h
index 905076fe134..905076fe134 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Xml.Dom.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Xml.Dom.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Xml.Dom.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Xml.Dom.2.h
index aff2912092d..aff2912092d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Xml.Dom.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Xml.Dom.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Xml.Xsl.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Xml.Xsl.0.h
index 7c67d8c2cbf..7c67d8c2cbf 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Xml.Xsl.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Xml.Xsl.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Xml.Xsl.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Xml.Xsl.1.h
index 786e645789a..786e645789a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Xml.Xsl.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Xml.Xsl.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Xml.Xsl.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Xml.Xsl.2.h
index d29c0e8604f..d29c0e8604f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Xml.Xsl.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Data.Xml.Xsl.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.0.h
index a1d81d7dfe1..a1d81d7dfe1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.1.h
index 8099f2201c5..8099f2201c5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.2.h
index 2143f199d0e..2143f199d0e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Adc.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Adc.0.h
index e7bbeb27730..e7bbeb27730 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Adc.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Adc.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Adc.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Adc.1.h
index fc7c5737dfd..fc7c5737dfd 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Adc.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Adc.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Adc.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Adc.2.h
index 3e129a9303c..3e129a9303c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Adc.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Adc.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Adc.Provider.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Adc.Provider.0.h
index e6e88089f8c..e6e88089f8c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Adc.Provider.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Adc.Provider.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Adc.Provider.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Adc.Provider.1.h
index 7779f741c45..7779f741c45 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Adc.Provider.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Adc.Provider.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Adc.Provider.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Adc.Provider.2.h
index c4ff28a4c2f..c4ff28a4c2f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Adc.Provider.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Adc.Provider.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.AllJoyn.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.AllJoyn.0.h
index 036ff058546..036ff058546 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.AllJoyn.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.AllJoyn.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.AllJoyn.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.AllJoyn.1.h
index a24f182e41f..a24f182e41f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.AllJoyn.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.AllJoyn.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.AllJoyn.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.AllJoyn.2.h
index a445ceea572..a445ceea572 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.AllJoyn.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.AllJoyn.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Background.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Background.0.h
index 39c7737a170..39c7737a170 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Background.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Background.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Background.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Background.1.h
index 6e70789d2c4..6e70789d2c4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Background.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Background.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Background.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Background.2.h
index ea47d81ca94..ea47d81ca94 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Background.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Background.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.0.h
index 606d9a54356..606d9a54356 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.1.h
index 47c9d61f05c..47c9d61f05c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.2.h
index 835b0f05a55..835b0f05a55 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Advertisement.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Advertisement.0.h
index a585bdc65ee..a585bdc65ee 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Advertisement.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Advertisement.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Advertisement.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Advertisement.1.h
index 92ac542c4e8..92ac542c4e8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Advertisement.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Advertisement.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Advertisement.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Advertisement.2.h
index 3875ae24cd3..3875ae24cd3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Advertisement.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Advertisement.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Background.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Background.0.h
index 50a4e30de61..50a4e30de61 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Background.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Background.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Background.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Background.1.h
index 0f367f40f29..0f367f40f29 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Background.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Background.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Background.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Background.2.h
index af042cf3cf9..af042cf3cf9 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Background.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Background.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.GenericAttributeProfile.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.GenericAttributeProfile.0.h
index 3d173abde0c..3d173abde0c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.GenericAttributeProfile.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.GenericAttributeProfile.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.GenericAttributeProfile.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.GenericAttributeProfile.1.h
index 7f936b16cd0..7f936b16cd0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.GenericAttributeProfile.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.GenericAttributeProfile.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.GenericAttributeProfile.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.GenericAttributeProfile.2.h
index e58af689a7d..e58af689a7d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.GenericAttributeProfile.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.GenericAttributeProfile.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Rfcomm.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Rfcomm.0.h
index b3343085a96..b3343085a96 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Rfcomm.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Rfcomm.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Rfcomm.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Rfcomm.1.h
index 5a9d99617c3..5a9d99617c3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Rfcomm.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Rfcomm.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Rfcomm.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Rfcomm.2.h
index 102665da740..102665da740 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Rfcomm.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Bluetooth.Rfcomm.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Custom.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Custom.0.h
index ec6c988ae4d..ec6c988ae4d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Custom.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Custom.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Custom.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Custom.1.h
index 304b075a6ba..304b075a6ba 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Custom.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Custom.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Custom.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Custom.2.h
index 58a8fd50e79..58a8fd50e79 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Custom.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Custom.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Display.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Display.0.h
index 3e8eabc4004..3e8eabc4004 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Display.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Display.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Display.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Display.1.h
index 31ae470b257..31ae470b257 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Display.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Display.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Display.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Display.2.h
index 3e1fa2363d3..3e1fa2363d3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Display.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Display.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Display.Core.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Display.Core.0.h
index fc7768ad8c6..fc7768ad8c6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Display.Core.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Display.Core.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Display.Core.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Display.Core.1.h
index 0c3e0c834be..0c3e0c834be 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Display.Core.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Display.Core.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Display.Core.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Display.Core.2.h
index b1e3b3c5e00..b1e3b3c5e00 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Display.Core.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Display.Core.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Enumeration.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Enumeration.0.h
index 4afba783b94..4afba783b94 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Enumeration.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Enumeration.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Enumeration.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Enumeration.1.h
index 446c8681ab4..446c8681ab4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Enumeration.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Enumeration.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Enumeration.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Enumeration.2.h
index cb380a0140f..cb380a0140f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Enumeration.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Enumeration.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Enumeration.Pnp.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Enumeration.Pnp.0.h
index a9ec6f4dd35..a9ec6f4dd35 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Enumeration.Pnp.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Enumeration.Pnp.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Enumeration.Pnp.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Enumeration.Pnp.1.h
index 623f3e4a311..623f3e4a311 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Enumeration.Pnp.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Enumeration.Pnp.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Enumeration.Pnp.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Enumeration.Pnp.2.h
index 650c60d74af..650c60d74af 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Enumeration.Pnp.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Enumeration.Pnp.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Geolocation.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Geolocation.0.h
index fe2ab7610cc..fe2ab7610cc 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Geolocation.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Geolocation.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Geolocation.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Geolocation.1.h
index 01bcc8beaef..01bcc8beaef 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Geolocation.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Geolocation.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Geolocation.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Geolocation.2.h
index cb43c7c88c1..cb43c7c88c1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Geolocation.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Geolocation.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Geolocation.Geofencing.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Geolocation.Geofencing.0.h
index 02f29353e88..02f29353e88 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Geolocation.Geofencing.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Geolocation.Geofencing.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Geolocation.Geofencing.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Geolocation.Geofencing.1.h
index fbf4d709d33..fbf4d709d33 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Geolocation.Geofencing.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Geolocation.Geofencing.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Geolocation.Geofencing.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Geolocation.Geofencing.2.h
index d1697abac0b..d1697abac0b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Geolocation.Geofencing.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Geolocation.Geofencing.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Gpio.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Gpio.0.h
index 0878cac8ff6..0878cac8ff6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Gpio.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Gpio.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Gpio.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Gpio.1.h
index c62d9c79b61..c62d9c79b61 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Gpio.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Gpio.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Gpio.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Gpio.2.h
index 1e0f9097639..1e0f9097639 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Gpio.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Gpio.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Gpio.Provider.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Gpio.Provider.0.h
index c85de80b8ef..c85de80b8ef 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Gpio.Provider.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Gpio.Provider.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Gpio.Provider.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Gpio.Provider.1.h
index 4b60be08318..4b60be08318 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Gpio.Provider.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Gpio.Provider.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Gpio.Provider.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Gpio.Provider.2.h
index 850c83f8c42..850c83f8c42 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Gpio.Provider.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Gpio.Provider.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Haptics.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Haptics.0.h
index 92411865c60..92411865c60 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Haptics.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Haptics.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Haptics.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Haptics.1.h
index afcfbb3d226..afcfbb3d226 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Haptics.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Haptics.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Haptics.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Haptics.2.h
index 25efc314d5c..25efc314d5c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Haptics.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Haptics.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.HumanInterfaceDevice.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.HumanInterfaceDevice.0.h
index 0ed5e40199f..0ed5e40199f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.HumanInterfaceDevice.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.HumanInterfaceDevice.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.HumanInterfaceDevice.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.HumanInterfaceDevice.1.h
index 6a6245b6c68..6a6245b6c68 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.HumanInterfaceDevice.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.HumanInterfaceDevice.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.HumanInterfaceDevice.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.HumanInterfaceDevice.2.h
index 05cdf29ffb6..05cdf29ffb6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.HumanInterfaceDevice.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.HumanInterfaceDevice.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.I2c.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.I2c.0.h
index 8459c632abe..8459c632abe 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.I2c.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.I2c.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.I2c.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.I2c.1.h
index 3e4adb658d7..3e4adb658d7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.I2c.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.I2c.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.I2c.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.I2c.2.h
index 03b5bb790ea..03b5bb790ea 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.I2c.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.I2c.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.I2c.Provider.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.I2c.Provider.0.h
index d6d52cd62b2..d6d52cd62b2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.I2c.Provider.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.I2c.Provider.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.I2c.Provider.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.I2c.Provider.1.h
index 0bcd90303a8..0bcd90303a8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.I2c.Provider.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.I2c.Provider.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.I2c.Provider.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.I2c.Provider.2.h
index e5ede00df40..e5ede00df40 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.I2c.Provider.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.I2c.Provider.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Input.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Input.0.h
index 9d930cf1199..9d930cf1199 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Input.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Input.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Input.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Input.1.h
index 5f1fa18873e..5f1fa18873e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Input.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Input.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Input.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Input.2.h
index b3e27284f88..b3e27284f88 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Input.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Input.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Input.Preview.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Input.Preview.0.h
index e0d0a3308d7..e0d0a3308d7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Input.Preview.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Input.Preview.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Input.Preview.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Input.Preview.1.h
index 2b7199cd635..2b7199cd635 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Input.Preview.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Input.Preview.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Input.Preview.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Input.Preview.2.h
index f35f9ecdf93..f35f9ecdf93 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Input.Preview.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Input.Preview.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Lights.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Lights.0.h
index 2f974cd367b..2f974cd367b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Lights.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Lights.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Lights.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Lights.1.h
index 5aee5ecebef..5aee5ecebef 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Lights.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Lights.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Lights.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Lights.2.h
index 42fa35b5ac9..42fa35b5ac9 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Lights.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Lights.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Lights.Effects.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Lights.Effects.0.h
index e5c09d9703b..e5c09d9703b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Lights.Effects.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Lights.Effects.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Lights.Effects.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Lights.Effects.1.h
index 674970d23c5..674970d23c5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Lights.Effects.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Lights.Effects.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Lights.Effects.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Lights.Effects.2.h
index b12f76f027a..b12f76f027a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Lights.Effects.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Lights.Effects.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Midi.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Midi.0.h
index 490f868ed23..490f868ed23 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Midi.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Midi.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Midi.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Midi.1.h
index a963b55e21c..a963b55e21c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Midi.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Midi.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Midi.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Midi.2.h
index df20bd75fc7..df20bd75fc7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Midi.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Midi.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Perception.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Perception.0.h
index 7a34a35352d..7a34a35352d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Perception.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Perception.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Perception.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Perception.1.h
index f9adb35f76f..f9adb35f76f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Perception.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Perception.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Perception.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Perception.2.h
index 657e114a95d..657e114a95d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Perception.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Perception.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Perception.Provider.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Perception.Provider.0.h
index 479df09a493..479df09a493 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Perception.Provider.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Perception.Provider.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Perception.Provider.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Perception.Provider.1.h
index 0215a763b92..0215a763b92 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Perception.Provider.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Perception.Provider.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Perception.Provider.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Perception.Provider.2.h
index 3a7da8d4dff..3a7da8d4dff 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Perception.Provider.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Perception.Provider.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.PointOfService.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.PointOfService.0.h
index 88020429e3d..88020429e3d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.PointOfService.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.PointOfService.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.PointOfService.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.PointOfService.1.h
index e72905ad994..e72905ad994 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.PointOfService.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.PointOfService.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.PointOfService.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.PointOfService.2.h
index 034b25cee05..034b25cee05 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.PointOfService.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.PointOfService.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.PointOfService.Provider.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.PointOfService.Provider.0.h
index ba5f2b08c1f..ba5f2b08c1f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.PointOfService.Provider.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.PointOfService.Provider.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.PointOfService.Provider.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.PointOfService.Provider.1.h
index 0c52b8c375a..0c52b8c375a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.PointOfService.Provider.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.PointOfService.Provider.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.PointOfService.Provider.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.PointOfService.Provider.2.h
index 875215b9df5..875215b9df5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.PointOfService.Provider.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.PointOfService.Provider.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Portable.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Portable.0.h
index f47351b3e50..f47351b3e50 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Portable.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Portable.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Portable.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Portable.1.h
index 5eaf1b5727c..5eaf1b5727c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Portable.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Portable.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Portable.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Portable.2.h
index 8859a72b43a..8859a72b43a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Portable.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Portable.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Power.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Power.0.h
index ad31ee1f78d..ad31ee1f78d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Power.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Power.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Power.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Power.1.h
index eca1cd521ea..eca1cd521ea 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Power.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Power.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Power.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Power.2.h
index 54b2d9e4f0d..54b2d9e4f0d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Power.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Power.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Printers.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Printers.0.h
index 7f02e5ade61..7f02e5ade61 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Printers.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Printers.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Printers.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Printers.1.h
index 69dc643cc09..69dc643cc09 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Printers.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Printers.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Printers.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Printers.2.h
index 52c21c4edc9..52c21c4edc9 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Printers.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Printers.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Printers.Extensions.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Printers.Extensions.0.h
index 5b819513ead..5b819513ead 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Printers.Extensions.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Printers.Extensions.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Printers.Extensions.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Printers.Extensions.1.h
index db758bda36f..db758bda36f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Printers.Extensions.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Printers.Extensions.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Printers.Extensions.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Printers.Extensions.2.h
index e8c715cd3dc..e8c715cd3dc 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Printers.Extensions.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Printers.Extensions.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Pwm.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Pwm.0.h
index 582688b4d6a..582688b4d6a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Pwm.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Pwm.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Pwm.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Pwm.1.h
index 3c16d03c4d1..3c16d03c4d1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Pwm.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Pwm.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Pwm.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Pwm.2.h
index 883b01aa83c..883b01aa83c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Pwm.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Pwm.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Pwm.Provider.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Pwm.Provider.0.h
index 7c437174119..7c437174119 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Pwm.Provider.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Pwm.Provider.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Pwm.Provider.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Pwm.Provider.1.h
index df4523574f7..df4523574f7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Pwm.Provider.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Pwm.Provider.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Pwm.Provider.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Pwm.Provider.2.h
index 2cdb5d6f812..2cdb5d6f812 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Pwm.Provider.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Pwm.Provider.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Radios.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Radios.0.h
index 0254f72314d..0254f72314d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Radios.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Radios.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Radios.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Radios.1.h
index 1c5636b454a..1c5636b454a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Radios.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Radios.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Radios.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Radios.2.h
index 9d9621c9750..9d9621c9750 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Radios.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Radios.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Scanners.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Scanners.0.h
index 5579e13cab5..5579e13cab5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Scanners.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Scanners.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Scanners.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Scanners.1.h
index 121babedee0..121babedee0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Scanners.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Scanners.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Scanners.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Scanners.2.h
index cb7de48a0d0..cb7de48a0d0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Scanners.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Scanners.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sensors.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sensors.0.h
index de133425b04..de133425b04 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sensors.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sensors.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sensors.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sensors.1.h
index c2cbe86d027..c2cbe86d027 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sensors.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sensors.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sensors.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sensors.2.h
index 81b426761f8..81b426761f8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sensors.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sensors.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sensors.Custom.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sensors.Custom.0.h
index 68568ae2898..68568ae2898 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sensors.Custom.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sensors.Custom.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sensors.Custom.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sensors.Custom.1.h
index 48516e3b4e3..48516e3b4e3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sensors.Custom.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sensors.Custom.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sensors.Custom.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sensors.Custom.2.h
index e21bbdc3dd2..e21bbdc3dd2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sensors.Custom.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sensors.Custom.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.SerialCommunication.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.SerialCommunication.0.h
index 6d77a1e3d30..6d77a1e3d30 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.SerialCommunication.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.SerialCommunication.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.SerialCommunication.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.SerialCommunication.1.h
index 1b0139a34b1..1b0139a34b1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.SerialCommunication.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.SerialCommunication.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.SerialCommunication.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.SerialCommunication.2.h
index ad6bbca7ce1..ad6bbca7ce1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.SerialCommunication.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.SerialCommunication.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.SmartCards.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.SmartCards.0.h
index 4deb061a86a..4deb061a86a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.SmartCards.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.SmartCards.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.SmartCards.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.SmartCards.1.h
index bb0924208dd..bb0924208dd 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.SmartCards.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.SmartCards.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.SmartCards.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.SmartCards.2.h
index 774a1f8cd87..774a1f8cd87 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.SmartCards.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.SmartCards.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sms.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sms.0.h
index 5f98d4b01b7..5f98d4b01b7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sms.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sms.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sms.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sms.1.h
index 489297935f8..489297935f8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sms.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sms.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sms.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sms.2.h
index 11b8bed010c..11b8bed010c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Sms.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Sms.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Spi.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Spi.0.h
index b6612c4aae4..b6612c4aae4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Spi.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Spi.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Spi.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Spi.1.h
index 4d9e115a1fc..4d9e115a1fc 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Spi.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Spi.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Spi.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Spi.2.h
index cc150bb394c..cc150bb394c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Spi.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Spi.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Spi.Provider.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Spi.Provider.0.h
index 3531c4ab113..3531c4ab113 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Spi.Provider.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Spi.Provider.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Spi.Provider.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Spi.Provider.1.h
index f0eee27f22b..f0eee27f22b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Spi.Provider.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Spi.Provider.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Spi.Provider.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Spi.Provider.2.h
index 54101d3f30b..54101d3f30b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Spi.Provider.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Spi.Provider.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Usb.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Usb.0.h
index 6b611046be1..6b611046be1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Usb.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Usb.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Usb.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Usb.1.h
index 832cdad9101..832cdad9101 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Usb.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Usb.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Usb.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Usb.2.h
index 59fb39e0a01..59fb39e0a01 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.Usb.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Usb.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFi.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFi.0.h
index c7c51fd369d..c7c51fd369d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFi.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFi.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFi.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFi.1.h
index c7fdf3e80d1..c7fdf3e80d1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFi.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFi.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFi.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFi.2.h
index 4bebbae3828..4bebbae3828 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFi.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFi.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.0.h
index c4550ae78ca..c4550ae78ca 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.1.h
index 525b6ff1dc8..525b6ff1dc8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.2.h
index e864589a326..e864589a326 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.Services.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.Services.0.h
index c618c49e580..c618c49e580 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.Services.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.Services.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.Services.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.Services.1.h
index 9466502a8a6..9466502a8a6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.Services.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.Services.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.Services.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.Services.2.h
index 802c58caced..802c58caced 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.Services.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.WiFiDirect.Services.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Embedded.DeviceLockdown.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Embedded.DeviceLockdown.0.h
index 72c9c5b56a0..72c9c5b56a0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Embedded.DeviceLockdown.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Embedded.DeviceLockdown.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Embedded.DeviceLockdown.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Embedded.DeviceLockdown.1.h
index d81d0c8fed2..d81d0c8fed2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Embedded.DeviceLockdown.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Embedded.DeviceLockdown.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Embedded.DeviceLockdown.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Embedded.DeviceLockdown.2.h
index 66348771435..66348771435 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Embedded.DeviceLockdown.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Embedded.DeviceLockdown.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.0.h
index 5f6e306dc27..5f6e306dc27 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.1.h
index 0a4fb70b813..0a4fb70b813 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.2.h
index 8bf37e00e7d..8bf37e00e7d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Collections.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Collections.0.h
index e163296f0f4..e163296f0f4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Collections.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Collections.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Collections.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Collections.1.h
index 864a002385c..864a002385c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Collections.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Collections.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Collections.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Collections.2.h
index 44a621a68ba..44a621a68ba 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Collections.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Collections.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Diagnostics.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Diagnostics.0.h
index 4ff53fa8832..4ff53fa8832 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Diagnostics.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Diagnostics.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Diagnostics.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Diagnostics.1.h
index 2554b574b8b..2554b574b8b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Diagnostics.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Diagnostics.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Diagnostics.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Diagnostics.2.h
index ad742491865..ad742491865 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Diagnostics.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Diagnostics.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Metadata.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Metadata.0.h
index 126eb81649d..126eb81649d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Metadata.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Metadata.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Metadata.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Metadata.1.h
index 5c2510ab14b..5c2510ab14b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Metadata.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Metadata.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Metadata.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Metadata.2.h
index 0e894898e17..0e894898e17 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Metadata.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Metadata.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Numerics.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Numerics.0.h
index c688c60eca0..c688c60eca0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Numerics.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Numerics.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Numerics.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Numerics.1.h
index 082a27d4f65..082a27d4f65 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Numerics.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Numerics.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Numerics.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Numerics.2.h
index c2714ffce5d..c2714ffce5d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Foundation.Numerics.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Foundation.Numerics.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.0.h
index 5d28f2fb894..5d28f2fb894 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.1.h
index 083439a838d..083439a838d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.2.h
index f790d0779eb..f790d0779eb 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.Custom.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.Custom.0.h
index 2cb643637cf..2cb643637cf 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.Custom.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.Custom.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.Custom.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.Custom.1.h
index 8f89382cf1e..8f89382cf1e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.Custom.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.Custom.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.Custom.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.Custom.2.h
index 4b6a6053ba7..4b6a6053ba7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.Custom.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.Custom.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.ForceFeedback.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.ForceFeedback.0.h
index 1ecb31d6cc9..1ecb31d6cc9 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.ForceFeedback.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.ForceFeedback.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.ForceFeedback.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.ForceFeedback.1.h
index 824b52763f5..824b52763f5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.ForceFeedback.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.ForceFeedback.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.ForceFeedback.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.ForceFeedback.2.h
index ba8e8f23bd7..ba8e8f23bd7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.ForceFeedback.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.ForceFeedback.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.Preview.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.Preview.0.h
index 31cf4a94860..31cf4a94860 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.Preview.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.Preview.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.Preview.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.Preview.1.h
index 52ddfe91fdf..52ddfe91fdf 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.Preview.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.Preview.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.Preview.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.Preview.2.h
index fda686a1d80..fda686a1d80 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Input.Preview.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Input.Preview.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Preview.GamesEnumeration.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Preview.GamesEnumeration.0.h
index bb7eedf72b1..bb7eedf72b1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Preview.GamesEnumeration.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Preview.GamesEnumeration.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Preview.GamesEnumeration.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Preview.GamesEnumeration.1.h
index 9b43b76c291..9b43b76c291 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Preview.GamesEnumeration.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Preview.GamesEnumeration.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Preview.GamesEnumeration.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Preview.GamesEnumeration.2.h
index c6c2a0ba29f..c6c2a0ba29f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.Preview.GamesEnumeration.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.Preview.GamesEnumeration.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.UI.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.UI.0.h
index 72eb667e94e..72eb667e94e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.UI.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.UI.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.UI.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.UI.1.h
index e1d01259087..e1d01259087 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.UI.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.UI.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.UI.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.UI.2.h
index d677586ea9f..d677586ea9f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.UI.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.UI.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.XboxLive.Storage.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.XboxLive.Storage.0.h
index 06a49b184a4..06a49b184a4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.XboxLive.Storage.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.XboxLive.Storage.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.XboxLive.Storage.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.XboxLive.Storage.1.h
index 8be2fd7fe62..8be2fd7fe62 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.XboxLive.Storage.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.XboxLive.Storage.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.XboxLive.Storage.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.XboxLive.Storage.2.h
index c110c2cf135..c110c2cf135 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Gaming.XboxLive.Storage.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Gaming.XboxLive.Storage.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.0.h
index b8d08d72822..b8d08d72822 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.1.h
index 52ec3194850..52ec3194850 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.2.h
index 19bbf782c36..19bbf782c36 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.Collation.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.Collation.0.h
index a42a39b7bbb..a42a39b7bbb 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.Collation.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.Collation.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.Collation.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.Collation.1.h
index 6691d76051b..6691d76051b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.Collation.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.Collation.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.Collation.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.Collation.2.h
index df803dcd3cf..df803dcd3cf 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.Collation.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.Collation.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.DateTimeFormatting.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.DateTimeFormatting.0.h
index 2ef26ca3417..2ef26ca3417 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.DateTimeFormatting.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.DateTimeFormatting.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.DateTimeFormatting.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.DateTimeFormatting.1.h
index 3c50228654a..3c50228654a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.DateTimeFormatting.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.DateTimeFormatting.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.DateTimeFormatting.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.DateTimeFormatting.2.h
index cf85088d028..cf85088d028 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.DateTimeFormatting.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.DateTimeFormatting.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.Fonts.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.Fonts.0.h
index d66241d0bf6..d66241d0bf6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.Fonts.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.Fonts.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.Fonts.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.Fonts.1.h
index 3b7ad6934ad..3b7ad6934ad 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.Fonts.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.Fonts.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.Fonts.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.Fonts.2.h
index 3d202138017..3d202138017 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.Fonts.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.Fonts.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.NumberFormatting.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.NumberFormatting.0.h
index d52a9c5033d..d52a9c5033d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.NumberFormatting.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.NumberFormatting.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.NumberFormatting.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.NumberFormatting.1.h
index 648510ab302..648510ab302 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.NumberFormatting.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.NumberFormatting.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.NumberFormatting.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.NumberFormatting.2.h
index fa150176a12..fa150176a12 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.NumberFormatting.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.NumberFormatting.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.PhoneNumberFormatting.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.PhoneNumberFormatting.0.h
index e837866f729..e837866f729 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.PhoneNumberFormatting.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.PhoneNumberFormatting.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.PhoneNumberFormatting.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.PhoneNumberFormatting.1.h
index 7d707816f95..7d707816f95 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.PhoneNumberFormatting.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.PhoneNumberFormatting.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.PhoneNumberFormatting.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.PhoneNumberFormatting.2.h
index 96dbd75470b..96dbd75470b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Globalization.PhoneNumberFormatting.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Globalization.PhoneNumberFormatting.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.0.h
index bbd10c5f600..bbd10c5f600 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.1.h
index 1a3d16aebf8..1a3d16aebf8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.2.h
index 9033fdb22e8..9033fdb22e8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Capture.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Capture.0.h
index 64361d57d91..64361d57d91 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Capture.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Capture.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Capture.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Capture.1.h
index 87c4cbede7c..87c4cbede7c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Capture.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Capture.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Capture.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Capture.2.h
index 5adc964f66c..5adc964f66c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Capture.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Capture.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.DirectX.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.DirectX.0.h
index d917ab6dd5a..d917ab6dd5a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.DirectX.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.DirectX.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.DirectX.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.DirectX.1.h
index d73d917a91d..d73d917a91d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.DirectX.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.DirectX.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.DirectX.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.DirectX.2.h
index dfdaa1caced..dfdaa1caced 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.DirectX.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.DirectX.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.DirectX.Direct3D11.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.DirectX.Direct3D11.0.h
index 12968d9b733..12968d9b733 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.DirectX.Direct3D11.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.DirectX.Direct3D11.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.DirectX.Direct3D11.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.DirectX.Direct3D11.1.h
index a17b9223fda..a17b9223fda 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.DirectX.Direct3D11.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.DirectX.Direct3D11.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.DirectX.Direct3D11.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.DirectX.Direct3D11.2.h
index 74d868c0099..74d868c0099 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.DirectX.Direct3D11.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.DirectX.Direct3D11.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Display.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Display.0.h
index 512dd010d51..512dd010d51 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Display.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Display.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Display.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Display.1.h
index 1be4f0143d7..1be4f0143d7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Display.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Display.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Display.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Display.2.h
index 915d3de9a29..915d3de9a29 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Display.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Display.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Display.Core.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Display.Core.0.h
index fefd5e0d040..fefd5e0d040 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Display.Core.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Display.Core.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Display.Core.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Display.Core.1.h
index e08152fbfba..e08152fbfba 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Display.Core.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Display.Core.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Display.Core.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Display.Core.2.h
index 9b4547349ef..9b4547349ef 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Display.Core.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Display.Core.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Effects.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Effects.0.h
index 2147bba17ff..2147bba17ff 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Effects.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Effects.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Effects.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Effects.1.h
index 1a1c884d48a..1a1c884d48a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Effects.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Effects.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Effects.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Effects.2.h
index 3889241ca22..3889241ca22 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Effects.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Effects.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Holographic.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Holographic.0.h
index 40fe6660e53..40fe6660e53 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Holographic.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Holographic.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Holographic.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Holographic.1.h
index bb9fd882461..bb9fd882461 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Holographic.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Holographic.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Holographic.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Holographic.2.h
index a28533fb7be..a28533fb7be 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Holographic.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Holographic.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Imaging.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Imaging.0.h
index 662636d606e..662636d606e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Imaging.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Imaging.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Imaging.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Imaging.1.h
index b907e31e46e..b907e31e46e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Imaging.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Imaging.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Imaging.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Imaging.2.h
index 428a650bbe4..428a650bbe4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Imaging.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Imaging.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.0.h
index b8c3b8c379e..b8c3b8c379e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.1.h
index 29dee8eae71..29dee8eae71 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.2.h
index a2b47b3a6c5..a2b47b3a6c5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.OptionDetails.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.OptionDetails.0.h
index 44e84d6971f..44e84d6971f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.OptionDetails.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.OptionDetails.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.OptionDetails.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.OptionDetails.1.h
index 466e1406159..466e1406159 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.OptionDetails.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.OptionDetails.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.OptionDetails.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.OptionDetails.2.h
index 9db999865c4..9db999865c4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.OptionDetails.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.OptionDetails.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.PrintTicket.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.PrintTicket.0.h
index 7a08d6d5a1e..7a08d6d5a1e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.PrintTicket.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.PrintTicket.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.PrintTicket.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.PrintTicket.1.h
index 7efe4297546..7efe4297546 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.PrintTicket.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.PrintTicket.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.PrintTicket.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.PrintTicket.2.h
index 8c1ae5668de..8c1ae5668de 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.PrintTicket.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.PrintTicket.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.Workflow.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.Workflow.0.h
index e65e6071b87..e65e6071b87 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.Workflow.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.Workflow.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.Workflow.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.Workflow.1.h
index d90120498e5..d90120498e5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.Workflow.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.Workflow.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.Workflow.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.Workflow.2.h
index 6e5dae1c3a7..6e5dae1c3a7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing.Workflow.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing.Workflow.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing3D.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing3D.0.h
index d268e6993a5..d268e6993a5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing3D.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing3D.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing3D.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing3D.1.h
index 8e89dd2c92c..8e89dd2c92c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing3D.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing3D.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing3D.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing3D.2.h
index 0644c9cd78f..0644c9cd78f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Graphics.Printing3D.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Graphics.Printing3D.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.0.h
index 65d9d4c5515..65d9d4c5515 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.1.h
index d7bb357b4d6..d7bb357b4d6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.2.h
index afc970381ec..afc970381ec 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Core.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Core.0.h
index 9467603f3d3..9467603f3d3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Core.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Core.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Core.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Core.1.h
index a47d00feb48..a47d00feb48 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Core.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Core.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Core.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Core.2.h
index ce0d91e6361..ce0d91e6361 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Core.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Core.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Deployment.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Deployment.0.h
index 604007089bb..604007089bb 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Deployment.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Deployment.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Deployment.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Deployment.1.h
index 4c752dfb0d5..4c752dfb0d5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Deployment.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Deployment.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Deployment.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Deployment.2.h
index 0e85896e25e..0e85896e25e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Deployment.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Deployment.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Deployment.Preview.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Deployment.Preview.0.h
index d500f52b202..d500f52b202 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Deployment.Preview.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Deployment.Preview.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Deployment.Preview.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Deployment.Preview.1.h
index e9cfb56b950..e9cfb56b950 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Deployment.Preview.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Deployment.Preview.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Deployment.Preview.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Deployment.Preview.2.h
index 17b6864d202..17b6864d202 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Deployment.Preview.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Deployment.Preview.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Policies.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Policies.0.h
index bc1b0f1b547..bc1b0f1b547 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Policies.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Policies.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Policies.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Policies.1.h
index a7bbe0dd50e..a7bbe0dd50e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Policies.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Policies.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Policies.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Policies.2.h
index b9cadca1bd9..b9cadca1bd9 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Policies.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Policies.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Update.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Update.0.h
index e6d243322a1..e6d243322a1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Update.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Update.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Update.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Update.1.h
index 088adf683c1..088adf683c1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Update.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Update.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Update.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Update.2.h
index 477af056eb6..477af056eb6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Update.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Update.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Workplace.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Workplace.0.h
index bb72ca102de..bb72ca102de 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Workplace.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Workplace.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Workplace.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Workplace.1.h
index 0a6444b1580..0a6444b1580 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Workplace.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Workplace.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Workplace.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Workplace.2.h
index 05a900410d6..05a900410d6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Management.Workplace.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Management.Workplace.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.0.h
index 3fd248d3641..3fd248d3641 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.1.h
index 53e08da537c..53e08da537c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.2.h
index 6a2b61768a1..6a2b61768a1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.AppBroadcasting.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.AppBroadcasting.0.h
index 7238b551556..7238b551556 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.AppBroadcasting.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.AppBroadcasting.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.AppBroadcasting.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.AppBroadcasting.1.h
index 353088647f3..353088647f3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.AppBroadcasting.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.AppBroadcasting.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.AppBroadcasting.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.AppBroadcasting.2.h
index 9661e5be8e4..9661e5be8e4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.AppBroadcasting.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.AppBroadcasting.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.AppRecording.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.AppRecording.0.h
index 72769c0370b..72769c0370b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.AppRecording.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.AppRecording.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.AppRecording.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.AppRecording.1.h
index e83b6517124..e83b6517124 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.AppRecording.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.AppRecording.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.AppRecording.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.AppRecording.2.h
index 539206381f8..539206381f8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.AppRecording.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.AppRecording.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Audio.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Audio.0.h
index bbf1585577b..bbf1585577b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Audio.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Audio.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Audio.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Audio.1.h
index 384d6c98714..384d6c98714 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Audio.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Audio.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Audio.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Audio.2.h
index 312d86b297b..312d86b297b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Audio.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Audio.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.0.h
index edd3d90789d..edd3d90789d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.1.h
index 52f42487807..52f42487807 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.2.h
index 4567af8b087..4567af8b087 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.Core.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.Core.0.h
index 1446cb8727a..1446cb8727a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.Core.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.Core.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.Core.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.Core.1.h
index b3c8b8f6111..b3c8b8f6111 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.Core.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.Core.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.Core.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.Core.2.h
index a14ed5ec163..a14ed5ec163 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.Core.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.Core.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.Frames.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.Frames.0.h
index c53eb498e26..c53eb498e26 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.Frames.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.Frames.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.Frames.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.Frames.1.h
index cf1b2155786..cf1b2155786 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.Frames.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.Frames.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.Frames.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.Frames.2.h
index f22e9e094c6..f22e9e094c6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Capture.Frames.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Capture.Frames.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Casting.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Casting.0.h
index 4c1847bc105..4c1847bc105 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Casting.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Casting.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Casting.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Casting.1.h
index 16ac225940e..16ac225940e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Casting.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Casting.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Casting.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Casting.2.h
index d8322515320..d8322515320 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Casting.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Casting.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.ClosedCaptioning.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.ClosedCaptioning.0.h
index fdc977e612a..fdc977e612a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.ClosedCaptioning.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.ClosedCaptioning.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.ClosedCaptioning.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.ClosedCaptioning.1.h
index 2e2a16ca068..2e2a16ca068 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.ClosedCaptioning.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.ClosedCaptioning.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.ClosedCaptioning.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.ClosedCaptioning.2.h
index c154fb67975..c154fb67975 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.ClosedCaptioning.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.ClosedCaptioning.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.ContentRestrictions.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.ContentRestrictions.0.h
index 6f8da5bb3c2..6f8da5bb3c2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.ContentRestrictions.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.ContentRestrictions.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.ContentRestrictions.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.ContentRestrictions.1.h
index 28f950ca8ec..28f950ca8ec 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.ContentRestrictions.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.ContentRestrictions.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.ContentRestrictions.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.ContentRestrictions.2.h
index 87b2b38a719..87b2b38a719 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.ContentRestrictions.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.ContentRestrictions.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Control.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Control.0.h
index c7145b3ba0c..c7145b3ba0c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Control.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Control.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Control.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Control.1.h
index 9bbff292de6..9bbff292de6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Control.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Control.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Control.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Control.2.h
index 97dd1359855..97dd1359855 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Control.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Control.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Core.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Core.0.h
index 36b924cfa71..36b924cfa71 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Core.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Core.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Core.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Core.1.h
index 797281c8ed0..797281c8ed0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Core.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Core.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Core.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Core.2.h
index 5aa10d180e1..5aa10d180e1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Core.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Core.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Core.Preview.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Core.Preview.0.h
index 274e63dd3e0..274e63dd3e0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Core.Preview.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Core.Preview.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Core.Preview.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Core.Preview.1.h
index be569d72795..be569d72795 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Core.Preview.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Core.Preview.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Core.Preview.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Core.Preview.2.h
index 45bbfc8f468..45bbfc8f468 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Core.Preview.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Core.Preview.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Devices.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Devices.0.h
index db3c4864633..db3c4864633 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Devices.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Devices.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Devices.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Devices.1.h
index 73438cc3a70..73438cc3a70 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Devices.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Devices.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Devices.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Devices.2.h
index d1af1fc1665..d1af1fc1665 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Devices.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Devices.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Devices.Core.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Devices.Core.0.h
index e821e711b04..e821e711b04 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Devices.Core.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Devices.Core.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Devices.Core.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Devices.Core.1.h
index 09eb22139ea..09eb22139ea 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Devices.Core.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Devices.Core.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Devices.Core.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Devices.Core.2.h
index 6d0a8d7edd3..6d0a8d7edd3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Devices.Core.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Devices.Core.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.DialProtocol.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.DialProtocol.0.h
index 66908f0c811..66908f0c811 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.DialProtocol.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.DialProtocol.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.DialProtocol.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.DialProtocol.1.h
index a703e67989b..a703e67989b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.DialProtocol.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.DialProtocol.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.DialProtocol.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.DialProtocol.2.h
index 2c9b64ecdd9..2c9b64ecdd9 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.DialProtocol.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.DialProtocol.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Editing.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Editing.0.h
index 682c6e0faa2..682c6e0faa2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Editing.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Editing.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Editing.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Editing.1.h
index 79048d9b644..79048d9b644 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Editing.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Editing.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Editing.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Editing.2.h
index b291d471912..b291d471912 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Editing.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Editing.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Effects.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Effects.0.h
index c5ee42cb648..c5ee42cb648 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Effects.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Effects.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Effects.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Effects.1.h
index 5eb42552df1..5eb42552df1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Effects.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Effects.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Effects.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Effects.2.h
index 6704ab6156c..6704ab6156c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Effects.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Effects.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.FaceAnalysis.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.FaceAnalysis.0.h
index 2dc915eacf7..2dc915eacf7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.FaceAnalysis.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.FaceAnalysis.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.FaceAnalysis.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.FaceAnalysis.1.h
index 51f03691eb6..51f03691eb6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.FaceAnalysis.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.FaceAnalysis.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.FaceAnalysis.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.FaceAnalysis.2.h
index 456a0628f7b..456a0628f7b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.FaceAnalysis.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.FaceAnalysis.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Import.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Import.0.h
index dd6b9f8ef42..dd6b9f8ef42 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Import.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Import.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Import.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Import.1.h
index b95c1b8a104..b95c1b8a104 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Import.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Import.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Import.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Import.2.h
index 5abb8ca7c43..5abb8ca7c43 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Import.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Import.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.MediaProperties.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.MediaProperties.0.h
index cfde96d2c77..cfde96d2c77 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.MediaProperties.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.MediaProperties.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.MediaProperties.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.MediaProperties.1.h
index 591d7b26a16..591d7b26a16 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.MediaProperties.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.MediaProperties.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.MediaProperties.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.MediaProperties.2.h
index c7253dd90f2..c7253dd90f2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.MediaProperties.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.MediaProperties.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Miracast.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Miracast.0.h
index 88ea97e2edf..88ea97e2edf 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Miracast.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Miracast.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Miracast.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Miracast.1.h
index 73eefa50e03..73eefa50e03 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Miracast.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Miracast.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Miracast.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Miracast.2.h
index e070fdeeaf0..e070fdeeaf0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Miracast.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Miracast.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Ocr.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Ocr.0.h
index eb667249777..eb667249777 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Ocr.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Ocr.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Ocr.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Ocr.1.h
index 2e2dd93e93a..2e2dd93e93a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Ocr.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Ocr.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Ocr.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Ocr.2.h
index 617b5e647cb..617b5e647cb 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Ocr.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Ocr.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.PlayTo.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.PlayTo.0.h
index f926c211b61..f926c211b61 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.PlayTo.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.PlayTo.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.PlayTo.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.PlayTo.1.h
index 70edd77e3a8..70edd77e3a8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.PlayTo.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.PlayTo.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.PlayTo.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.PlayTo.2.h
index 3f3c2b70a36..3f3c2b70a36 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.PlayTo.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.PlayTo.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Playback.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Playback.0.h
index b3ce23c0f8a..b3ce23c0f8a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Playback.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Playback.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Playback.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Playback.1.h
index 4193d5c6725..4193d5c6725 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Playback.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Playback.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Playback.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Playback.2.h
index 64140f23ea2..64140f23ea2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Playback.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Playback.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Playlists.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Playlists.0.h
index 978dd4e3c79..978dd4e3c79 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Playlists.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Playlists.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Playlists.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Playlists.1.h
index 59d7bc81450..59d7bc81450 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Playlists.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Playlists.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Playlists.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Playlists.2.h
index b412160118c..b412160118c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Playlists.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Playlists.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Protection.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Protection.0.h
index c1e3da5ebe3..c1e3da5ebe3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Protection.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Protection.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Protection.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Protection.1.h
index c39086041cb..c39086041cb 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Protection.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Protection.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Protection.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Protection.2.h
index ad0b485694b..ad0b485694b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Protection.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Protection.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Protection.PlayReady.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Protection.PlayReady.0.h
index 1fa072cdcdf..1fa072cdcdf 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Protection.PlayReady.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Protection.PlayReady.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Protection.PlayReady.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Protection.PlayReady.1.h
index 5fd66aab74d..5fd66aab74d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Protection.PlayReady.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Protection.PlayReady.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Protection.PlayReady.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Protection.PlayReady.2.h
index 9b8b94dbd8a..9b8b94dbd8a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Protection.PlayReady.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Protection.PlayReady.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Render.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Render.0.h
index 79179022047..79179022047 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Render.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Render.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Render.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Render.1.h
index 18d77376f0c..18d77376f0c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Render.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Render.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Render.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Render.2.h
index cfec448c86a..cfec448c86a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Render.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Render.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.SpeechRecognition.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.SpeechRecognition.0.h
index 0594a8a38e8..0594a8a38e8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.SpeechRecognition.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.SpeechRecognition.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.SpeechRecognition.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.SpeechRecognition.1.h
index 59d92acbe7a..59d92acbe7a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.SpeechRecognition.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.SpeechRecognition.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.SpeechRecognition.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.SpeechRecognition.2.h
index f7a3448a127..f7a3448a127 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.SpeechRecognition.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.SpeechRecognition.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.SpeechSynthesis.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.SpeechSynthesis.0.h
index 24c168f612f..24c168f612f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.SpeechSynthesis.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.SpeechSynthesis.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.SpeechSynthesis.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.SpeechSynthesis.1.h
index 5f0dd26c8e7..5f0dd26c8e7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.SpeechSynthesis.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.SpeechSynthesis.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.SpeechSynthesis.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.SpeechSynthesis.2.h
index 91c3eb2d7f5..91c3eb2d7f5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.SpeechSynthesis.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.SpeechSynthesis.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Streaming.Adaptive.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Streaming.Adaptive.0.h
index 3602eb54257..3602eb54257 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Streaming.Adaptive.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Streaming.Adaptive.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Streaming.Adaptive.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Streaming.Adaptive.1.h
index 35ce7a4573c..35ce7a4573c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Streaming.Adaptive.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Streaming.Adaptive.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Streaming.Adaptive.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Streaming.Adaptive.2.h
index 1da17a0bfa5..1da17a0bfa5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Streaming.Adaptive.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Streaming.Adaptive.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Transcoding.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Transcoding.0.h
index f0b82c92d37..f0b82c92d37 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Transcoding.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Transcoding.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Transcoding.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Transcoding.1.h
index d12865db1b7..d12865db1b7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Transcoding.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Transcoding.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Transcoding.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Transcoding.2.h
index aa9ef113d6d..aa9ef113d6d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Media.Transcoding.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Media.Transcoding.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.0.h
index 181252f0968..181252f0968 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.1.h
index cee864343dd..cee864343dd 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.2.h
index 58b7438383f..58b7438383f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.BackgroundTransfer.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.BackgroundTransfer.0.h
index d69b2e29070..d69b2e29070 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.BackgroundTransfer.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.BackgroundTransfer.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.BackgroundTransfer.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.BackgroundTransfer.1.h
index 7a14ffa9d0e..7a14ffa9d0e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.BackgroundTransfer.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.BackgroundTransfer.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.BackgroundTransfer.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.BackgroundTransfer.2.h
index d26c07e5a96..d26c07e5a96 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.BackgroundTransfer.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.BackgroundTransfer.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Connectivity.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Connectivity.0.h
index 6c3c616e47f..6c3c616e47f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Connectivity.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Connectivity.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Connectivity.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Connectivity.1.h
index 264f7765e26..264f7765e26 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Connectivity.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Connectivity.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Connectivity.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Connectivity.2.h
index 90c569d0a23..90c569d0a23 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Connectivity.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Connectivity.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.NetworkOperators.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.NetworkOperators.0.h
index dd6edc70b5c..dd6edc70b5c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.NetworkOperators.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.NetworkOperators.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.NetworkOperators.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.NetworkOperators.1.h
index d62ac2e0c59..d62ac2e0c59 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.NetworkOperators.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.NetworkOperators.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.NetworkOperators.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.NetworkOperators.2.h
index be6869a284a..be6869a284a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.NetworkOperators.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.NetworkOperators.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Proximity.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Proximity.0.h
index 360b57225de..360b57225de 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Proximity.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Proximity.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Proximity.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Proximity.1.h
index 24d3f29eee1..24d3f29eee1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Proximity.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Proximity.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Proximity.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Proximity.2.h
index afa0670a28a..afa0670a28a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Proximity.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Proximity.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.PushNotifications.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.PushNotifications.0.h
index f46651e659b..f46651e659b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.PushNotifications.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.PushNotifications.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.PushNotifications.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.PushNotifications.1.h
index 9d14fbc4061..9d14fbc4061 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.PushNotifications.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.PushNotifications.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.PushNotifications.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.PushNotifications.2.h
index 64aedcf5b14..64aedcf5b14 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.PushNotifications.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.PushNotifications.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.ServiceDiscovery.Dnssd.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.ServiceDiscovery.Dnssd.0.h
index ea6275614bd..ea6275614bd 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.ServiceDiscovery.Dnssd.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.ServiceDiscovery.Dnssd.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.ServiceDiscovery.Dnssd.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.ServiceDiscovery.Dnssd.1.h
index 1d10e8a0998..1d10e8a0998 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.ServiceDiscovery.Dnssd.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.ServiceDiscovery.Dnssd.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.ServiceDiscovery.Dnssd.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.ServiceDiscovery.Dnssd.2.h
index a78553ec620..a78553ec620 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.ServiceDiscovery.Dnssd.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.ServiceDiscovery.Dnssd.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Sockets.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Sockets.0.h
index 47f3ca6509a..47f3ca6509a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Sockets.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Sockets.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Sockets.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Sockets.1.h
index 22bdd77b127..22bdd77b127 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Sockets.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Sockets.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Sockets.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Sockets.2.h
index 172d9d632e2..172d9d632e2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Sockets.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Sockets.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Vpn.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Vpn.0.h
index 42be193fa5e..42be193fa5e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Vpn.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Vpn.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Vpn.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Vpn.1.h
index fe334f1178a..fe334f1178a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Vpn.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Vpn.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Vpn.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Vpn.2.h
index c7177fa926a..c7177fa926a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.Vpn.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.Vpn.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.XboxLive.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.XboxLive.0.h
index 9819161fba5..9819161fba5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.XboxLive.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.XboxLive.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.XboxLive.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.XboxLive.1.h
index f4d042314fc..f4d042314fc 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.XboxLive.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.XboxLive.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.XboxLive.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.XboxLive.2.h
index 222d547a2ff..222d547a2ff 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Networking.XboxLive.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Networking.XboxLive.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.0.h
index 7a91009d4bb..7a91009d4bb 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.1.h
index 49d1ed69548..49d1ed69548 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.2.h
index 8b9fa91734c..8b9fa91734c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Automation.Core.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Automation.Core.0.h
index 31ced5cdd04..31ced5cdd04 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Automation.Core.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Automation.Core.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Automation.Core.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Automation.Core.1.h
index 406a1d3d9f9..406a1d3d9f9 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Automation.Core.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Automation.Core.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Automation.Core.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Automation.Core.2.h
index 25df10a220f..25df10a220f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Automation.Core.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Automation.Core.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.People.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.People.0.h
index 208bf60a61f..208bf60a61f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.People.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.People.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.People.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.People.1.h
index dcb41e15dfb..dcb41e15dfb 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.People.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.People.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.People.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.People.2.h
index 2ba16330e7d..2ba16330e7d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.People.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.People.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.0.h
index 6423bb19b88..6423bb19b88 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.1.h
index b7a1f551fb0..b7a1f551fb0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.2.h
index c8517e5d58c..c8517e5d58c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.Preview.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.Preview.0.h
index 3b1cd881038..3b1cd881038 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.Preview.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.Preview.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.Preview.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.Preview.1.h
index 818f8c663d6..818f8c663d6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.Preview.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.Preview.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.Preview.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.Preview.2.h
index 7eb6baaba4a..7eb6baaba4a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.Preview.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.Preview.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.Surfaces.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.Surfaces.0.h
index a4052be91a1..a4052be91a1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.Surfaces.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.Surfaces.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.Surfaces.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.Surfaces.1.h
index aae283b9f52..aae283b9f52 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.Surfaces.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.Surfaces.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.Surfaces.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.Surfaces.2.h
index d3dec379be6..d3dec379be6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Perception.Spatial.Surfaces.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Perception.Spatial.Surfaces.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.ApplicationModel.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.ApplicationModel.0.h
index 2bc5a9e958e..2bc5a9e958e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.ApplicationModel.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.ApplicationModel.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.ApplicationModel.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.ApplicationModel.1.h
index a41d167203e..a41d167203e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.ApplicationModel.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.ApplicationModel.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.ApplicationModel.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.ApplicationModel.2.h
index f196f34c507..f196f34c507 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.ApplicationModel.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.ApplicationModel.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Devices.Notification.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Devices.Notification.0.h
index 08e53fbab90..08e53fbab90 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Devices.Notification.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Devices.Notification.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Devices.Notification.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Devices.Notification.1.h
index aafe5769ba1..aafe5769ba1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Devices.Notification.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Devices.Notification.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Devices.Notification.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Devices.Notification.2.h
index c5abb116573..c5abb116573 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Devices.Notification.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Devices.Notification.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Devices.Power.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Devices.Power.0.h
index 2bd89bb0efb..2bd89bb0efb 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Devices.Power.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Devices.Power.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Devices.Power.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Devices.Power.1.h
index 921512f255b..921512f255b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Devices.Power.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Devices.Power.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Devices.Power.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Devices.Power.2.h
index 09c273df3f2..09c273df3f2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Devices.Power.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Devices.Power.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Management.Deployment.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Management.Deployment.0.h
index 59e20fa9e84..59e20fa9e84 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Management.Deployment.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Management.Deployment.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Management.Deployment.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Management.Deployment.1.h
index 66d79345122..66d79345122 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Management.Deployment.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Management.Deployment.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Management.Deployment.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Management.Deployment.2.h
index b6a094ae837..b6a094ae837 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Management.Deployment.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Management.Deployment.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Media.Devices.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Media.Devices.0.h
index 5d76ce67a58..5d76ce67a58 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Media.Devices.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Media.Devices.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Media.Devices.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Media.Devices.1.h
index 6ea3d4bca49..6ea3d4bca49 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Media.Devices.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Media.Devices.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Media.Devices.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Media.Devices.2.h
index ff4e14b6f3a..ff4e14b6f3a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Media.Devices.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Media.Devices.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Notification.Management.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Notification.Management.0.h
index 98149679eb8..98149679eb8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Notification.Management.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Notification.Management.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Notification.Management.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Notification.Management.1.h
index 906dc49a5b5..906dc49a5b5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Notification.Management.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Notification.Management.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Notification.Management.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Notification.Management.2.h
index e49db7402ff..e49db7402ff 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Notification.Management.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Notification.Management.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.0.h
index 08ea9e752b3..08ea9e752b3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.1.h
index 1780d4d21c6..1780d4d21c6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.2.h
index c07a814fd72..c07a814fd72 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.Provisioning.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.Provisioning.0.h
index 9a2436ed26e..9a2436ed26e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.Provisioning.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.Provisioning.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.Provisioning.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.Provisioning.1.h
index dad8cc43b5d..dad8cc43b5d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.Provisioning.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.Provisioning.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.Provisioning.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.Provisioning.2.h
index e6de5454b41..e6de5454b41 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.Provisioning.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.PersonalInformation.Provisioning.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Speech.Recognition.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Speech.Recognition.0.h
index 68bca054a62..68bca054a62 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Speech.Recognition.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Speech.Recognition.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Speech.Recognition.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Speech.Recognition.1.h
index 95d1169b6c3..95d1169b6c3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Speech.Recognition.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Speech.Recognition.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Speech.Recognition.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Speech.Recognition.2.h
index 92ec1a7b5bc..92ec1a7b5bc 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.Speech.Recognition.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.Speech.Recognition.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.StartScreen.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.StartScreen.0.h
index 9755c10c391..9755c10c391 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.StartScreen.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.StartScreen.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.StartScreen.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.StartScreen.1.h
index be1956c4e11..be1956c4e11 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.StartScreen.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.StartScreen.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.StartScreen.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.StartScreen.2.h
index 84e92f59cc0..84e92f59cc0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.StartScreen.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.StartScreen.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.0.h
index 6502f56bb07..6502f56bb07 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.1.h
index 6ee23a58a64..6ee23a58a64 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.2.h
index da339f63b0e..da339f63b0e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.Power.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.Power.0.h
index 1058a0c64aa..1058a0c64aa 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.Power.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.Power.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.Power.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.Power.1.h
index 8b22db8c4a7..8b22db8c4a7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.Power.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.Power.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.Power.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.Power.2.h
index 3f4bf7b791b..3f4bf7b791b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.Power.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.Power.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.Profile.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.Profile.0.h
index e2440334442..e2440334442 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.Profile.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.Profile.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.Profile.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.Profile.1.h
index 2ffd4732365..2ffd4732365 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.Profile.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.Profile.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.Profile.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.Profile.2.h
index 2c59a60e1e8..2c59a60e1e8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.Profile.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.Profile.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.UserProfile.GameServices.Core.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.UserProfile.GameServices.Core.0.h
index 23e93152638..23e93152638 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.UserProfile.GameServices.Core.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.UserProfile.GameServices.Core.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.UserProfile.GameServices.Core.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.UserProfile.GameServices.Core.1.h
index 3185f372555..3185f372555 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.UserProfile.GameServices.Core.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.UserProfile.GameServices.Core.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.UserProfile.GameServices.Core.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.UserProfile.GameServices.Core.2.h
index 7ac72ceb473..7ac72ceb473 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.System.UserProfile.GameServices.Core.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.System.UserProfile.GameServices.Core.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.UI.Input.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.UI.Input.0.h
index 527f1202c5a..527f1202c5a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.UI.Input.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.UI.Input.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.UI.Input.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.UI.Input.1.h
index cef3219c758..cef3219c758 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.UI.Input.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.UI.Input.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.UI.Input.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.UI.Input.2.h
index 8f318f398d3..8f318f398d3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Phone.UI.Input.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Phone.UI.Input.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.0.h
index 85d4d53a689..85d4d53a689 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.1.h
index 27449413ed8..27449413ed8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.2.h
index 0f511f5d33f..0f511f5d33f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Core.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Core.0.h
index f009cc449fa..f009cc449fa 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Core.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Core.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Core.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Core.1.h
index 3b61a617329..3b61a617329 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Core.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Core.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Core.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Core.2.h
index 307f496e505..307f496e505 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Core.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Core.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Provider.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Provider.0.h
index 912a81c65f5..912a81c65f5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Provider.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Provider.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Provider.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Provider.1.h
index 217abec7ce1..217abec7ce1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Provider.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Provider.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Provider.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Provider.2.h
index 9adf2da9561..9adf2da9561 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Provider.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Identity.Provider.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.OnlineId.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.OnlineId.0.h
index 15e85372a3c..15e85372a3c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.OnlineId.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.OnlineId.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.OnlineId.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.OnlineId.1.h
index 96552e36bb1..96552e36bb1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.OnlineId.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.OnlineId.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.OnlineId.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.OnlineId.2.h
index ad5e04cfb0f..ad5e04cfb0f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.OnlineId.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.OnlineId.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.0.h
index 99b77b88bd2..99b77b88bd2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.1.h
index 3fa16f22d26..3fa16f22d26 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.2.h
index 8564ee939bd..8564ee939bd 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Core.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Core.0.h
index 70553741112..70553741112 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Core.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Core.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Core.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Core.1.h
index 293594c644a..293594c644a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Core.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Core.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Core.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Core.2.h
index cfa65be33f2..cfa65be33f2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Core.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Core.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Provider.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Provider.0.h
index c5e3d2097ad..c5e3d2097ad 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Provider.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Provider.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Provider.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Provider.1.h
index 6d8a12f7da7..6d8a12f7da7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Provider.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Provider.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Provider.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Provider.2.h
index 4c7026fc2fa..4c7026fc2fa 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Provider.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authentication.Web.Provider.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authorization.AppCapabilityAccess.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authorization.AppCapabilityAccess.0.h
index f7dc118f42b..f7dc118f42b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authorization.AppCapabilityAccess.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authorization.AppCapabilityAccess.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authorization.AppCapabilityAccess.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authorization.AppCapabilityAccess.1.h
index 83498071292..83498071292 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authorization.AppCapabilityAccess.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authorization.AppCapabilityAccess.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authorization.AppCapabilityAccess.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authorization.AppCapabilityAccess.2.h
index 4f0a4e75c88..4f0a4e75c88 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Authorization.AppCapabilityAccess.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Authorization.AppCapabilityAccess.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Credentials.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Credentials.0.h
index 8ddcaedca9f..8ddcaedca9f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Credentials.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Credentials.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Credentials.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Credentials.1.h
index 8d3565172d3..8d3565172d3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Credentials.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Credentials.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Credentials.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Credentials.2.h
index 7b82f3a58e1..7b82f3a58e1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Credentials.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Credentials.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Credentials.UI.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Credentials.UI.0.h
index 735d8e0e5a3..735d8e0e5a3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Credentials.UI.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Credentials.UI.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Credentials.UI.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Credentials.UI.1.h
index be484a1865d..be484a1865d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Credentials.UI.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Credentials.UI.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Credentials.UI.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Credentials.UI.2.h
index 2ef4493f0dd..2ef4493f0dd 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Credentials.UI.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Credentials.UI.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.0.h
index 836197c4c6b..836197c4c6b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.1.h
index 3f415cda44a..3f415cda44a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.2.h
index 379c8d5a0db..379c8d5a0db 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.Certificates.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.Certificates.0.h
index c7864a7f972..c7864a7f972 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.Certificates.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.Certificates.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.Certificates.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.Certificates.1.h
index fdd5940289d..fdd5940289d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.Certificates.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.Certificates.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.Certificates.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.Certificates.2.h
index 1135f5ac5a5..1135f5ac5a5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.Certificates.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.Certificates.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.Core.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.Core.0.h
index 75a304cbfd5..75a304cbfd5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.Core.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.Core.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.Core.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.Core.1.h
index b8e22f6bca7..b8e22f6bca7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.Core.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.Core.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.Core.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.Core.2.h
index 23c7ec4cc15..23c7ec4cc15 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.Core.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.Core.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.DataProtection.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.DataProtection.0.h
index 554ba1a9dee..554ba1a9dee 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.DataProtection.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.DataProtection.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.DataProtection.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.DataProtection.1.h
index 38cca420503..38cca420503 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.DataProtection.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.DataProtection.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.DataProtection.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.DataProtection.2.h
index d460f47c4fd..d460f47c4fd 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Cryptography.DataProtection.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Cryptography.DataProtection.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.DataProtection.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.DataProtection.0.h
index 9f8a7c8c2e8..9f8a7c8c2e8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.DataProtection.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.DataProtection.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.DataProtection.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.DataProtection.1.h
index 0f0d3f10493..0f0d3f10493 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.DataProtection.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.DataProtection.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.DataProtection.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.DataProtection.2.h
index d5c86b9b77f..d5c86b9b77f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.DataProtection.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.DataProtection.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.EnterpriseData.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.EnterpriseData.0.h
index c7a9a9da2ee..c7a9a9da2ee 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.EnterpriseData.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.EnterpriseData.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.EnterpriseData.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.EnterpriseData.1.h
index ca924ca14c0..ca924ca14c0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.EnterpriseData.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.EnterpriseData.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.EnterpriseData.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.EnterpriseData.2.h
index 4ba1bc9226b..4ba1bc9226b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.EnterpriseData.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.EnterpriseData.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.ExchangeActiveSyncProvisioning.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.ExchangeActiveSyncProvisioning.0.h
index d4aea4d0a54..d4aea4d0a54 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.ExchangeActiveSyncProvisioning.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.ExchangeActiveSyncProvisioning.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.ExchangeActiveSyncProvisioning.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.ExchangeActiveSyncProvisioning.1.h
index 2d9c7a2447d..2d9c7a2447d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.ExchangeActiveSyncProvisioning.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.ExchangeActiveSyncProvisioning.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.ExchangeActiveSyncProvisioning.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.ExchangeActiveSyncProvisioning.2.h
index 5e1fa550296..5e1fa550296 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.ExchangeActiveSyncProvisioning.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.ExchangeActiveSyncProvisioning.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Isolation.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Isolation.0.h
index 3324940a488..3324940a488 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Isolation.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Isolation.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Isolation.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Isolation.1.h
index 906d57471c9..906d57471c9 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Isolation.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Isolation.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Isolation.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Isolation.2.h
index 57d40a4bef0..57d40a4bef0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Security.Isolation.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Security.Isolation.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Cortana.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Cortana.0.h
index 474a5a1bdad..474a5a1bdad 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Cortana.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Cortana.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Cortana.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Cortana.1.h
index becbf00bf33..becbf00bf33 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Cortana.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Cortana.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Cortana.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Cortana.2.h
index 0d83c87e3fa..0d83c87e3fa 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Cortana.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Cortana.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.0.h
index 30250020089..30250020089 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.1.h
index 014527abc43..014527abc43 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.2.h
index 8b6d37c5999..8b6d37c5999 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.Guidance.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.Guidance.0.h
index e9b5d55e207..e9b5d55e207 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.Guidance.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.Guidance.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.Guidance.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.Guidance.1.h
index f7d7d17676a..f7d7d17676a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.Guidance.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.Guidance.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.Guidance.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.Guidance.2.h
index 2d5ba61fadc..2d5ba61fadc 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.Guidance.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.Guidance.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.LocalSearch.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.LocalSearch.0.h
index 930545d171e..930545d171e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.LocalSearch.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.LocalSearch.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.LocalSearch.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.LocalSearch.1.h
index 70f702a2fa0..70f702a2fa0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.LocalSearch.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.LocalSearch.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.LocalSearch.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.LocalSearch.2.h
index 24b65d012ac..24b65d012ac 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.LocalSearch.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.LocalSearch.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.OfflineMaps.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.OfflineMaps.0.h
index e6ccd375004..e6ccd375004 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.OfflineMaps.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.OfflineMaps.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.OfflineMaps.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.OfflineMaps.1.h
index 0b8fcd97005..0b8fcd97005 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.OfflineMaps.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.OfflineMaps.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.OfflineMaps.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.OfflineMaps.2.h
index 45d564de7b5..45d564de7b5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Maps.OfflineMaps.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Maps.OfflineMaps.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Store.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Store.0.h
index da560434622..da560434622 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Store.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Store.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Store.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Store.1.h
index 9a945e0fa2c..9a945e0fa2c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Store.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Store.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Store.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Store.2.h
index 497076dbb4c..497076dbb4c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.Store.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.Store.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.TargetedContent.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.TargetedContent.0.h
index 6dcd912dc5d..6dcd912dc5d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.TargetedContent.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.TargetedContent.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.TargetedContent.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.TargetedContent.1.h
index 6103d37f80e..6103d37f80e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.TargetedContent.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.TargetedContent.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.TargetedContent.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.TargetedContent.2.h
index 44721a24d97..44721a24d97 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Services.TargetedContent.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Services.TargetedContent.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.0.h
index 23981d81bdc..23981d81bdc 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.1.h
index 9c012a93918..9c012a93918 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.2.h
index d441002c457..d441002c457 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.AccessCache.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.AccessCache.0.h
index e5e12156471..e5e12156471 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.AccessCache.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.AccessCache.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.AccessCache.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.AccessCache.1.h
index e4c1ae11169..e4c1ae11169 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.AccessCache.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.AccessCache.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.AccessCache.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.AccessCache.2.h
index 4e049f6dfae..4e049f6dfae 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.AccessCache.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.AccessCache.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.BulkAccess.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.BulkAccess.0.h
index a863d28b142..a863d28b142 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.BulkAccess.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.BulkAccess.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.BulkAccess.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.BulkAccess.1.h
index 90fab04f32b..90fab04f32b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.BulkAccess.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.BulkAccess.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.BulkAccess.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.BulkAccess.2.h
index c5a359a9eb3..c5a359a9eb3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.BulkAccess.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.BulkAccess.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Compression.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Compression.0.h
index 8a5a061dab2..8a5a061dab2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Compression.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Compression.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Compression.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Compression.1.h
index b1348b53d15..b1348b53d15 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Compression.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Compression.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Compression.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Compression.2.h
index e8095700dcb..e8095700dcb 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Compression.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Compression.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.FileProperties.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.FileProperties.0.h
index 7c23bfb0f49..7c23bfb0f49 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.FileProperties.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.FileProperties.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.FileProperties.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.FileProperties.1.h
index ca1b32465bf..ca1b32465bf 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.FileProperties.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.FileProperties.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.FileProperties.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.FileProperties.2.h
index cd5bd040bc6..cd5bd040bc6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.FileProperties.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.FileProperties.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Pickers.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Pickers.0.h
index 4d64141c4f8..4d64141c4f8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Pickers.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Pickers.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Pickers.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Pickers.1.h
index a59fbf44614..a59fbf44614 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Pickers.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Pickers.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Pickers.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Pickers.2.h
index 7ee462c0336..7ee462c0336 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Pickers.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Pickers.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Pickers.Provider.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Pickers.Provider.0.h
index 67b2a07c274..67b2a07c274 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Pickers.Provider.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Pickers.Provider.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Pickers.Provider.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Pickers.Provider.1.h
index a5e01371ed2..a5e01371ed2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Pickers.Provider.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Pickers.Provider.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Pickers.Provider.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Pickers.Provider.2.h
index 6db8a49e0ec..6db8a49e0ec 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Pickers.Provider.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Pickers.Provider.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Provider.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Provider.0.h
index e3320c9e787..e3320c9e787 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Provider.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Provider.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Provider.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Provider.1.h
index 10cbcf06597..10cbcf06597 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Provider.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Provider.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Provider.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Provider.2.h
index b652a781552..b652a781552 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Provider.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Provider.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Search.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Search.0.h
index 6906378e859..6906378e859 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Search.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Search.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Search.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Search.1.h
index d0603dd7222..d0603dd7222 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Search.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Search.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Search.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Search.2.h
index b70849c9d3f..b70849c9d3f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Search.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Search.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Streams.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Streams.0.h
index a89ee65217d..a89ee65217d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Streams.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Streams.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Streams.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Streams.1.h
index fe6e871f4ad..fe6e871f4ad 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Streams.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Streams.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Streams.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Streams.2.h
index a083ba644a2..a083ba644a2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Storage.Streams.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Storage.Streams.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.0.h
index aec55272161..aec55272161 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.1.h
index a1d77398fa7..a1d77398fa7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.2.h
index 582ae9e07c5..582ae9e07c5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.0.h
index 6c4adaa6f4f..6c4adaa6f4f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.1.h
index 867032015b0..867032015b0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.2.h
index 91036747f5f..91036747f5f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.DevicePortal.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.DevicePortal.0.h
index 0b639bfdfe1..0b639bfdfe1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.DevicePortal.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.DevicePortal.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.DevicePortal.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.DevicePortal.1.h
index b8d46016606..b8d46016606 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.DevicePortal.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.DevicePortal.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.DevicePortal.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.DevicePortal.2.h
index 31bc401a607..31bc401a607 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.DevicePortal.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.DevicePortal.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.Telemetry.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.Telemetry.0.h
index 53c50a39e8f..53c50a39e8f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.Telemetry.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.Telemetry.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.Telemetry.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.Telemetry.1.h
index dd0c35d830a..dd0c35d830a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.Telemetry.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.Telemetry.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.Telemetry.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.Telemetry.2.h
index 1c1fcc846ec..1c1fcc846ec 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.Telemetry.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.Telemetry.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.TraceReporting.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.TraceReporting.0.h
index fc70e386cb0..fc70e386cb0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.TraceReporting.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.TraceReporting.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.TraceReporting.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.TraceReporting.1.h
index f3cf014c547..f3cf014c547 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.TraceReporting.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.TraceReporting.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.TraceReporting.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.TraceReporting.2.h
index b280725668d..b280725668d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Diagnostics.TraceReporting.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Diagnostics.TraceReporting.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Display.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Display.0.h
index dc0724b72a2..dc0724b72a2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Display.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Display.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Display.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Display.1.h
index 4deacdd326a..4deacdd326a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Display.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Display.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Display.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Display.2.h
index 56f6f90fccd..56f6f90fccd 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Display.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Display.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Implementation.FileExplorer.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Implementation.FileExplorer.0.h
index 9be1a62fb74..9be1a62fb74 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Implementation.FileExplorer.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Implementation.FileExplorer.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Implementation.FileExplorer.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Implementation.FileExplorer.1.h
index 6e5a0eb5b7c..6e5a0eb5b7c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Implementation.FileExplorer.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Implementation.FileExplorer.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Implementation.FileExplorer.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Implementation.FileExplorer.2.h
index 0db98d25d8e..0db98d25d8e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Implementation.FileExplorer.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Implementation.FileExplorer.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Inventory.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Inventory.0.h
index adfa96842aa..adfa96842aa 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Inventory.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Inventory.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Inventory.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Inventory.1.h
index ae65cd3b55d..ae65cd3b55d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Inventory.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Inventory.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Inventory.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Inventory.2.h
index d55b37e8dfd..d55b37e8dfd 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Inventory.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Inventory.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Power.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Power.0.h
index 96787778d68..96787778d68 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Power.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Power.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Power.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Power.1.h
index 2c048cc5f95..2c048cc5f95 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Power.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Power.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Power.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Power.2.h
index 465fdae9178..465fdae9178 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Power.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Power.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Power.Diagnostics.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Power.Diagnostics.0.h
index 605c0b6b48a..605c0b6b48a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Power.Diagnostics.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Power.Diagnostics.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Power.Diagnostics.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Power.Diagnostics.1.h
index e5202868356..e5202868356 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Power.Diagnostics.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Power.Diagnostics.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Power.Diagnostics.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Power.Diagnostics.2.h
index d62b43c9f82..d62b43c9f82 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Power.Diagnostics.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Power.Diagnostics.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Preview.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Preview.0.h
index 80351ab2873..80351ab2873 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Preview.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Preview.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Preview.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Preview.1.h
index 837c443f332..837c443f332 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Preview.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Preview.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Preview.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Preview.2.h
index 505267c1966..505267c1966 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Preview.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Preview.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Profile.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Profile.0.h
index 33a825a51c6..33a825a51c6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Profile.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Profile.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Profile.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Profile.1.h
index 9434d2ee70c..9434d2ee70c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Profile.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Profile.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Profile.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Profile.2.h
index 1fa1dadc400..1fa1dadc400 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Profile.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Profile.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Profile.SystemManufacturers.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Profile.SystemManufacturers.0.h
index 145020fcb98..145020fcb98 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Profile.SystemManufacturers.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Profile.SystemManufacturers.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Profile.SystemManufacturers.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Profile.SystemManufacturers.1.h
index 929d183121e..929d183121e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Profile.SystemManufacturers.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Profile.SystemManufacturers.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Profile.SystemManufacturers.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Profile.SystemManufacturers.2.h
index 122511b6b25..122511b6b25 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Profile.SystemManufacturers.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Profile.SystemManufacturers.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.RemoteDesktop.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.RemoteDesktop.0.h
index 7e81dbcd70a..7e81dbcd70a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.RemoteDesktop.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.RemoteDesktop.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.RemoteDesktop.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.RemoteDesktop.1.h
index c598fc0cf8d..c598fc0cf8d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.RemoteDesktop.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.RemoteDesktop.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.RemoteDesktop.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.RemoteDesktop.2.h
index 8aab60b19dc..8aab60b19dc 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.RemoteDesktop.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.RemoteDesktop.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.RemoteSystems.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.RemoteSystems.0.h
index dfc0fc63dfe..dfc0fc63dfe 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.RemoteSystems.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.RemoteSystems.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.RemoteSystems.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.RemoteSystems.1.h
index c2b837331a8..c2b837331a8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.RemoteSystems.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.RemoteSystems.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.RemoteSystems.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.RemoteSystems.2.h
index 85323f3db5f..85323f3db5f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.RemoteSystems.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.RemoteSystems.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Threading.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Threading.0.h
index 68ab8dfd3d8..68ab8dfd3d8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Threading.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Threading.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Threading.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Threading.1.h
index 7f457d0018d..7f457d0018d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Threading.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Threading.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Threading.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Threading.2.h
index 60cdce4a3f3..60cdce4a3f3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Threading.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Threading.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Threading.Core.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Threading.Core.0.h
index 26dd9a1638c..26dd9a1638c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Threading.Core.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Threading.Core.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Threading.Core.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Threading.Core.1.h
index ab5e792f636..ab5e792f636 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Threading.Core.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Threading.Core.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Threading.Core.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Threading.Core.2.h
index 045fefec5a7..045fefec5a7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Threading.Core.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Threading.Core.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Update.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Update.0.h
index 0a4eb09c085..0a4eb09c085 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Update.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Update.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Update.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Update.1.h
index e03bf32d6fc..e03bf32d6fc 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Update.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Update.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Update.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Update.2.h
index ce580f7143c..ce580f7143c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.Update.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.Update.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.UserProfile.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.UserProfile.0.h
index 7b8ab844e79..7b8ab844e79 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.UserProfile.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.UserProfile.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.UserProfile.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.UserProfile.1.h
index 6731bbe5f4d..6731bbe5f4d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.UserProfile.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.UserProfile.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.UserProfile.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.UserProfile.2.h
index 9aab66e6123..9aab66e6123 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.System.UserProfile.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.System.UserProfile.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.0.h
index 56f2c0543cf..56f2c0543cf 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.1.h
index a605208f16b..a605208f16b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.2.h
index b549f9d3beb..b549f9d3beb 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Accessibility.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Accessibility.0.h
index 7adb5d23cd8..7adb5d23cd8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Accessibility.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Accessibility.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Accessibility.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Accessibility.1.h
index 01d11eb31a2..01d11eb31a2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Accessibility.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Accessibility.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Accessibility.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Accessibility.2.h
index 5b0943db137..5b0943db137 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Accessibility.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Accessibility.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ApplicationSettings.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ApplicationSettings.0.h
index 2c8b31841c8..2c8b31841c8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ApplicationSettings.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ApplicationSettings.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ApplicationSettings.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ApplicationSettings.1.h
index 11e578221d3..11e578221d3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ApplicationSettings.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ApplicationSettings.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ApplicationSettings.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ApplicationSettings.2.h
index b66e0be9b88..b66e0be9b88 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ApplicationSettings.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ApplicationSettings.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.0.h
index c08ae2c12d6..c08ae2c12d6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.1.h
index 26d655a98b4..26d655a98b4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.2.h
index 05e397a239a..05e397a239a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Core.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Core.0.h
index 8bc83324274..8bc83324274 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Core.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Core.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Core.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Core.1.h
index 6da6e992b9d..6da6e992b9d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Core.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Core.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Core.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Core.2.h
index 740f5ff07ff..740f5ff07ff 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Core.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Core.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Desktop.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Desktop.0.h
index 47f2223c00e..47f2223c00e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Desktop.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Desktop.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Desktop.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Desktop.1.h
index bda5ec560fd..bda5ec560fd 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Desktop.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Desktop.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Desktop.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Desktop.2.h
index e8c29f3db4b..e8c29f3db4b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Desktop.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Desktop.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Diagnostics.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Diagnostics.0.h
index 117888ee300..117888ee300 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Diagnostics.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Diagnostics.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Diagnostics.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Diagnostics.1.h
index c41c0e99425..c41c0e99425 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Diagnostics.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Diagnostics.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Diagnostics.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Diagnostics.2.h
index 9e8fb49c1f7..9e8fb49c1f7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Diagnostics.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Diagnostics.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Effects.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Effects.0.h
index 6f0e1e09fdf..6f0e1e09fdf 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Effects.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Effects.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Effects.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Effects.1.h
index a885848d121..a885848d121 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Effects.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Effects.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Effects.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Effects.2.h
index 6a74b741899..6a74b741899 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Effects.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Effects.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Interactions.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Interactions.0.h
index bad53961099..bad53961099 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Interactions.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Interactions.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Interactions.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Interactions.1.h
index dd3570e8a2e..dd3570e8a2e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Interactions.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Interactions.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Interactions.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Interactions.2.h
index ffbcf63170c..ffbcf63170c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Interactions.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Interactions.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Scenes.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Scenes.0.h
index 80a9741f40b..80a9741f40b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Scenes.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Scenes.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Scenes.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Scenes.1.h
index 7397f841096..7397f841096 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Scenes.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Scenes.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Scenes.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Scenes.2.h
index 975cc6ab012..975cc6ab012 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Composition.Scenes.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Composition.Scenes.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.0.h
index 4642e9bc120..4642e9bc120 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.1.h
index 1fb9f03824f..1fb9f03824f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.2.h
index bda17cd998d..bda17cd998d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.AnimationMetrics.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.AnimationMetrics.0.h
index d3fac5292b0..d3fac5292b0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.AnimationMetrics.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.AnimationMetrics.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.AnimationMetrics.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.AnimationMetrics.1.h
index cd658f2c1fd..cd658f2c1fd 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.AnimationMetrics.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.AnimationMetrics.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.AnimationMetrics.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.AnimationMetrics.2.h
index 1fe193c5414..1fe193c5414 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.AnimationMetrics.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.AnimationMetrics.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.Preview.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.Preview.0.h
index 98cf3ff1f9a..98cf3ff1f9a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.Preview.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.Preview.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.Preview.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.Preview.1.h
index 79d9ee15e87..79d9ee15e87 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.Preview.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.Preview.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.Preview.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.Preview.2.h
index 4981c8ed70f..4981c8ed70f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.Preview.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.Preview.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.Preview.Communications.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.Preview.Communications.0.h
index 019c27fd6ad..019c27fd6ad 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.Preview.Communications.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.Preview.Communications.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.Preview.Communications.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.Preview.Communications.1.h
index 1bb6cec7a21..1bb6cec7a21 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.Preview.Communications.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.Preview.Communications.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.Preview.Communications.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.Preview.Communications.2.h
index 0c6f59d3e85..0c6f59d3e85 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Core.Preview.Communications.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Core.Preview.Communications.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.0.h
index 036b0846b4c..036b0846b4c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.1.h
index 99e4b01a4ee..99e4b01a4ee 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.2.h
index e35a8423e75..e35a8423e75 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Core.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Core.0.h
index ca841edf6b0..ca841edf6b0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Core.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Core.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Core.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Core.1.h
index 2cb6f7e8b9f..2cb6f7e8b9f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Core.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Core.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Core.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Core.2.h
index 86632289a61..86632289a61 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Core.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Core.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.0.h
index 26ed566481a..26ed566481a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.1.h
index ce7ff79acf4..ce7ff79acf4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.2.h
index 96190e3dba0..96190e3dba0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Analysis.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Analysis.0.h
index 5ad57bc95a3..5ad57bc95a3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Analysis.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Analysis.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Analysis.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Analysis.1.h
index 498909898f3..498909898f3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Analysis.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Analysis.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Analysis.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Analysis.2.h
index e31af7a4103..e31af7a4103 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Analysis.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Analysis.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Core.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Core.0.h
index 561be0ca011..561be0ca011 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Core.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Core.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Core.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Core.1.h
index e03214d8e3e..e03214d8e3e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Core.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Core.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Core.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Core.2.h
index d3d49952159..d3d49952159 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Core.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Core.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Preview.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Preview.0.h
index 4df05611875..4df05611875 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Preview.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Preview.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Preview.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Preview.1.h
index 77bb616428a..77bb616428a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Preview.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Preview.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Preview.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Preview.2.h
index 852563123f5..852563123f5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Inking.Preview.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Inking.Preview.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Preview.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Preview.0.h
index 1149f418600..1149f418600 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Preview.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Preview.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Preview.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Preview.1.h
index eeaaa4859be..eeaaa4859be 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Preview.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Preview.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Preview.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Preview.2.h
index 6213bbb47f5..6213bbb47f5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Preview.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Preview.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Preview.Injection.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Preview.Injection.0.h
index 97294b59462..97294b59462 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Preview.Injection.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Preview.Injection.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Preview.Injection.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Preview.Injection.1.h
index c5f1205627f..c5f1205627f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Preview.Injection.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Preview.Injection.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Preview.Injection.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Preview.Injection.2.h
index d1f8c7794c2..d1f8c7794c2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Preview.Injection.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Preview.Injection.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Spatial.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Spatial.0.h
index a311c6397da..a311c6397da 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Spatial.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Spatial.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Spatial.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Spatial.1.h
index a85e4176a5e..a85e4176a5e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Spatial.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Spatial.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Spatial.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Spatial.2.h
index 0038dad9896..0038dad9896 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Input.Spatial.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Spatial.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Notifications.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Notifications.0.h
index 3cb801643da..3cb801643da 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Notifications.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Notifications.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Notifications.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Notifications.1.h
index ad8e2d7c267..ad8e2d7c267 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Notifications.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Notifications.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Notifications.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Notifications.2.h
index 119cb224630..119cb224630 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Notifications.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Notifications.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Notifications.Management.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Notifications.Management.0.h
index 80451bbd606..80451bbd606 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Notifications.Management.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Notifications.Management.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Notifications.Management.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Notifications.Management.1.h
index 8f62a5041b8..8f62a5041b8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Notifications.Management.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Notifications.Management.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Notifications.Management.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Notifications.Management.2.h
index 7f0e6fcb931..7f0e6fcb931 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Notifications.Management.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Notifications.Management.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Popups.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Popups.0.h
index 2d99e6cbfd3..2d99e6cbfd3 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Popups.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Popups.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Popups.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Popups.1.h
index 40fc4d1498c..40fc4d1498c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Popups.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Popups.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Popups.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Popups.2.h
index 69302e327bb..69302e327bb 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Popups.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Popups.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Shell.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Shell.0.h
index 9670de273d8..9670de273d8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Shell.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Shell.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Shell.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Shell.1.h
index 923f5b4c745..923f5b4c745 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Shell.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Shell.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Shell.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Shell.2.h
index 15ce0b9b926..15ce0b9b926 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Shell.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Shell.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.StartScreen.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.StartScreen.0.h
index 9079d4fd212..9079d4fd212 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.StartScreen.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.StartScreen.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.StartScreen.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.StartScreen.1.h
index dbfabf6281a..dbfabf6281a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.StartScreen.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.StartScreen.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.StartScreen.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.StartScreen.2.h
index 2ca89b956f4..2ca89b956f4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.StartScreen.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.StartScreen.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Text.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Text.0.h
index 291a15b0585..291a15b0585 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Text.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Text.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Text.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Text.1.h
index c100136065b..c100136065b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Text.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Text.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Text.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Text.2.h
index 926e90bbbee..926e90bbbee 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Text.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Text.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Text.Core.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Text.Core.0.h
index 3df8b2a51df..3df8b2a51df 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Text.Core.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Text.Core.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Text.Core.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Text.Core.1.h
index 27f7fff9f52..27f7fff9f52 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Text.Core.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Text.Core.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Text.Core.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Text.Core.2.h
index a5107061905..a5107061905 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Text.Core.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Text.Core.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.UIAutomation.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.UIAutomation.0.h
index 72ff367bb8b..72ff367bb8b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.UIAutomation.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.UIAutomation.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.UIAutomation.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.UIAutomation.1.h
index f9c34a6ad96..f9c34a6ad96 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.UIAutomation.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.UIAutomation.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.UIAutomation.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.UIAutomation.2.h
index 1dd15e65260..1dd15e65260 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.UIAutomation.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.UIAutomation.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.UIAutomation.Core.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.UIAutomation.Core.0.h
index f4c193145ea..f4c193145ea 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.UIAutomation.Core.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.UIAutomation.Core.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.UIAutomation.Core.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.UIAutomation.Core.1.h
index 92ea1f6aa3b..92ea1f6aa3b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.UIAutomation.Core.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.UIAutomation.Core.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.UIAutomation.Core.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.UIAutomation.Core.2.h
index 39152670d54..39152670d54 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.UIAutomation.Core.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.UIAutomation.Core.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ViewManagement.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ViewManagement.0.h
index b73031170a7..b73031170a7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ViewManagement.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ViewManagement.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ViewManagement.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ViewManagement.1.h
index e23d22e6805..e23d22e6805 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ViewManagement.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ViewManagement.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ViewManagement.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ViewManagement.2.h
index b5e30d4ba4c..b5e30d4ba4c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ViewManagement.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ViewManagement.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ViewManagement.Core.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ViewManagement.Core.0.h
index 2fe7debf8fd..2fe7debf8fd 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ViewManagement.Core.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ViewManagement.Core.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ViewManagement.Core.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ViewManagement.Core.1.h
index f94c83cf898..f94c83cf898 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ViewManagement.Core.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ViewManagement.Core.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ViewManagement.Core.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ViewManagement.Core.2.h
index 003c09209a4..003c09209a4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.ViewManagement.Core.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.ViewManagement.Core.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WebUI.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WebUI.0.h
index 217fdffb212..217fdffb212 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WebUI.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WebUI.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WebUI.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WebUI.1.h
index 75b3f14f64c..75b3f14f64c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WebUI.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WebUI.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WebUI.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WebUI.2.h
index 081c9f4b4ca..081c9f4b4ca 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WebUI.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WebUI.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WebUI.Core.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WebUI.Core.0.h
index a58636b95dc..a58636b95dc 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WebUI.Core.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WebUI.Core.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WebUI.Core.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WebUI.Core.1.h
index 70d1581d24b..70d1581d24b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WebUI.Core.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WebUI.Core.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WebUI.Core.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WebUI.Core.2.h
index 8c207af0a74..8c207af0a74 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WebUI.Core.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WebUI.Core.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WindowManagement.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WindowManagement.0.h
index 5aa03cb630a..5aa03cb630a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WindowManagement.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WindowManagement.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WindowManagement.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WindowManagement.1.h
index 528963a9ed7..528963a9ed7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WindowManagement.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WindowManagement.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WindowManagement.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WindowManagement.2.h
index c5dfddc882f..c5dfddc882f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WindowManagement.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WindowManagement.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WindowManagement.Preview.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WindowManagement.Preview.0.h
index 557f5a39558..557f5a39558 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WindowManagement.Preview.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WindowManagement.Preview.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WindowManagement.Preview.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WindowManagement.Preview.1.h
index e99496b1aec..e99496b1aec 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WindowManagement.Preview.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WindowManagement.Preview.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WindowManagement.Preview.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WindowManagement.Preview.2.h
index f9f6c9c04ba..f9f6c9c04ba 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.WindowManagement.Preview.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.WindowManagement.Preview.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.0.h
index b1b15587bcf..b1b15587bcf 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.1.h
index b16fbb3b85b..b16fbb3b85b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.2.h
index c248eab1bc4..c248eab1bc4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.0.h
index eaaf967ff1b..eaaf967ff1b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.1.h
index c606dea51fe..c606dea51fe 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.2.h
index 2a7f5f0b9bd..2a7f5f0b9bd 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Peers.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Peers.0.h
index 904d5e3569c..904d5e3569c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Peers.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Peers.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Peers.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Peers.1.h
index 3d2d2de9af0..3d2d2de9af0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Peers.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Peers.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Peers.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Peers.2.h
index b6cc708e709..b6cc708e709 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Peers.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Peers.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Provider.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Provider.0.h
index c9ea3036ac6..c9ea3036ac6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Provider.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Provider.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Provider.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Provider.1.h
index 49a2bab64d1..49a2bab64d1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Provider.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Provider.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Provider.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Provider.2.h
index e815ed15a80..e815ed15a80 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Provider.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Provider.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Text.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Text.0.h
index 38707b6079d..38707b6079d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Text.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Text.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Text.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Text.1.h
index d644892f9f6..d644892f9f6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Text.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Text.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Text.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Text.2.h
index 78a49947ff7..78a49947ff7 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Text.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Automation.Text.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.0.h
index 2b6ccc910d1..2b6ccc910d1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.1.h
index 5a6e4b1bfa4..5a6e4b1bfa4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.2.h
index f4d43e3fc3f..f4d43e3fc3f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Maps.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Maps.0.h
index d2f87e8d658..d2f87e8d658 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Maps.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Maps.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Maps.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Maps.1.h
index 1829c36ab08..1829c36ab08 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Maps.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Maps.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Maps.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Maps.2.h
index 4f5ca92bd79..4f5ca92bd79 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Maps.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Maps.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Primitives.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Primitives.0.h
index 3031f42193f..3031f42193f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Primitives.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Primitives.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Primitives.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Primitives.1.h
index 40c5308077e..40c5308077e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Primitives.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Primitives.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Primitives.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Primitives.2.h
index 37bd8ca3ba0..37bd8ca3ba0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Primitives.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Controls.Primitives.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Core.Direct.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Core.Direct.0.h
index dbbf2fc441a..dbbf2fc441a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Core.Direct.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Core.Direct.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Core.Direct.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Core.Direct.1.h
index 20c16216fe9..20c16216fe9 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Core.Direct.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Core.Direct.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Core.Direct.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Core.Direct.2.h
index 88ba4c01436..88ba4c01436 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Core.Direct.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Core.Direct.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Data.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Data.0.h
index 476da2600a5..476da2600a5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Data.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Data.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Data.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Data.1.h
index fb46a2e7a5a..fb46a2e7a5a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Data.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Data.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Data.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Data.2.h
index d7b72b05694..d7b72b05694 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Data.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Data.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Documents.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Documents.0.h
index 65e054ef380..65e054ef380 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Documents.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Documents.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Documents.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Documents.1.h
index f574c935842..f574c935842 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Documents.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Documents.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Documents.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Documents.2.h
index 8568b88f905..8568b88f905 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Documents.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Documents.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Hosting.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Hosting.0.h
index 553a8af4bcc..553a8af4bcc 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Hosting.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Hosting.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Hosting.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Hosting.1.h
index 74f4d02adc4..74f4d02adc4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Hosting.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Hosting.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Hosting.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Hosting.2.h
index 9f814bbf73f..9f814bbf73f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Hosting.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Hosting.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Input.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Input.0.h
index b0f97c270e9..b0f97c270e9 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Input.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Input.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Input.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Input.1.h
index b78bed38097..b78bed38097 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Input.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Input.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Input.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Input.2.h
index 5fe5da8f6cd..5fe5da8f6cd 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Input.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Input.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Interop.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Interop.0.h
index 0a7d59f2607..0a7d59f2607 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Interop.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Interop.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Interop.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Interop.1.h
index bbf5528a046..bbf5528a046 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Interop.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Interop.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Interop.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Interop.2.h
index 888e48da143..888e48da143 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Interop.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Interop.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Markup.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Markup.0.h
index 2f058cb64e6..2f058cb64e6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Markup.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Markup.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Markup.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Markup.1.h
index 8a41e43ef08..8a41e43ef08 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Markup.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Markup.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Markup.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Markup.2.h
index f2e20647119..f2e20647119 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Markup.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Markup.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.0.h
index 80541253a0f..80541253a0f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.1.h
index 7556e82052c..7556e82052c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.2.h
index 714fa2bcdc6..714fa2bcdc6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Animation.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Animation.0.h
index 1ef2163a80c..1ef2163a80c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Animation.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Animation.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Animation.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Animation.1.h
index 02013ca08db..02013ca08db 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Animation.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Animation.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Animation.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Animation.2.h
index 2abef3a7c51..2abef3a7c51 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Animation.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Animation.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Imaging.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Imaging.0.h
index bdc24e9d034..bdc24e9d034 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Imaging.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Imaging.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Imaging.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Imaging.1.h
index 62399e1f9d1..62399e1f9d1 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Imaging.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Imaging.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Imaging.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Imaging.2.h
index 14ce9935316..14ce9935316 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Imaging.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Imaging.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Media3D.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Media3D.0.h
index ddbb1c3d5c8..ddbb1c3d5c8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Media3D.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Media3D.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Media3D.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Media3D.1.h
index 95a10061c4f..95a10061c4f 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Media3D.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Media3D.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Media3D.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Media3D.2.h
index 35808240bf6..35808240bf6 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Media3D.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Media.Media3D.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Navigation.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Navigation.0.h
index 2ce67679e5d..2ce67679e5d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Navigation.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Navigation.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Navigation.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Navigation.1.h
index 66027aa70eb..66027aa70eb 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Navigation.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Navigation.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Navigation.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Navigation.2.h
index b3852c07cde..b3852c07cde 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Navigation.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Navigation.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Printing.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Printing.0.h
index 16a7145a442..16a7145a442 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Printing.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Printing.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Printing.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Printing.1.h
index 51bf273c22b..51bf273c22b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Printing.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Printing.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Printing.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Printing.2.h
index 30ae41e0de9..30ae41e0de9 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Printing.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Printing.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Resources.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Resources.0.h
index 1fb67985226..1fb67985226 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Resources.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Resources.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Resources.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Resources.1.h
index a796648c988..a796648c988 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Resources.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Resources.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Resources.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Resources.2.h
index c1ba29284be..c1ba29284be 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Resources.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Resources.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Shapes.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Shapes.0.h
index bf8fb675925..bf8fb675925 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Shapes.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Shapes.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Shapes.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Shapes.1.h
index 0aa2ece06a9..0aa2ece06a9 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Shapes.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Shapes.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Shapes.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Shapes.2.h
index db679e9afe8..db679e9afe8 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.UI.Xaml.Shapes.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Xaml.Shapes.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.0.h
index 7e281fc0d2a..7e281fc0d2a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.1.h
index 221f2b771ea..221f2b771ea 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.2.h
index 1cc1a6da40e..1cc1a6da40e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.AtomPub.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.AtomPub.0.h
index 2584af8bd2a..2584af8bd2a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.AtomPub.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.AtomPub.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.AtomPub.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.AtomPub.1.h
index 21cd15c584c..21cd15c584c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.AtomPub.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.AtomPub.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.AtomPub.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.AtomPub.2.h
index 1eba4a20bf2..1eba4a20bf2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.AtomPub.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.AtomPub.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.0.h
index 94709627540..94709627540 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.1.h
index 2077992c205..2077992c205 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.2.h
index 7df20d72c46..7df20d72c46 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Diagnostics.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Diagnostics.0.h
index 0e7a1605a9d..0e7a1605a9d 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Diagnostics.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Diagnostics.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Diagnostics.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Diagnostics.1.h
index 7047f5a3d3c..7047f5a3d3c 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Diagnostics.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Diagnostics.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Diagnostics.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Diagnostics.2.h
index 19991b29d8b..19991b29d8b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Diagnostics.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Diagnostics.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Filters.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Filters.0.h
index 0653baafa72..0653baafa72 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Filters.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Filters.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Filters.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Filters.1.h
index 7756e1f6dc2..7756e1f6dc2 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Filters.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Filters.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Filters.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Filters.2.h
index 0a322b94b2a..0a322b94b2a 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Filters.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Filters.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Headers.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Headers.0.h
index b7c1c28f902..b7c1c28f902 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Headers.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Headers.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Headers.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Headers.1.h
index a75e017fe29..a75e017fe29 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Headers.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Headers.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Headers.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Headers.2.h
index 3029b993fdb..3029b993fdb 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Http.Headers.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Http.Headers.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Syndication.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Syndication.0.h
index 919e5181fff..919e5181fff 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Syndication.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Syndication.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Syndication.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Syndication.1.h
index e4b12a4fc16..e4b12a4fc16 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Syndication.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Syndication.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Syndication.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Syndication.2.h
index 7e73831d053..7e73831d053 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.Syndication.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.Syndication.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.UI.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.UI.0.h
index 7a2d435e6de..7a2d435e6de 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.UI.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.UI.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.UI.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.UI.1.h
index 2ec7dea6841..2ec7dea6841 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.UI.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.UI.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.UI.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.UI.2.h
index 4777d0f47a5..4777d0f47a5 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.UI.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.UI.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.UI.Interop.0.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.UI.Interop.0.h
index e5acfcb330e..e5acfcb330e 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.UI.Interop.0.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.UI.Interop.0.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.UI.Interop.1.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.UI.Interop.1.h
index d361b2384d4..d361b2384d4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.UI.Interop.1.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.UI.Interop.1.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.UI.Interop.2.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.UI.Interop.2.h
index 2f174083d52..2f174083d52 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/impl/Windows.Web.UI.Interop.2.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/impl/Windows.Web.UI.Interop.2.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/winrt.ixx b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/winrt.ixx
index 7bc10cebd92..7bc10cebd92 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/generated/winrt/winrt.ixx
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/generated/winrt/winrt.ixx
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/input_file.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/input_file.h
new file mode 100644
index 00000000000..c9ac8792df2
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/input_file.h
@@ -0,0 +1,50 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_INPUT_FILE_H_
+#define PLATFORM_IMPL_WINDOWS_INPUT_FILE_H_
+
+#include "internal/platform/implementation/input_file.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/exception.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+// An InputFile represents a readable file on the system.
+class InputFile : public api::InputFile {
+ public:
+ // TODO(b/184975123): replace with real implementation.
+ ~InputFile() override = default;
+ // TODO(b/184975123): replace with real implementation.
+ std::string GetFilePath() const override { return "Un-implemented"; }
+ // TODO(b/184975123): replace with real implementation.
+ std::int64_t GetTotalSize() const override { return 0; }
+
+ // throws Exception::kIo
+ // TODO(b/184975123): replace with real implementation.
+ ExceptionOr<ByteArray> Read(std::int64_t size) override {
+ return ExceptionOr<ByteArray>(Exception::kFailed);
+ }
+ // throws Exception::kIo
+ // TODO(b/184975123): replace with real implementation.
+ Exception Close() override { return Exception{}; }
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_WINDOWS_INPUT_FILE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/input_file_test.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/input_file_test.cc
new file mode 100644
index 00000000000..7e5b7dd8aaf
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/input_file_test.cc
@@ -0,0 +1,152 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/windows/input_file.h"
+
+#include "gtest/gtest.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/payload_id.h"
+#include "internal/platform/implementation/windows/test_utils.h"
+#include "internal/platform/logging.h"
+
+class InputFileTests : public testing::Test {
+ protected:
+ // You can define per-test set-up logic as usual.
+ void SetUp() override {
+ location::nearby::PayloadId payloadId(TEST_PAYLOAD_ID);
+
+ hFile_ = CreateFileA(
+ test_utils::GetPayloadPath(payloadId).c_str(), // name of the write
+ GENERIC_WRITE, // open for writing
+ 0, // do not share
+ NULL, // default security
+ CREATE_ALWAYS, // create new file only
+ FILE_ATTRIBUTE_NORMAL, // normal file
+ NULL); // no attr. template
+
+ if (hFile_ == INVALID_HANDLE_VALUE) {
+ NEARBY_LOG(ERROR,
+ "Failed to create OutputFile with payloadId: %s and error: %d",
+ test_utils::GetPayloadPath(payloadId).c_str(), GetLastError());
+ }
+
+ const char* buffer = TEST_STRING;
+ DWORD bytesWritten;
+
+ WriteFile(hFile_, buffer, lstrlenA(buffer) * sizeof(char), &bytesWritten,
+ nullptr);
+
+ CloseHandle(hFile_);
+ }
+
+ // You can define per-test tear-down logic as usual.
+ void TearDown() override {
+ location::nearby::PayloadId payloadId(TEST_PAYLOAD_ID);
+ if (FileExists(test_utils::GetPayloadPath(payloadId).c_str())) {
+ DeleteFileA(test_utils::GetPayloadPath(payloadId).c_str());
+ }
+ }
+
+ BOOL FileExists(const char* szPath) {
+ DWORD dwAttrib = GetFileAttributesA(szPath);
+
+ return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
+ !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
+ }
+
+ private:
+ HANDLE hFile_ = nullptr;
+};
+
+TEST_F(InputFileTests, SuccessfulCreation) {
+ location::nearby::PayloadId payloadId(TEST_PAYLOAD_ID);
+ std::unique_ptr<location::nearby::api::InputFile> inputFile = nullptr;
+
+ inputFile = location::nearby::api::ImplementationPlatform::CreateInputFile(
+ payloadId, strlen(TEST_STRING));
+
+ EXPECT_NE(inputFile, nullptr);
+ EXPECT_EQ(inputFile->Close(),
+ location::nearby::Exception{location::nearby::Exception::kSuccess});
+}
+
+TEST_F(InputFileTests, SuccessfulGetFilePath) {
+ location::nearby::PayloadId payloadId(TEST_PAYLOAD_ID);
+ std::unique_ptr<location::nearby::api::InputFile> inputFile = nullptr;
+ std::string fileName;
+
+ inputFile = location::nearby::api::ImplementationPlatform::CreateInputFile(
+ payloadId, strlen(TEST_STRING));
+
+ fileName = inputFile->GetFilePath();
+
+ EXPECT_EQ(inputFile->Close(),
+ location::nearby::Exception{location::nearby::Exception::kSuccess});
+
+ EXPECT_EQ(fileName, test_utils::GetPayloadPath(payloadId).c_str());
+}
+
+TEST_F(InputFileTests, SuccessfulGetTotalSize) {
+ location::nearby::PayloadId payloadId(TEST_PAYLOAD_ID);
+ std::unique_ptr<location::nearby::api::InputFile> inputFile = nullptr;
+ int64_t size = -1;
+
+ inputFile = location::nearby::api::ImplementationPlatform::CreateInputFile(
+ payloadId, strlen(TEST_STRING));
+
+ size = inputFile->GetTotalSize();
+
+ EXPECT_EQ(inputFile->Close(),
+ location::nearby::Exception{location::nearby::Exception::kSuccess});
+
+ EXPECT_EQ(size, strlen(TEST_STRING));
+}
+
+TEST_F(InputFileTests, SuccessfulRead) {
+ location::nearby::PayloadId payloadId(TEST_PAYLOAD_ID);
+ std::unique_ptr<location::nearby::api::InputFile> inputFile = nullptr;
+
+ inputFile = location::nearby::api::ImplementationPlatform::CreateInputFile(
+ payloadId, strlen(TEST_STRING));
+
+ auto fileSize = inputFile->GetTotalSize();
+ auto dataRead = inputFile->Read(fileSize);
+
+ EXPECT_TRUE(dataRead.ok());
+ EXPECT_EQ(inputFile->Close(),
+ location::nearby::Exception{location::nearby::Exception::kSuccess});
+
+ EXPECT_STREQ(std::string(dataRead.result()).c_str(), TEST_STRING);
+}
+
+TEST_F(InputFileTests, FailedRead) {
+ location::nearby::PayloadId payloadId(TEST_PAYLOAD_ID);
+ std::unique_ptr<location::nearby::api::InputFile> inputFile = nullptr;
+
+ inputFile = location::nearby::api::ImplementationPlatform::CreateInputFile(
+ payloadId, strlen(TEST_STRING));
+
+ auto fileSize = inputFile->GetTotalSize();
+ EXPECT_NE(fileSize, -1);
+
+ auto dataRead = inputFile->Read(fileSize);
+ EXPECT_TRUE(dataRead.ok());
+
+ dataRead = inputFile->Read(fileSize);
+ std::string data = std::string(dataRead.result());
+
+ inputFile->Close();
+
+ EXPECT_STREQ(data.c_str(), "");
+}
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/listenable_future.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/listenable_future.h
new file mode 100644
index 00000000000..8c47ab5ad26
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/listenable_future.h
@@ -0,0 +1,41 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_LISTENABLE_FUTURE_H_
+#define PLATFORM_IMPL_WINDOWS_LISTENABLE_FUTURE_H_
+
+#include "internal/platform/implementation/listenable_future.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+// A Future that accepts completion listeners.
+//
+// https://guava.dev/releases/20.0/api/docs/com/google/common/util/concurrent/ListenableFuture.html
+template <typename T>
+class ListenableFuture : public api::ListenableFuture<T> {
+ public:
+ // TODO(b/184975123): replace with real implementation.
+ ~ListenableFuture() override = default;
+
+ // TODO(b/184975123): replace with real implementation.
+ void AddListener(Runnable runnable, api::Executor* executor) {}
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_WINDOWS_LISTENABLE_FUTURE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/log_message.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/log_message.cc
new file mode 100644
index 00000000000..f1632f932be
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/log_message.cc
@@ -0,0 +1,74 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/windows/log_message.h"
+
+#include <algorithm>
+// TODO(b/217211016): may need get rid of this dependency since there is
+// no "base" in OSS.
+#include "base/stringprintf.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+api::LogMessage::Severity min_log_severity_ = api::LogMessage::Severity::kInfo;
+
+inline absl::LogSeverity ConvertSeverity(api::LogMessage::Severity severity) {
+ switch (severity) {
+ // api::LogMessage::Severity kVerbose and kInfo is mapped to
+ // absl::LogSeverity kInfo since absl::LogSeverity doesn't have kVerbose
+ // level.
+ case api::LogMessage::Severity::kVerbose:
+ case api::LogMessage::Severity::kInfo:
+ return absl::LogSeverity::kInfo;
+ case api::LogMessage::Severity::kWarning:
+ return absl::LogSeverity::kWarning;
+ case api::LogMessage::Severity::kError:
+ return absl::LogSeverity::kError;
+ case api::LogMessage::Severity::kFatal:
+ return absl::LogSeverity::kFatal;
+ }
+}
+
+LogMessage::LogMessage(const char* file, int line, Severity severity)
+ : log_streamer_(ConvertSeverity(severity), file, line) {}
+
+LogMessage::~LogMessage() = default;
+
+void LogMessage::Print(const char* format, ...) {
+ va_list ap;
+ va_start(ap, format);
+ std::string result;
+ StringAppendV(&result, format, ap);
+ log_streamer_.stream() << result;
+ va_end(ap);
+}
+
+std::ostream& LogMessage::Stream() { return log_streamer_.stream(); }
+
+} // namespace windows
+
+namespace api {
+
+void LogMessage::SetMinLogSeverity(Severity severity) {
+ windows::min_log_severity_ = severity;
+}
+
+bool LogMessage::ShouldCreateLogMessage(Severity severity) {
+ return severity >= windows::min_log_severity_;
+}
+} // namespace api
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/log_message.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/log_message.h
new file mode 100644
index 00000000000..fe2bdf20e9f
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/log_message.h
@@ -0,0 +1,45 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_LOG_MESSAGE_H_
+#define PLATFORM_IMPL_WINDOWS_LOG_MESSAGE_H_
+
+#include "glog/logging.h"
+#include "internal/platform/implementation/log_message.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+// See documentation in
+// cpp/platform/api/log_message.h
+class LogMessage : public api::LogMessage {
+ public:
+ LogMessage(const char* file, int line, Severity severity);
+ ~LogMessage() override;
+
+ void Print(const char* format, ...) override;
+
+ std::ostream& Stream() override;
+
+ private:
+ google::LogMessage log_streamer_;
+ static api::LogMessage::Severity min_log_severity_;
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_WINDOWS_LOG_MESSAGE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/mutex.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/mutex.h
new file mode 100644
index 00000000000..42410827575
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/mutex.h
@@ -0,0 +1,72 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+#ifndef PLATFORM_IMPL_WINDOWS_MUTEX_H_
+#define PLATFORM_IMPL_WINDOWS_MUTEX_H_
+#include <windows.h>
+#include <stdio.h>
+#include <synchapi.h>
+
+#include <memory>
+#include <mutex> // NOLINT
+
+#include "absl/memory/memory.h"
+#include "absl/synchronization/mutex.h"
+#include "internal/platform/implementation/mutex.h"
+namespace location {
+namespace nearby {
+namespace windows {
+
+// A lock is a tool for controlling access to a shared resource by multiple
+// threads.
+// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/Lock.html
+class ABSL_LOCKABLE Mutex : public api::Mutex {
+ public:
+ explicit Mutex(Mode mode) : mode_(mode) {}
+ ~Mutex() override = default;
+ Mutex(Mutex&&) = delete;
+ Mutex& operator=(Mutex&&) = delete;
+ Mutex(const Mutex&) = delete;
+ Mutex& operator=(const Mutex&) = delete;
+
+ void Lock() ABSL_EXCLUSIVE_LOCK_FUNCTION() override {
+ if (mode_ == Mode::kRegularNoCheck) mutex_.ForgetDeadlockInfo();
+ if (mode_ == Mode::kRegular || mode_ == Mode::kRegularNoCheck) {
+ mutex_.Lock();
+ } else {
+ recursive_mutex_.lock();
+ }
+ }
+
+ void Unlock() ABSL_UNLOCK_FUNCTION() override {
+ if (mode_ == Mode::kRegular || mode_ == Mode::kRegularNoCheck) {
+ mutex_.Unlock();
+ } else {
+ recursive_mutex_.unlock();
+ }
+ }
+
+ absl::Mutex& GetMutex() { return mutex_; }
+ std::recursive_mutex& GetRecursiveMutex() { return recursive_mutex_; }
+
+ private:
+ friend class ConditionVariable;
+ absl::Mutex mutex_;
+ std::recursive_mutex recursive_mutex_; // The actual mutex allocation
+ Mode mode_;
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+#endif // PLATFORM_IMPL_WINDOWS_MUTEX_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/mutex_test.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/mutex_test.cc
new file mode 100644
index 00000000000..f8223a3ec3c
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/mutex_test.cc
@@ -0,0 +1,108 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/windows/mutex.h"
+
+#include <future> // NOLINT
+
+#include "gtest/gtest.h"
+
+class MutexTests : public testing::Test {
+ public:
+ class MutexTest {
+ public:
+ MutexTest(location::nearby::windows::Mutex& mutex) : mutex_(mutex) {}
+
+ std::future<bool> WaitForLock() { // NOLINT
+ return std::async(std::launch::async,
+ // for this lambda you need C++14
+ [this]() mutable {
+ absl::MutexLock::MutexLock(&mutex_.GetMutex());
+ return true;
+ });
+ }
+
+ void PostEvent() {
+ absl::MutexLock::MutexLock(&mutex_.GetMutex());
+ mutex_.Unlock();
+ }
+
+ private:
+ location::nearby::windows::Mutex& mutex_;
+ };
+};
+
+TEST_F(MutexTests, SuccessfulRecursiveCreation) {
+ // Arrange
+ location::nearby::windows::Mutex mutex = location::nearby::windows::Mutex(
+ location::nearby::windows::Mutex::Mode::kRecursive);
+
+ // Act
+ std::recursive_mutex& actual = mutex.GetRecursiveMutex();
+
+ // Assert
+ ASSERT_TRUE(actual.native_handle() != nullptr);
+}
+
+TEST_F(MutexTests, SuccessfulCreation) {
+ // Arrange
+ location::nearby::windows::Mutex mutex(
+ location::nearby::windows::Mutex::Mode::kRegular);
+
+ // Act
+ absl::Mutex& actual = mutex.GetMutex();
+
+ // Assert
+ ASSERT_TRUE(&actual != nullptr);
+}
+
+TEST_F(MutexTests, SuccessfulSignal) {
+ // Arrange
+ location::nearby::windows::Mutex mutex(
+ location::nearby::windows::Mutex::Mode::kRegular);
+
+ location::nearby::windows::Mutex& mutexRef = mutex;
+ MutexTest mutexTest(mutexRef);
+
+ mutex.Lock();
+
+ // Act
+ auto result = mutexTest.WaitForLock();
+ mutex.Unlock();
+
+ // Assert
+ ASSERT_TRUE(result.get());
+}
+
+TEST_F(MutexTests, SuccessfulRecursiveSignal) {
+ // Arrange
+ location::nearby::windows::Mutex mutex(
+ location::nearby::windows::Mutex::Mode::kRecursive);
+
+ location::nearby::windows::Mutex& mutexRef = mutex;
+ MutexTest mutexTest(mutexRef);
+
+ mutex.Lock();
+ mutex.Lock();
+ mutex.Lock();
+
+ // Act
+ auto result = mutexTest.WaitForLock();
+ mutex.Unlock();
+ mutex.Unlock();
+ mutex.Unlock();
+
+ // Assert
+ ASSERT_TRUE(result.get());
+}
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/output_file.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/output_file.h
new file mode 100644
index 00000000000..764907d1e5b
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/output_file.h
@@ -0,0 +1,47 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_OUTPUT_FILE_H_
+#define PLATFORM_IMPL_WINDOWS_OUTPUT_FILE_H_
+
+#include "internal/platform/implementation/output_file.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/exception.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+// An OutputFile represents a writable file on the system.
+class OutputFile : public api::OutputFile {
+ public:
+ // TODO(b/184975123): replace with real implementation.
+ ~OutputFile() override = default;
+
+ // throws Exception::kIo
+ // TODO(b/184975123): replace with real implementation.
+ Exception Write(const ByteArray& data) override { return Exception{}; }
+ // throws Exception::kIo
+ // TODO(b/184975123): replace with real implementation.
+ Exception Flush() override { return Exception{}; }
+ // throws Exception::kIo
+ // TODO(b/184975123): replace with real implementation.
+ Exception Close() override { return Exception{}; }
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_WINDOWS_OUTPUT_FILE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/output_file_test.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/output_file_test.cc
new file mode 100644
index 00000000000..034bc7bdc77
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/output_file_test.cc
@@ -0,0 +1,90 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/windows/output_file.h"
+
+#include "gtest/gtest.h"
+#include "internal/platform/implementation/platform.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/payload_id.h"
+#include "internal/platform/implementation/windows/test_utils.h"
+
+class OutputFileTests : public testing::Test {
+ protected:
+ // You can define per-test set-up logic as usual.
+ void SetUp() override {
+ location::nearby::PayloadId payloadId(TEST_PAYLOAD_ID);
+ if (FileExists(test_utils::GetPayloadPath(payloadId).c_str())) {
+ DeleteFileA(test_utils::GetPayloadPath(payloadId).c_str());
+ }
+ }
+
+ // You can define per-test tear-down logic as usual.
+ void TearDown() override {
+ location::nearby::PayloadId payloadId(TEST_PAYLOAD_ID);
+ if (FileExists(test_utils::GetPayloadPath(payloadId).c_str())) {
+ DeleteFileA(test_utils::GetPayloadPath(payloadId).c_str());
+ }
+ }
+
+ BOOL FileExists(const char* szPath) {
+ DWORD dwAttrib = GetFileAttributesA(szPath);
+
+ return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
+ !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
+ }
+};
+
+TEST_F(OutputFileTests, SuccessfulCreation) {
+ location::nearby::PayloadId payloadId(TEST_PAYLOAD_ID);
+ std::unique_ptr<location::nearby::api::OutputFile> outputFile = nullptr;
+
+ EXPECT_NO_THROW(
+ outputFile =
+ location::nearby::api::ImplementationPlatform::CreateOutputFile(
+ payloadId));
+
+ EXPECT_NE(outputFile, nullptr);
+ EXPECT_NO_THROW(outputFile->Close());
+}
+
+TEST_F(OutputFileTests, SuccessfulClose) {
+ location::nearby::PayloadId payloadId(TEST_PAYLOAD_ID);
+ std::unique_ptr<location::nearby::api::OutputFile> outputFile = nullptr;
+
+ EXPECT_NO_THROW(
+ outputFile =
+ location::nearby::api::ImplementationPlatform::CreateOutputFile(
+ payloadId));
+
+ EXPECT_NO_THROW(outputFile->Close());
+
+ DeleteFileA(test_utils::GetPayloadPath(payloadId).c_str());
+}
+
+TEST_F(OutputFileTests, SuccessfulWrite) {
+ location::nearby::PayloadId payloadId(TEST_PAYLOAD_ID);
+ location::nearby::ByteArray data(std::string(TEST_STRING));
+ std::unique_ptr<location::nearby::api::OutputFile> outputFile = nullptr;
+
+ EXPECT_NO_THROW(
+ outputFile =
+ location::nearby::api::ImplementationPlatform::CreateOutputFile(
+ payloadId));
+
+ EXPECT_NO_THROW(outputFile->Write(data));
+ EXPECT_NO_THROW(outputFile->Close());
+
+ DeleteFileA(test_utils::GetPayloadPath(payloadId).c_str());
+}
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/platform.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/platform.cc
new file mode 100644
index 00000000000..c98dfbd293b
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/platform.cc
@@ -0,0 +1,177 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/platform.h"
+
+#include <shlobj.h>
+
+#include "internal/platform/implementation/shared/count_down_latch.h"
+#include "internal/platform/implementation/shared/file.h"
+#include "internal/platform/implementation/windows/atomic_boolean.h"
+#include "internal/platform/implementation/windows/atomic_reference.h"
+#include "internal/platform/implementation/windows/ble.h"
+#include "internal/platform/implementation/windows/bluetooth_adapter.h"
+#include "internal/platform/implementation/windows/bluetooth_classic_medium.h"
+#include "internal/platform/implementation/windows/cancelable.h"
+#include "internal/platform/implementation/windows/condition_variable.h"
+#include "internal/platform/implementation/windows/executor.h"
+#include "internal/platform/implementation/windows/future.h"
+#include "internal/platform/implementation/windows/listenable_future.h"
+#include "internal/platform/implementation/windows/log_message.h"
+#include "internal/platform/implementation/windows/mutex.h"
+#include "internal/platform/implementation/windows/scheduled_executor.h"
+#include "internal/platform/implementation/windows/server_sync.h"
+#include "internal/platform/implementation/windows/settable_future.h"
+#include "internal/platform/implementation/windows/submittable_executor.h"
+#include "internal/platform/implementation/windows/webrtc.h"
+#include "internal/platform/implementation/windows/wifi.h"
+#include "internal/platform/implementation/windows/wifi_lan.h"
+
+namespace location {
+namespace nearby {
+namespace api {
+namespace {
+
+std::string GetPayloadPath(PayloadId payload_id) {
+ PWSTR basePath;
+
+ // Retrieves the full path of a known folder identified by the folder's
+ // KNOWNFOLDERID.
+ // https://docs.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetknownfolderpath
+ SHGetKnownFolderPath(
+ FOLDERID_Downloads, // rfid: A reference to the KNOWNFOLDERID that
+ // identifies the folder.
+ 0, // dwFlags: Flags that specify special retrieval options.
+ NULL, // hToken: An access token that represents a particular user.
+ &basePath); // ppszPath: When this method returns, contains the address
+ // of a pointer to a null-terminated Unicode string that
+ // specifies the path of the known folder. The calling
+ // process is responsible for freeing this resource once it
+ // is no longer needed by calling CoTaskMemFree, whether
+ // SHGetKnownFolderPath succeeds or not.
+ size_t bufferSize;
+ wcstombs_s(&bufferSize, NULL, 0, basePath, 0);
+ char* fullpathUTF8 = new char[bufferSize + 1];
+ memset(fullpathUTF8, 0, bufferSize);
+ wcstombs_s(&bufferSize, fullpathUTF8, bufferSize, basePath, bufferSize - 1);
+ std::string fullPath = std::string(fullpathUTF8);
+ auto retval = absl::StrCat(fullPath += "\\", payload_id);
+ delete[] fullpathUTF8;
+ return retval;
+}
+} // namespace
+
+std::unique_ptr<AtomicBoolean> ImplementationPlatform::CreateAtomicBoolean(
+ bool initial_value) {
+ return absl::make_unique<windows::AtomicBoolean>();
+}
+
+std::unique_ptr<AtomicUint32> ImplementationPlatform::CreateAtomicUint32(
+ std::uint32_t value) {
+ return absl::make_unique<windows::AtomicUint32>();
+}
+
+std::unique_ptr<CountDownLatch> ImplementationPlatform::CreateCountDownLatch(
+ std::int32_t count) {
+ return absl::make_unique<shared::CountDownLatch>(count);
+}
+
+std::unique_ptr<Mutex> ImplementationPlatform::CreateMutex(Mutex::Mode mode) {
+ return absl::make_unique<windows::Mutex>(mode);
+}
+
+std::unique_ptr<ConditionVariable>
+ImplementationPlatform::CreateConditionVariable(Mutex* mutex) {
+ return absl::make_unique<windows::ConditionVariable>(mutex);
+}
+
+std::unique_ptr<InputFile> ImplementationPlatform::CreateInputFile(
+ PayloadId payload_id, std::int64_t total_size) {
+ return shared::IOFile::CreateInputFile(GetPayloadPath(payload_id),
+ total_size);
+}
+
+std::unique_ptr<OutputFile> ImplementationPlatform::CreateOutputFile(
+ PayloadId payload_id) {
+ return shared::IOFile::CreateOutputFile(GetPayloadPath(payload_id));
+}
+
+// TODO(b/184975123): replace with real implementation.
+std::unique_ptr<LogMessage> ImplementationPlatform::CreateLogMessage(
+ const char* file, int line, LogMessage::Severity severity) {
+ return absl::make_unique<windows::LogMessage>(file, line, severity);
+}
+
+std::unique_ptr<SubmittableExecutor>
+ImplementationPlatform::CreateSingleThreadExecutor() {
+ return absl::make_unique<windows::SubmittableExecutor>();
+}
+
+std::unique_ptr<SubmittableExecutor>
+ImplementationPlatform::CreateMultiThreadExecutor(
+ std::int32_t max_concurrency) {
+ return absl::make_unique<windows::SubmittableExecutor>(max_concurrency);
+}
+
+std::unique_ptr<ScheduledExecutor>
+ImplementationPlatform::CreateScheduledExecutor() {
+ return absl::make_unique<windows::ScheduledExecutor>();
+}
+
+std::unique_ptr<BluetoothAdapter>
+ImplementationPlatform::CreateBluetoothAdapter() {
+ return absl::make_unique<windows::BluetoothAdapter>();
+}
+
+std::unique_ptr<BluetoothClassicMedium>
+ImplementationPlatform::CreateBluetoothClassicMedium(
+ nearby::api::BluetoothAdapter& adapter) {
+ return absl::make_unique<windows::BluetoothClassicMedium>(adapter);
+}
+
+// TODO(b/184975123): replace with real implementation.
+std::unique_ptr<BleMedium> ImplementationPlatform::CreateBleMedium(
+ BluetoothAdapter& adapter) {
+ return absl::make_unique<windows::BleMedium>();
+}
+
+// TODO(b/184975123): replace with real implementation.
+std::unique_ptr<ble_v2::BleMedium> ImplementationPlatform::CreateBleV2Medium(
+ BluetoothAdapter&) {
+ return nullptr;
+}
+
+// TODO(b/184975123): replace with real implementation.
+std::unique_ptr<ServerSyncMedium>
+ImplementationPlatform::CreateServerSyncMedium() {
+ return std::unique_ptr<windows::ServerSyncMedium>();
+}
+
+// TODO(b/184975123): replace with real implementation.
+std::unique_ptr<WifiMedium> ImplementationPlatform::CreateWifiMedium() {
+ return std::unique_ptr<WifiMedium>();
+}
+
+std::unique_ptr<WifiLanMedium> ImplementationPlatform::CreateWifiLanMedium() {
+ return absl::make_unique<windows::WifiLanMedium>();
+}
+
+// TODO(b/184975123): replace with real implementation.
+std::unique_ptr<WebRtcMedium> ImplementationPlatform::CreateWebRtcMedium() {
+ return absl::make_unique<windows::WebRtcMedium>();
+}
+
+} // namespace api
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/runner.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/runner.h
new file mode 100644
index 00000000000..c6d414c02c6
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/runner.h
@@ -0,0 +1,42 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_RUNNER_H_
+#define PLATFORM_IMPL_WINDOWS_RUNNER_H_
+
+#include "internal/platform/runnable.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+class ThreadPool;
+
+class Runner {
+ public:
+ Runner(std::function<void()> runnable)
+ : thread_pool_(nullptr), runnable_(runnable) {}
+ void Run() { runnable_(); }
+ ~Runner(){}
+ ThreadPool* thread_pool_;
+
+ private:
+ std::function<void()> runnable_;
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_WINDOWS_RUNNER_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/scheduled_executor.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/scheduled_executor.cc
new file mode 100644
index 00000000000..83d6cb4e737
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/scheduled_executor.cc
@@ -0,0 +1,149 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/windows/scheduled_executor.h"
+
+#include "internal/platform/implementation/windows/cancelable.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+class ScheduledExecutorException : public std::runtime_error {
+ public:
+ ScheduledExecutorException() : std::runtime_error("") {}
+ ScheduledExecutorException(const std::string& message)
+ : std::runtime_error(message) {}
+ virtual const char* what() const throw() {
+ return "WaitableTimer creation failed";
+ }
+};
+
+class TimerData {
+ public:
+ TimerData(ScheduledExecutor* scheduledExecutor,
+ std::function<void()> runnable, HANDLE waitableTimer)
+ : scheduled_executor_(scheduledExecutor),
+ runnable_(std::move(runnable)),
+ waitable_timer_handle_(waitableTimer) {}
+
+ ScheduledExecutor* GetScheduledExecutor() { return scheduled_executor_; }
+ std::function<void()> GetRunnable() { return runnable_; }
+ HANDLE GetWaitableTimerHandle() { return waitable_timer_handle_; }
+
+ private:
+ ScheduledExecutor* scheduled_executor_;
+ std::function<void()> runnable_;
+ HANDLE waitable_timer_handle_;
+};
+
+void WINAPI ScheduledExecutor::_TimerProc(LPVOID argToCompletionRoutine,
+ DWORD dwTimerLowValue,
+ DWORD dwTimerHighValue) {
+ TimerData* timerData;
+ DWORD threadId = GetCurrentThreadId();
+
+ _ASSERT(argToCompletionRoutine != NULL);
+ if (NULL == argToCompletionRoutine) {
+ NEARBY_LOGS(ERROR)
+ << __func__
+ << ": TimerProc argument argToCompletionRoutine was null.";
+
+ return;
+ }
+
+ timerData = static_cast<TimerData*>(argToCompletionRoutine);
+ timerData->GetScheduledExecutor()->Execute(timerData->GetRunnable());
+
+ // Get the waitable timer and destroy it
+ CloseHandle(timerData->GetWaitableTimerHandle());
+ free(timerData);
+ return;
+}
+
+ScheduledExecutor::ScheduledExecutor()
+ : executor_(std::make_unique<nearby::windows::Executor>()),
+ shut_down_(false) {}
+
+// Cancelable is kept both in the executor context, and in the caller context.
+// We want Cancelable to live until both caller and executor are done with it.
+// Exclusive ownership model does not work for this case;
+// using std:shared_ptr<> instead of std::unique_ptr<>.
+std::shared_ptr<api::Cancelable> ScheduledExecutor::Schedule(
+ Runnable&& runnable, absl::Duration duration) {
+ if (shut_down_) {
+ NEARBY_LOGS(ERROR)
+ << __func__
+ << ": Attempt to Schedule on a shut down executor.";
+
+ return nullptr;
+ }
+
+ // Create the waitable timer
+ // Create a name for this timer
+ // TODO: (jfcarroll) construct a timer name based on ??
+ char buffer[TIMER_NAME_BUFFER_SIZE];
+
+ snprintf(buffer, TIMER_NAME_BUFFER_SIZE, "PID:%ld", GetCurrentProcessId());
+
+ HANDLE waitableTimer = CreateWaitableTimerA(NULL, true, buffer);
+
+ if (waitableTimer == NULL) {
+ throw ScheduledExecutorException("WaitableTimer creation failed");
+ }
+
+ waitable_timers_.push_back(waitableTimer);
+
+ // Create the delay value - due time
+ LARGE_INTEGER dueTime;
+ dueTime.QuadPart = -(absl::ToChronoNanoseconds(duration).count() / 100);
+
+ TimerData* timerData = new TimerData(this, runnable, waitableTimer);
+
+ BOOL result = SetWaitableTimer(waitableTimer, &dueTime, 0, _TimerProc,
+ timerData, false);
+
+ if (result == 0) {
+ NEARBY_LOGS(ERROR) << "Error: " << __func__ << ": Failed to set the timer.";
+ return nullptr;
+ }
+
+ return std::make_shared<nearby::windows::Cancelable>(waitableTimer);
+}
+
+// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-
+void ScheduledExecutor::Execute(Runnable&& runnable) {
+ if (shut_down_) {
+ NEARBY_LOGS(ERROR) << __func__
+ << ": Attempt to Execute on a shut down executor.";
+ return;
+ }
+
+ executor_->Execute(std::move(runnable));
+}
+
+// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#shutdown--
+void ScheduledExecutor::Shutdown() {
+ if (!shut_down_) {
+ shut_down_ = true;
+ executor_->Shutdown();
+ return;
+ }
+ NEARBY_LOGS(ERROR) << __func__
+ << ": Attempt to Shutdown on a shut down executor.";
+}
+} // namespace windows
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/scheduled_executor.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/scheduled_executor.h
new file mode 100644
index 00000000000..109d6618e44
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/scheduled_executor.h
@@ -0,0 +1,65 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_SCHEDULED_EXECUTOR_H_
+#define PLATFORM_IMPL_WINDOWS_SCHEDULED_EXECUTOR_H_
+
+#include <windows.h>
+
+#include "internal/platform/implementation/scheduled_executor.h"
+#include "internal/platform/implementation/windows/executor.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+#define TIMER_NAME_BUFFER_SIZE 64
+
+// An Executor that can schedule commands to run after a given delay, or to
+// execute periodically.
+//
+// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html
+class ScheduledExecutor : public api::ScheduledExecutor {
+ public:
+ ScheduledExecutor();
+
+ ~ScheduledExecutor() override = default;
+
+ // Cancelable is kept both in the executor context, and in the caller context.
+ // We want Cancelable to live until both caller and executor are done with it.
+ // Exclusive ownership model does not work for this case;
+ // using std:shared_ptr<> instead if std::unique_ptr<>.
+ std::shared_ptr<api::Cancelable> Schedule(Runnable&& runnable,
+ absl::Duration duration) override;
+
+ // https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-
+ void Execute(Runnable&& runnable) override;
+
+ // https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#shutdown--
+ void Shutdown() override;
+
+ private:
+ static void WINAPI _TimerProc(LPVOID lpArgToCompletionRoutine,
+ DWORD dwTimerLowValue, DWORD dwTimerHighValue);
+
+ std::unique_ptr<nearby::windows::Executor> executor_;
+ std::vector<HANDLE> waitable_timers_;
+ std::atomic_bool shut_down_;
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_WINDOWS_SCHEDULED_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/scheduled_executor_test.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/scheduled_executor_test.cc
new file mode 100644
index 00000000000..d9126d3ae08
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/scheduled_executor_test.cc
@@ -0,0 +1,174 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+#include "internal/platform/implementation/windows/scheduled_executor.h"
+
+#include <utility>
+
+#include "internal/platform/implementation/windows/test_data.h"
+
+#include "gtest/gtest.h"
+
+TEST(ScheduledExecutorTests, ExecuteSucceeds) {
+ // Arrange
+ std::string expected(RUNNABLE_0_TEXT.c_str());
+
+ std::unique_ptr<location::nearby::windows::ScheduledExecutor>
+ submittableExecutor =
+ std::make_unique<location::nearby::windows::ScheduledExecutor>();
+ std::string output = std::string();
+ // Container to note threads that ran
+ std::unique_ptr<std::vector<DWORD>> threadIds =
+ std::make_unique<std::vector<DWORD>>();
+
+ threadIds->push_back(GetCurrentThreadId());
+
+ // Act
+ submittableExecutor->Execute([&output, &threadIds]() {
+ threadIds->push_back(GetCurrentThreadId());
+ output.append(RUNNABLE_0_TEXT.c_str());
+ });
+
+ submittableExecutor->Shutdown();
+
+ // Assert
+ // We should've run 1 time on the main thread, and 1 times on the
+ // workerThread
+ ASSERT_EQ(threadIds->size(), 2);
+ // We should still be on the main thread
+ ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
+ // We should've run all runnables on the worker thread
+ ASSERT_EQ(output, expected);
+}
+
+TEST(ScheduledExecutorTests, ScheduleSucceeds) {
+ // Arrange
+ std::string expected(RUNNABLE_0_TEXT.c_str());
+
+ std::unique_ptr<location::nearby::windows::ScheduledExecutor>
+ submittableExecutor =
+ std::make_unique<location::nearby::windows::ScheduledExecutor>();
+ std::string output = std::string();
+ // Container to note threads that ran
+ std::unique_ptr<std::vector<DWORD>> threadIds =
+ std::make_unique<std::vector<DWORD>>();
+
+ threadIds->push_back(GetCurrentThreadId());
+
+ std::chrono::system_clock::time_point timeNow =
+ std::chrono::system_clock::now();
+ std::chrono::system_clock::time_point timeExecuted;
+
+ // Act
+ submittableExecutor->Schedule(
+ [&output, &threadIds, &timeExecuted]() {
+ timeExecuted = std::chrono::system_clock::now();
+ threadIds->push_back(GetCurrentThreadId());
+ output.append(RUNNABLE_0_TEXT.c_str());
+ },
+ absl::Milliseconds(50));
+
+ SleepEx(100, true); // Yield the thread
+
+ submittableExecutor->Shutdown();
+
+ auto difference = std::chrono::duration_cast<std::chrono::milliseconds>(
+ timeExecuted - timeNow)
+ .count();
+
+ // Assert
+ // We should've run 1 time on the main thread, and 1 times on the
+ // workerThread
+ ASSERT_TRUE(difference >= 50) << "difference was: " << difference;
+ ASSERT_TRUE(difference < 100) << "difference was: " << difference;
+
+ ASSERT_EQ(threadIds->size(), 2);
+ // We should still be on the main thread
+ ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
+ // We should've run all runnables on the worker thread
+ ASSERT_EQ(output, expected);
+}
+
+TEST(ScheduledExecutorTests, CancelSucceeds) {
+ // Arrange
+ std::string expected("");
+
+ std::unique_ptr<location::nearby::windows::ScheduledExecutor>
+ submittableExecutor =
+ std::make_unique<location::nearby::windows::ScheduledExecutor>();
+ std::string output = std::string();
+ // Container to note threads that ran
+ std::unique_ptr<std::vector<DWORD>> threadIds =
+ std::make_unique<std::vector<DWORD>>();
+
+ threadIds->push_back(GetCurrentThreadId());
+
+ // Act
+ auto cancelable = submittableExecutor->Schedule(
+ [&output, &threadIds]() {
+ threadIds->push_back(GetCurrentThreadId());
+ output.append(RUNNABLE_0_TEXT.c_str());
+ },
+ absl::Milliseconds(1000));
+
+ SleepEx(100, true); // Yield the thread
+
+ auto actual = cancelable->Cancel();
+
+ submittableExecutor->Shutdown();
+
+ // Assert
+ ASSERT_TRUE(actual);
+ ASSERT_EQ(threadIds->size(), 1);
+ // We should still be on the main thread
+ ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
+ // We should've run all runnables on the worker thread
+ ASSERT_EQ(output, expected);
+}
+
+TEST(ScheduledExecutorTests, CancelAfterStartedFails) {
+ // Arrange
+ std::string expected(RUNNABLE_0_TEXT.c_str());
+
+ std::unique_ptr<location::nearby::windows::ScheduledExecutor>
+ submittableExecutor =
+ std::make_unique<location::nearby::windows::ScheduledExecutor>();
+ std::string output = std::string();
+ // Container to note threads that ran
+ std::unique_ptr<std::vector<DWORD>> threadIds =
+ std::make_unique<std::vector<DWORD>>();
+
+ threadIds->push_back(GetCurrentThreadId());
+
+ // Act
+ auto cancelable = submittableExecutor->Schedule(
+ [&output, &threadIds]() {
+ threadIds->push_back(GetCurrentThreadId());
+ output.append(RUNNABLE_0_TEXT.c_str());
+ },
+ absl::Milliseconds(100));
+
+ SleepEx(1000, true); // Yield the thread
+
+ auto actual = cancelable->Cancel();
+
+ submittableExecutor->Shutdown();
+
+ // Assert
+ ASSERT_FALSE(actual);
+ ASSERT_EQ(threadIds->size(), 2);
+ // We should still be on the main thread
+ ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
+ // We should've run all runnables on the worker thread
+ ASSERT_EQ(output, expected);
+}
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/server_sync.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/server_sync.h
new file mode 100644
index 00000000000..95dd30b27cd
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/server_sync.h
@@ -0,0 +1,90 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_SERVER_SYNC_H_
+#define PLATFORM_IMPL_WINDOWS_SERVER_SYNC_H_
+
+#include "internal/platform/implementation/server_sync.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+// Abstraction that represents a Nearby endpoint exchanging data through
+// ServerSync Medium.
+class ServerSyncDevice : public api::ServerSyncDevice {
+ public:
+ // TODO(b/184975123): replace with real implementation.
+ ~ServerSyncDevice() override = default;
+
+ // TODO(b/184975123): replace with real implementation.
+ std::string GetName() const override { return "Un-implemented"; }
+ // TODO(b/184975123): replace with real implementation.
+ std::string GetGuid() const override { return "Un-implemented"; }
+ // TODO(b/184975123): replace with real implementation.
+ std::string GetOwnGuid() const override { return "Un-implemented"; }
+};
+
+// Container of operations that can be performed over the Chrome Sync medium.
+class ServerSyncMedium : public api::ServerSyncMedium {
+ public:
+ // TODO(b/184975123): replace with real implementation.
+ ~ServerSyncMedium() override = default;
+
+ // TODO(b/184975123): replace with real implementation.
+ bool StartAdvertising(absl::string_view service_id,
+ absl::string_view endpoint_id,
+ const ByteArray& endpoint_info) override {
+ return false;
+ }
+ // TODO(b/184975123): replace with real implementation.
+ void StopAdvertising(absl::string_view service_id) override {}
+
+ class DiscoveredDeviceCallback
+ : public api::ServerSyncMedium::DiscoveredDeviceCallback {
+ public:
+ // TODO(b/184975123): replace with real implementation.
+ ~DiscoveredDeviceCallback() override = default;
+
+ // Called on a new ServerSyncDevice discovery.
+ // TODO(b/184975123): replace with real implementation.
+ void OnDeviceDiscovered(api::ServerSyncDevice* device,
+ absl::string_view service_id,
+ absl::string_view endpoint_id,
+ const ByteArray& endpoint_info) override {}
+ // Called when ServerSyncDevice is no longer reachable.
+ // TODO(b/184975123): replace with real implementation.
+ void OnDeviceLost(api::ServerSyncDevice* device,
+ absl::string_view service_id) override {}
+ };
+
+ // Returns true once the Chrome Sync scan has been initiated.
+ // TODO(b/184975123): replace with real implementation.
+ bool StartDiscovery(absl::string_view service_id,
+ const api::ServerSyncMedium::DiscoveredDeviceCallback&
+ discovered_device_callback) override {
+ return false;
+ }
+ // Returns true once Chrome Sync scan for service_id is well and truly
+ // stopped; after this returns, there must be no more invocations of the
+ // DiscoveredDeviceCallback passed in to startScanning() for service_id.
+ // TODO(b/184975123): replace with real implementation.
+ void StopDiscovery(absl::string_view service_id) override {}
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_WINDOWS_SERVER_SYNC_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/settable_future.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/settable_future.h
new file mode 100644
index 00000000000..15323ead080
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/settable_future.h
@@ -0,0 +1,51 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_SETTABLE_FUTURE_H_
+#define PLATFORM_IMPL_WINDOWS_SETTABLE_FUTURE_H_
+
+#include "internal/platform/implementation/settable_future.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+// A SettableFuture is a type of Future whose result can be set.
+//
+// https://google.github.io/guava/releases/20.0/api/docs/com/google/common/util/concurrent/SettableFuture.html
+template <typename T>
+class SettableFuture : public api::SettableFuture<T> {
+ public:
+ // TODO(b/184975123): replace with real implementation.
+ ~SettableFuture() override = default;
+
+ // Completes the future successfully. The value is returned to any waiters.
+ // Returns true, if value was set.
+ // Returns false, if Future is already in "done" state.
+ // TODO(b/184975123): replace with real implementation.
+ bool Set(T value) override { return false; }
+
+ // Completes the future unsuccessfully. The exception value is returned to any
+ // waiters.
+ // Returns true, if exception was set.
+ // Returns false, if Future is already in "done" state.
+ // TODO(b/184975123): replace with real implementation.
+ bool SetException(Exception exception) override { return false; }
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_WINDOWS_SETTABLE_FUTURE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/submittable_executor.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/submittable_executor.cc
new file mode 100644
index 00000000000..a6a7b01011b
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/submittable_executor.cc
@@ -0,0 +1,65 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/windows/submittable_executor.h"
+
+#include "internal/platform/implementation/windows/executor.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+SubmittableExecutor::SubmittableExecutor() : SubmittableExecutor(1) {}
+
+SubmittableExecutor::SubmittableExecutor(int32_t max_concurrancy)
+ : executor_(std::make_unique<nearby::windows::Executor>(max_concurrancy)),
+ shut_down_(false) {}
+
+bool SubmittableExecutor::DoSubmit(Runnable&& wrapped_callable) {
+ if (!shut_down_) {
+ executor_->Execute(std::move(wrapped_callable));
+ return true;
+ }
+
+ NEARBY_LOGS(ERROR) << "Error: " << __func__
+ << ": Attempt to DoSubmit on a shutdown executor.";
+
+ return false;
+}
+
+// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-
+void SubmittableExecutor::Execute(Runnable&& runnable) {
+ if (!shut_down_) {
+ executor_->Execute(std::move(runnable));
+ } else {
+ NEARBY_LOGS(ERROR) << "Error: " << __func__
+ << ": Attempt to Execute on a shutdown executor.";
+ }
+}
+
+// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#shutdown--
+void SubmittableExecutor::Shutdown() {
+ if (!shut_down_) {
+ executor_->Shutdown();
+ shut_down_ = true;
+ }
+
+ NEARBY_LOGS(ERROR) << "Error: " << __func__
+ << ": Attempt to Shutdown on a shutdown executor.";
+}
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/submittable_executor.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/submittable_executor.h
new file mode 100644
index 00000000000..165e2323d39
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/submittable_executor.h
@@ -0,0 +1,55 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_SUBMITTABLE_EXECUTOR_H_
+#define PLATFORM_IMPL_WINDOWS_SUBMITTABLE_EXECUTOR_H_
+
+#include "internal/platform/implementation/submittable_executor.h"
+#include "internal/platform/implementation/windows/executor.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+// Main interface to be used by platform as a base class for
+// - MultiThreadExecutorWrapper
+// - SingleThreadExecutorWrapper
+// Platform must override bool submit(std::function<void()>) method.
+class SubmittableExecutor : public api::SubmittableExecutor {
+ public:
+ SubmittableExecutor();
+ SubmittableExecutor(int32_t maxConcurrancy);
+ ~SubmittableExecutor() override = default;
+
+ // Submit a callable (with no delay).
+ // Returns true, if callable was submitted, false otherwise.
+ // Callable is not submitted if shutdown is in progress.
+ bool DoSubmit(Runnable&& wrapped_callable) override;
+
+ // https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-
+ void Execute(Runnable&& runnable) override;
+
+ // https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#shutdown--
+ void Shutdown() override;
+
+ private:
+ std::unique_ptr<nearby::windows::Executor> executor_;
+ std::atomic_bool shut_down_;
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_WINDOWS_SUBMITTABLE_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/submittable_executor_test.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/submittable_executor_test.cc
new file mode 100644
index 00000000000..99bc6bb50b9
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/submittable_executor_test.cc
@@ -0,0 +1,240 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+#include "internal/platform/implementation/windows/submittable_executor.h"
+
+#include <utility>
+
+#include "internal/platform/implementation/windows/test_data.h"
+
+#include "gtest/gtest.h"
+
+TEST(SubmittableExecutorTests, SingleThreadedExecuteSucceeds) {
+ // Arrange
+ std::string expected(RUNNABLE_0_TEXT.c_str());
+
+ std::unique_ptr<location::nearby::windows::SubmittableExecutor>
+ submittableExecutor =
+ std::make_unique<location::nearby::windows::SubmittableExecutor>();
+ std::string output = std::string();
+ // Container to note threads that ran
+ std::unique_ptr<std::vector<DWORD>> threadIds =
+ std::make_unique<std::vector<DWORD>>();
+
+ threadIds->push_back(GetCurrentThreadId());
+
+ // Act
+ submittableExecutor->Execute([&output, &threadIds]() {
+ threadIds->push_back(GetCurrentThreadId());
+ output.append(RUNNABLE_0_TEXT.c_str());
+ });
+
+ submittableExecutor->Shutdown();
+
+ // Assert
+ // We should've run 1 time on the main thread, and 1 times on the
+ // workerThread
+ ASSERT_EQ(threadIds->size(), 2);
+ // We should still be on the main thread
+ ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
+ // We should've run all runnables on the worker thread
+ ASSERT_EQ(output, expected);
+}
+
+TEST(SubmittableExecutorTests, SingleThreadedExecuteAfterShutdownFails) {
+ // Arrange
+ std::string expected("");
+
+ std::unique_ptr<location::nearby::windows::SubmittableExecutor>
+ submittableExecutor =
+ std::make_unique<location::nearby::windows::SubmittableExecutor>();
+ std::string output = std::string();
+ // Container to note threads that ran
+ std::unique_ptr<std::vector<DWORD>> threadIds =
+ std::make_unique<std::vector<DWORD>>();
+
+ threadIds->push_back(GetCurrentThreadId());
+
+ submittableExecutor->Shutdown();
+
+ // Act
+ submittableExecutor->Execute([&output, &threadIds]() {
+ threadIds->push_back(GetCurrentThreadId());
+ output.append(RUNNABLE_0_TEXT.c_str());
+ });
+
+ // Assert
+ // We should've run 1 time on the main thread, and 0 times on the
+ // workerThread
+ ASSERT_EQ(threadIds->size(), 1);
+ // We should still be on the main thread
+ ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
+ // We should've run all runnables on the worker thread
+ ASSERT_EQ(output, expected);
+}
+
+TEST(SubmittableExecutorTests, SingleThreadedDoSubmitSucceeds) {
+ // Arrange
+ std::string expected(RUNNABLE_0_TEXT.c_str());
+
+ std::unique_ptr<location::nearby::windows::SubmittableExecutor>
+ submittableExecutor =
+ std::make_unique<location::nearby::windows::SubmittableExecutor>();
+ std::string output = std::string();
+ // Container to note threads that ran
+ std::unique_ptr<std::vector<DWORD>> threadIds =
+ std::make_unique<std::vector<DWORD>>();
+
+ threadIds->push_back(GetCurrentThreadId());
+
+ // Act
+ auto result = submittableExecutor->DoSubmit([&output, &threadIds]() {
+ threadIds->push_back(GetCurrentThreadId());
+ output.append(RUNNABLE_0_TEXT.c_str());
+ });
+
+ submittableExecutor->Shutdown();
+
+ // Assert
+ // We should've said we were going to run this one
+ ASSERT_TRUE(result);
+ // We should've run 1 time on the main thread, and 1 times on the
+ // workerThread
+ ASSERT_EQ(threadIds->size(), 2);
+ // We should still be on the main thread
+ ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
+ // We should've run all runnables on the worker thread
+ ASSERT_EQ(output, expected);
+}
+
+TEST(SubmittableExecutorTests,
+ SingleThreadedDoSubmitAfterShutdownReturnsFalse) {
+ // Arrange
+ std::string expected("");
+
+ std::unique_ptr<location::nearby::windows::SubmittableExecutor>
+ submittableExecutor =
+ std::make_unique<location::nearby::windows::SubmittableExecutor>();
+ std::unique_ptr<std::string> output = std::make_unique<std::string>();
+ // Container to note threads that ran
+ std::unique_ptr<std::vector<DWORD>> threadIds =
+ std::make_unique<std::vector<DWORD>>();
+
+ threadIds->push_back(GetCurrentThreadId());
+
+ submittableExecutor->Shutdown();
+
+ // Act
+ auto result = submittableExecutor->DoSubmit([&output, &threadIds]() {
+ threadIds->push_back(GetCurrentThreadId());
+ output->append(RUNNABLE_0_TEXT.c_str());
+ });
+
+ // Assert
+ // We should've said we were going to run this one
+ ASSERT_FALSE(result);
+ // We should've run 1 time on the main thread, and 1 times on the
+ // workerThread
+ ASSERT_EQ(threadIds->size(), 1);
+ // We should still be on the main thread
+ ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
+ // We should've run all runnables on the worker thread
+ ASSERT_EQ(*output.get(), expected);
+}
+
+TEST(SubmittableExecutorTests, SingleThreadedExecuteMultipleTasksSucceeds) {
+ // Arrange
+ std::string expected(RUNNABLE_ALL_TEXT.c_str());
+
+ std::unique_ptr<location::nearby::windows::SubmittableExecutor>
+ submittableExecutor =
+ std::make_unique<location::nearby::windows::SubmittableExecutor>();
+ std::unique_ptr<std::string> output = std::make_unique<std::string>();
+ // Container to note threads that ran
+ std::unique_ptr<std::vector<DWORD>> threadIds =
+ std::make_unique<std::vector<DWORD>>();
+
+ threadIds->push_back(GetCurrentThreadId());
+
+ // Act
+ for (int index = 0; index < 5; index++) {
+ submittableExecutor->Execute([&output, &threadIds, index]() {
+ threadIds->push_back(GetCurrentThreadId());
+ char buffer[128];
+ snprintf(buffer, sizeof(buffer), "%s%d, ", RUNNABLE_TEXT.c_str(), index);
+ output->append(std::string(buffer));
+ });
+ }
+
+ submittableExecutor->Shutdown();
+
+ // Assert
+ // We should've run 1 time on the main thread, and 5 times on the
+ // workerThread
+ ASSERT_EQ(threadIds->size(), 6);
+ // We should still be on the main thread
+ ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
+ // We should've run all runnables on the worker thread
+ auto workerThreadId = threadIds->at(1);
+ for (int index = 1; index < threadIds->size(); index++) {
+ ASSERT_EQ(threadIds->at(index), workerThreadId);
+ }
+
+ // We should of run them in the order submitted
+ ASSERT_EQ(*output.get(), expected);
+}
+
+TEST(SubmittableExecutorTests, SingleThreadedDoSubmitMultipleTasksSucceeds) {
+ // Arrange
+ std::string expected(RUNNABLE_ALL_TEXT.c_str());
+
+ std::unique_ptr<location::nearby::windows::SubmittableExecutor>
+ submittableExecutor =
+ std::make_unique<location::nearby::windows::SubmittableExecutor>();
+ std::unique_ptr<std::string> output = std::make_unique<std::string>();
+ // Container to note threads that ran
+ std::unique_ptr<std::vector<DWORD>> threadIds =
+ std::make_unique<std::vector<DWORD>>();
+
+ threadIds->push_back(GetCurrentThreadId());
+
+ // Act
+ bool result = true;
+ for (int index = 0; index < 5; index++) {
+ result &= submittableExecutor->DoSubmit([&output, &threadIds, index]() {
+ threadIds->push_back(GetCurrentThreadId());
+ char buffer[128];
+ snprintf(buffer, sizeof(buffer), "%s%d, ", RUNNABLE_TEXT.c_str(), index);
+ output->append(std::string(buffer));
+ });
+ }
+
+ submittableExecutor->Shutdown();
+
+ // Assert
+ // All of these should have submitted
+ ASSERT_TRUE(result);
+ // We should've run 1 time on the main thread, and 5 times on the
+ // workerThread
+ ASSERT_EQ(threadIds->size(), 6);
+ // We should still be on the main thread
+ ASSERT_EQ(GetCurrentThreadId(), threadIds->at(0));
+ // We should've run all runnables on the worker thread
+ auto workerThreadId = threadIds->at(1);
+ for (int index = 1; index < threadIds->size(); index++) {
+ ASSERT_EQ(threadIds->at(index), workerThreadId);
+ }
+
+ // We should of run them in the order submitted
+ ASSERT_EQ(*output.get(), expected);
+}
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/system_clock.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/system_clock.cc
new file mode 100644
index 00000000000..c08f9a9c329
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/system_clock.cc
@@ -0,0 +1,43 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_SYSTEM_CLOCK_H_
+#define PLATFORM_IMPL_WINDOWS_SYSTEM_CLOCK_H_
+
+#include "internal/platform/implementation/system_clock.h"
+
+namespace location {
+namespace nearby {
+
+// Initialize global system state.
+void SystemClock::Init() { }
+
+// Returns current absolute time. It is guaranteed to be monotonic.
+absl::Time SystemClock::ElapsedRealtime() {
+ return absl::FromUnixNanos(
+ std::chrono::duration_cast<std::chrono::nanoseconds>(
+ std::chrono::steady_clock::now().time_since_epoch())
+ .count());
+}
+
+// Pauses current thread for the specified duration.
+Exception SystemClock::Sleep(absl::Duration duration) {
+ absl::SleepFor(duration);
+ return {Exception::kSuccess};
+}
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_WINDOWS_SYSTEM_CLOCK_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/impl/windows/test_data.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/test_data.h
index ce1605200c0..ce1605200c0 100644
--- a/chromium/third_party/nearby/src/cpp/platform/impl/windows/test_data.h
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/test_data.h
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/test_utils.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/test_utils.cc
new file mode 100644
index 00000000000..71cb79ab633
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/test_utils.cc
@@ -0,0 +1,61 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/windows/test_utils.h"
+
+#include <shlobj.h>
+
+#include "absl/strings/str_cat.h"
+
+namespace test_utils {
+std::wstring StringToWideString(const std::string& s) {
+ int len;
+ int slength = (int)s.length() + 1;
+ len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
+ wchar_t* buf = new wchar_t[len];
+ MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
+ std::wstring r(buf);
+ delete[] buf;
+ return r;
+}
+
+std::string GetPayloadPath(location::nearby::PayloadId payload_id) {
+ PWSTR basePath;
+
+ // Retrieves the full path of a known folder identified by the folder's
+ // KNOWNFOLDERID.
+ // https://docs.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetknownfolderpath
+ SHGetKnownFolderPath(
+ FOLDERID_Downloads, // rfid: A reference to the KNOWNFOLDERID that
+ // identifies the folder.
+ 0, // dwFlags: Flags that specify special retrieval options.
+ NULL, // hToken: An access token that represents a particular user.
+ &basePath); // ppszPath: When this method returns, contains the address
+ // of a pointer to a null-terminated Unicode string that
+ // specifies the path of the known folder. The calling
+ // process is responsible for freeing this resource once it
+ // is no longer needed by calling CoTaskMemFree, whether
+ // SHGetKnownFolderPath succeeds or not.
+
+ size_t bufferSize;
+ wcstombs_s(&bufferSize, NULL, 0, basePath, 0);
+ char* fullpathUTF8 = new char[bufferSize + 1];
+ memset(fullpathUTF8, 0, bufferSize);
+ wcstombs_s(&bufferSize, fullpathUTF8, bufferSize, basePath, bufferSize - 1);
+ std::string fullPath = std::string(fullpathUTF8);
+ auto retval = absl::StrCat(fullPath += "\\", payload_id);
+ delete[] fullpathUTF8;
+ return retval;
+}
+} // namespace test_utils
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/test_utils.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/test_utils.h
new file mode 100644
index 00000000000..155eaa41c27
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/test_utils.h
@@ -0,0 +1,43 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_TEST_UTILS_H_
+#define PLATFORM_IMPL_WINDOWS_TEST_UTILS_H_
+
+#include <xstring>
+
+#include "internal/platform/payload_id.h"
+
+#define TEST_BUFFER_SIZE 256
+#define TEST_PAYLOAD_ID 64l
+#define TEST_STRING \
+ "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas " \
+ "eleifend nisl at magna maximus, id finibus mauris ultrices. Mauris " \
+ "interdum efficitur turpis eget auctor. Nullam commodo metus et ante " \
+ "bibendum molestie. Donec iaculis ante nec diam rutrum egestas. Proin " \
+ "maximus metus luctus rutrum congue. Integer et eros nunc. Etiam purus " \
+ "neque, tincidunt eu elementum in, pharetra sit amet magna. Quisque " \
+ "consequat aliquam aliquam. Vestibulum ante ipsum primis in faucibus orci " \
+ "luctus et ultrices posuere cubilia curae; Maecenas a semper eros, a " \
+ "auctor mi. In luctus diam sem, eu pretium nisi porttitor ac. Sed cursus, " \
+ "arcu in bibendum feugiat, leo erat finibus massa, ut tincidunt magna nunc " \
+ "eu tellus. Cras feugiat ornare vestibulum. Nullam at ipsum vestibulum " \
+ "sapien luctus dictum ac vel ligula."
+
+namespace test_utils {
+std::wstring StringToWideString(const std::string& s);
+std::string GetPayloadPath(location::nearby::PayloadId payload_id);
+} // namespace test_utils
+
+#endif // PLATFORM_IMPL_WINDOWS_TEST_UTILS_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/thread_pool.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/thread_pool.cc
new file mode 100644
index 00000000000..7e92c06d25f
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/thread_pool.cc
@@ -0,0 +1,531 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/windows/thread_pool.h"
+
+#include <stdio.h>
+
+#include <iomanip>
+#include <iostream>
+
+#include "internal/platform/implementation/windows/runner.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+#define POOL_NAME_BUFFER_SIZE 64
+#define EVENT_NAME_BUFFER_SIZE 64
+
+__declspec(align(8)) volatile long ThreadPool::instance_ = // NOLINT
+ 0; // NOLINT because the Windows function takes a volatile long
+
+DWORD WINAPI ThreadPool::_ThreadProc(LPVOID pParam) {
+ DWORD wait;
+ ThreadPool* pool;
+ DWORD threadId = GetCurrentThreadId();
+ HANDLE waits[2];
+ std::unique_ptr<Runner> runner;
+
+ _ASSERT(pParam != NULL);
+ if (NULL == pParam) {
+ NEARBY_LOGS(ERROR) << __func__ << ": pParam must not be null.";
+ return -1;
+ }
+
+ NEARBY_LOGS(VERBOSE) << "Info: " << __func__
+ << ": Starting thread id: " << threadId;
+
+ pool = static_cast<ThreadPool*>(pParam);
+ waits[0] = pool->GetWaitHandle(threadId);
+ waits[1] = pool->GetShutdownHandle();
+
+loop_here:
+ wait = WaitForMultipleObjects(2, waits, FALSE, INFINITE);
+ if (wait == 1) {
+ if (pool->CheckThreadStop()) {
+ if (pool->GetWorkingThreadCount() < 1) {
+ NEARBY_LOGS(VERBOSE) << "Info: " << __func__
+ << ": Pool is being destroyed, and working thread "
+ "count is 0, thread exiting.";
+
+ return 0;
+ }
+ }
+ }
+
+ // a new function was added, go and get it
+ runner = nullptr;
+
+ NEARBY_LOGS(VERBOSE) << "Info: " << __func__ << ": On thread id: " << threadId
+ << ", checking for work.";
+
+ if (pool->GetThreadProc(threadId, std::move(runner))) {
+ pool->BusyNotify(threadId);
+ runner->Run();
+ pool->FinishNotify(threadId); // tell the pool, i am now free
+ }
+
+ goto loop_here;
+
+ NEARBY_LOGS(VERBOSE) << "Info: " << __func__ << ": Thread shutdown occurred.";
+
+ return 0;
+}
+
+ThreadPool::ThreadPool(int nPoolSize, bool bCreateNow)
+ : function_list_(std::make_unique<FunctionList>()),
+ thread_map_(std::make_unique<ThreadMap>()),
+ thread_handles_(nullptr),
+ wait_for_threads_to_die_ms_(500),
+ notify_shutdown_(nullptr) {
+ // The MAXIMUM_WAIT_OBJECTS is the limiting factor, currently
+ // windows has a max of 64. This means we can only wait on up
+ // to 64 threads, anything more gives undesirable results.
+ if (nPoolSize > 63) {
+ NEARBY_LOGS(ERROR) << __func__ << ": Thread pool max size exceeded.";
+ throw ThreadPoolException("Thread pool max size exceeded.");
+ }
+
+ pool_state_ = State::Destroyed;
+ pool_size_ = nPoolSize;
+
+ InitializeCriticalSection(&critical_section_);
+
+ if (bCreateNow) {
+ if (!Create()) {
+ NEARBY_LOGS(ERROR) << __func__ << ": Thread pool creation failed.";
+ throw ThreadPoolException("Thread pool creation failed.");
+ }
+ }
+}
+
+bool ThreadPool::Create() {
+ if (pool_state_ != State::Destroyed) {
+ // To create a new pool, destroy the existing one first
+ NEARBY_LOGS(ERROR) << __func__
+ << ": Attempt to create a new thread pool before "
+ "destroying the old one.";
+ return false;
+ }
+
+ char buffer[POOL_NAME_BUFFER_SIZE];
+ snprintf(buffer, POOL_NAME_BUFFER_SIZE, "Pool%d",
+ (uint32_t)(InterlockedIncrement(
+ &ThreadPool::instance_))); // InterlockedIncrement done here
+ // since there's no access to the
+ // instance_ var except through the
+ // interlocked functions
+ pool_name_ = std::string(buffer);
+
+ // create the event which will signal the threads to stop
+ std::string eventName;
+ notify_shutdown_ = CreateEvent(NULL, TRUE, FALSE, NULL);
+ _ASSERT(notify_shutdown_ != NULL);
+ if (!notify_shutdown_) {
+ NEARBY_LOGS(ERROR) << "Error: " << __func__
+ << ": Failed to create thread shut down event.";
+
+ return false;
+ }
+
+ SYSTEM_INFO sysinfo;
+ GetSystemInfo(&sysinfo);
+ int numCPU = sysinfo.dwNumberOfProcessors;
+
+ int threadsToCreate = 0;
+
+ // We are going to initially allocate the first n
+ // threads based on the number of logical cores
+ if (pool_size_ > numCPU) {
+ threadsToCreate = STARTUP_THREAD_COUNT;
+ } else {
+ threadsToCreate = pool_size_;
+ }
+
+ thread_handles_ = new HANDLE[pool_size_];
+
+ // create the threads
+ for (int index = 0; index < threadsToCreate; index++) {
+ CreateThreadPoolThread(&thread_handles_[index]);
+ }
+
+ pool_state_ = State::Ready;
+ return true;
+}
+
+ThreadPool::~ThreadPool() {
+ Destroy();
+ ReleaseMemory();
+ DeleteCriticalSection(&critical_section_);
+}
+
+DWORD ThreadPool::CreateThreadPoolThread(HANDLE* handles) {
+ HANDLE thread;
+ DWORD threadId;
+ std::unique_ptr<ThreadData> threadData = std::make_unique<ThreadData>();
+
+ char buffer[EVENT_NAME_BUFFER_SIZE];
+
+ snprintf(buffer, EVENT_NAME_BUFFER_SIZE, "PID:%ld IID:%d TDX:%d",
+ GetCurrentProcessId(),
+ (uint32_t)(InterlockedAdd(&ThreadPool::instance_, 0)),
+ (int)thread_map_->size());
+
+ thread = CreateThread(NULL, 0, ThreadPool::_ThreadProc, this,
+ CREATE_SUSPENDED, &threadId);
+
+ _ASSERT(NULL != thread);
+
+ if (NULL == thread) {
+ NEARBY_LOGS(ERROR) << "Error: " << __func__ << ": Failed to create thread.";
+ return NULL;
+ }
+
+ if (thread) {
+ // add the entry to the map of threads
+ EnterCriticalSection(&critical_section_);
+
+ threadData->free = true;
+ threadData->wait_handle = CreateEventA(NULL, TRUE, FALSE, buffer);
+
+ threadData->thread_handle = thread;
+ threadData->thread_id = threadId;
+
+ thread_map_->insert(ThreadMap::value_type(threadId, std::move(threadData)));
+ *handles = thread;
+ LeaveCriticalSection(&critical_section_);
+
+ ResumeThread(thread);
+
+ NEARBY_LOGS(VERBOSE) << "Info: " << __func__
+ << ": Thread created, handle: " << thread
+ << ", id: " << threadId;
+
+ return threadId;
+ } else {
+ NEARBY_LOGS(ERROR) << "Error: " << __func__ << ": Failed to create thread.";
+ return NULL;
+ }
+}
+
+void ThreadPool::ReleaseMemory() {
+ // empty all collections
+ EnterCriticalSection(&critical_section_);
+
+ NEARBY_LOGS(VERBOSE) << "Info: " << __func__
+ << ": Clearing the function list.";
+
+ function_list_->clear();
+
+ NEARBY_LOGS(VERBOSE) << "Info: " << __func__ << ": Clearing the thread map.";
+
+ thread_map_->clear();
+
+ LeaveCriticalSection(&critical_section_);
+}
+
+void ThreadPool::Destroy() {
+ if (pool_state_ == State::Destroying || pool_state_ == State::Destroyed)
+ return;
+
+ NEARBY_LOGS(VERBOSE) << "Info: " << __func__ << ": Destroying thread pool.";
+
+ pool_state_ = State::Destroying;
+
+ bool notDone = true;
+
+ EnterCriticalSection(&critical_section_);
+
+ ThreadMap::iterator iter = thread_map_->begin();
+ int index = 0;
+
+ // Build an array of handles
+ while (iter != thread_map_->end()) {
+ thread_handles_[index] = iter->second->thread_handle;
+ index++;
+ iter++;
+ }
+
+ LeaveCriticalSection(&critical_section_);
+
+ // tell all threads to shutdown.
+ _ASSERT(NULL != notify_shutdown_);
+ SetEvent(GetShutdownHandle());
+
+ NEARBY_LOGS(VERBOSE) << "Info: " << __func__
+ << ": Setting waits for the threads to exit.";
+
+ if (pool_size_ == 1) {
+ // Waits until the specified object is in the signaled state or the time-out
+ // interval elapses.
+ // https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitforsingleobject
+ auto wait = WaitForSingleObject(
+ thread_handles_[0], // A handle to the object
+ INFINITE // The time-out interval, in milliseconds.
+ );
+ } else {
+ auto wait =
+ // Waits until one or all of the specified objects are in the signaled
+ // state or the time-out interval elapses.
+ // https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitformultipleobjects
+ WaitForMultipleObjects(
+ index, // The number of object handles in the array.
+ thread_handles_, // An array of object handles.
+ true, // If this parameter is TRUE, the function returns when the
+ // state of all objects in the handles array are signaled.
+ INFINITE // The time-out interval, in milliseconds.
+ );
+ }
+
+ NEARBY_LOGS(VERBOSE) << "Info: " << __func__ << ": All threads have exited.";
+
+ delete[] thread_handles_;
+
+ // close the shutdown event
+ CloseHandle(notify_shutdown_);
+ notify_shutdown_ = NULL;
+
+ EnterCriticalSection(&critical_section_);
+
+ ThreadMap::iterator threadMapIterator;
+
+ // walk through the events and threads and close them all
+ for (threadMapIterator = thread_map_->begin();
+ threadMapIterator != thread_map_->end(); threadMapIterator++) {
+ NEARBY_LOGS(VERBOSE) << "Info: " << __func__ << ": Closing thread handle: "
+ << threadMapIterator->second->thread_handle
+ << " thread id: "
+ << threadMapIterator->second->thread_id
+ << " wait_handle: "
+ << threadMapIterator->second->wait_handle;
+
+ CloseHandle(threadMapIterator->second->wait_handle);
+ CloseHandle(threadMapIterator->second->thread_handle);
+ }
+
+ LeaveCriticalSection(&critical_section_);
+
+ NEARBY_LOGS(VERBOSE) << "Info: " << __func__
+ << ": Sending the shutdown event.";
+
+ ReleaseMemory(); // free any remaining UserPoolData objects
+
+ InterlockedDecrement(&ThreadPool::instance_);
+
+ pool_state_ = State::Destroyed;
+}
+
+int ThreadPool::GetPoolSize() { return pool_size_; }
+
+void ThreadPool::SetPoolSize(int nSize) {
+ _ASSERT(nSize > 0);
+
+ if (nSize <= 0) {
+ NEARBY_LOGS(ERROR)
+ << __func__ << ": 0 or negative value is not a valid thread pool size.";
+ return;
+ }
+
+ pool_size_ = nSize;
+}
+
+HANDLE ThreadPool::GetShutdownHandle() { return notify_shutdown_; }
+
+bool ThreadPool::GetThreadProc(DWORD threadId,
+ std::unique_ptr<Runner>&& runner) {
+ // get the first function info in the function list
+ FunctionList::iterator functionListIterator;
+ bool haveAnotherRunner = false;
+
+ EnterCriticalSection(&critical_section_);
+
+ functionListIterator = function_list_->begin();
+
+ if (functionListIterator != function_list_->end()) {
+ runner = std::move(*functionListIterator);
+
+ NEARBY_LOGS(VERBOSE) << "Info: " << __func__
+ << ": popping runner from the front.";
+
+ function_list_->pop_front(); // remove the function from the list
+
+ haveAnotherRunner = true;
+ } else {
+ thread_map_->at(threadId)->free = true;
+ ResetEvent(thread_map_->at(threadId)->wait_handle);
+ }
+
+ LeaveCriticalSection(&critical_section_);
+
+ return haveAnotherRunner;
+}
+
+void ThreadPool::FinishNotify(DWORD threadId) {
+ ThreadMap::iterator threadMapIterator;
+
+ EnterCriticalSection(&critical_section_);
+
+ threadMapIterator = thread_map_->find(threadId);
+
+ if (threadMapIterator == thread_map_->end()) // if search found no elements
+ {
+ _ASSERT(!"No matching thread found.");
+ NEARBY_LOGS(ERROR) << __func__ << ": No matching thread found.";
+ } else {
+ thread_map_->at(threadId)->free = true;
+
+ if (!function_list_->empty()) {
+ // there are some more functions that need servicing, lets do that.
+ // By not doing anything here we are letting the thread go back and
+ // check the function list and pick up a function and execute it.
+ thread_map_->at(threadId)->free = false;
+ } else {
+ ResetEvent(thread_map_->at(threadId)->wait_handle);
+ }
+ }
+
+ LeaveCriticalSection(&critical_section_);
+}
+
+void ThreadPool::BusyNotify(DWORD threadId) {
+ ThreadMap::iterator iter;
+
+ EnterCriticalSection(&critical_section_);
+
+ iter = thread_map_->find(threadId);
+
+ if (iter == thread_map_->end()) // if search found no elements
+ {
+ _ASSERT(!"No matching thread found.");
+ } else {
+ thread_map_->at(threadId)->free = false;
+ }
+
+ LeaveCriticalSection(&critical_section_);
+}
+
+bool ThreadPool::Run(std::unique_ptr<Runner> runner) {
+ if (pool_state_ == State::Destroying || pool_state_ == State::Destroyed)
+ return false;
+
+ _ASSERT(runner != NULL);
+
+ AddRunner(std::move(runner));
+
+ // See if any threads are free
+ ThreadMap::iterator iterator;
+ std::unique_ptr<ThreadData> threadData;
+
+ bool freeThreadFound = false;
+
+ EnterCriticalSection(&critical_section_);
+
+ for (iterator = thread_map_->begin(); iterator != thread_map_->end();
+ iterator++) {
+ if (iterator->second->free) {
+ // here is a free thread, put it to work
+ iterator->second->free = false;
+ SetEvent(iterator->second->wait_handle);
+ // this thread will now call GetThreadProc() and pick up the next
+ // function in the list.
+ freeThreadFound = true;
+ break;
+ }
+ }
+
+ if (!freeThreadFound && thread_map_->size() < pool_size_) {
+ // We haven't used up all of our threads, go ahead and spin up another one
+ DWORD threadId =
+ CreateThreadPoolThread(&thread_handles_[thread_map_->size()]);
+ thread_map_->at(threadId)->free = false;
+ SetEvent(thread_map_->at(threadId)->wait_handle);
+ }
+
+ LeaveCriticalSection(&critical_section_);
+
+ return true;
+}
+
+void ThreadPool::AddRunner(std::unique_ptr<Runner> runner) {
+ // add it to the list
+ runner->thread_pool_ = this;
+
+ NEARBY_LOGS(VERBOSE) << "Info: " << __func__
+ << ": pushing new runner to the back.";
+
+ EnterCriticalSection(&critical_section_);
+
+ function_list_->push_back(std::move(runner));
+
+ LeaveCriticalSection(&critical_section_);
+}
+
+HANDLE ThreadPool::GetWaitHandle(DWORD dwThreadId) {
+ HANDLE hWait = NULL;
+ ThreadMap::iterator iter;
+
+ EnterCriticalSection(&critical_section_);
+
+ iter = thread_map_->find(dwThreadId);
+
+ if (iter != thread_map_->end()) // if search found no elements
+ {
+ hWait = thread_map_->at(dwThreadId)->wait_handle;
+ }
+
+ LeaveCriticalSection(&critical_section_);
+
+ return hWait;
+}
+
+bool ThreadPool::CheckThreadStop() {
+ EnterCriticalSection(&critical_section_);
+
+ bool bRet =
+ (pool_state_ == State::Destroying || pool_state_ == State::Destroyed);
+
+ LeaveCriticalSection(&critical_section_);
+
+ return bRet;
+}
+
+int ThreadPool::GetWorkingThreadCount() {
+ ThreadMap::iterator iter;
+
+ int nCount = 0;
+
+ EnterCriticalSection(&critical_section_);
+
+ for (iter = thread_map_->begin(); iter != thread_map_->end(); iter++) {
+ if (function_list_->empty()) {
+ iter->second->free = true;
+ }
+
+ if (!iter->second->free) {
+ nCount++;
+ }
+ }
+
+ LeaveCriticalSection(&critical_section_);
+
+ return nCount;
+}
+
+State ThreadPool::GetState() { return pool_state_; }
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/thread_pool.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/thread_pool.h
new file mode 100644
index 00000000000..7aedf1571e2
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/thread_pool.h
@@ -0,0 +1,106 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+#ifndef PLATFORM_IMPL_WINDOWS_THREAD_POOL_H_
+#define PLATFORM_IMPL_WINDOWS_THREAD_POOL_H_
+#include <windows.h>
+
+#include <functional>
+#include <list>
+#include <map>
+#include <stdexcept>
+
+#include "internal/platform/implementation/windows/runner.h"
+namespace location {
+namespace nearby {
+namespace windows {
+
+// This is the number of threads that will be started initially if the pool
+// size is greater than 4, or if the pool size is greater than the number
+// of cores present, including virtual cores
+#define STARTUP_THREAD_COUNT 4
+
+class ThreadPoolException : public std::runtime_error {
+ public:
+ ThreadPoolException() : std::runtime_error("") {}
+ ThreadPoolException(const std::string& message)
+ : std::runtime_error(message), message_(message) {}
+ virtual const char* what() const throw() {
+ return message_.c_str();
+ }
+
+ private:
+ const std::string message_;
+};
+
+// all functions passed in by clients will be initially stored in this list.
+typedef std::list<std::unique_ptr<Runner>> FunctionList;
+// info about threads in the pool will be saved using this struct.
+typedef struct tagThreadData {
+ bool free;
+ HANDLE wait_handle;
+ HANDLE thread_handle;
+ DWORD thread_id;
+} ThreadData;
+// info about all threads belonging to this pool will be stored in this map
+typedef std::map<DWORD, std::unique_ptr<ThreadData>>
+ ThreadMap;
+enum class State {
+ Ready, // has been created
+ Destroying, // in the process of getting destroyed, no request is processed /
+ // accepted
+ Destroyed // Destroyed, no threads are available, request can still be queued
+};
+class ThreadPool {
+ public:
+ ThreadPool(int nPoolSize, bool bCreateNow);
+ virtual ~ThreadPool();
+ bool Create(); // creates the thread pool
+ void Destroy(); // destroy the thread pool
+ int GetPoolSize();
+ void SetPoolSize(int);
+ bool Run(std::unique_ptr<Runner> runObject);
+ bool CheckThreadStop();
+ int GetWorkingThreadCount();
+ State GetState();
+
+ private:
+ static DWORD WINAPI _ThreadProc(LPVOID);
+ std::unique_ptr<FunctionList> function_list_;
+ std::unique_ptr<ThreadMap> thread_map_;
+ HANDLE* thread_handles_ = nullptr;
+ int pool_size_;
+ int wait_for_threads_to_die_ms_; // In milli-seconds
+ std::string pool_name_; // To assist in logging and debug
+ HANDLE notify_shutdown_; // notifies threads that a new function
+ // is added
+ volatile State pool_state_;
+ static __declspec(
+ align(8)) volatile long instance_; // NOLINT Windows function takes
+ // volatile long
+ CRITICAL_SECTION critical_section_;
+
+ bool GetThreadProc(DWORD dwThreadId, std::unique_ptr<Runner>&& runner);
+ void FinishNotify(DWORD dwThreadId);
+ void BusyNotify(DWORD dwThreadId);
+ void ReleaseMemory();
+ HANDLE GetWaitHandle(DWORD dwThreadId);
+ HANDLE GetShutdownHandle();
+ void AddRunner(std::unique_ptr<Runner> runner);
+ DWORD CreateThreadPoolThread(HANDLE* handles);
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+#endif // PLATFORM_IMPL_WINDOWS_THREAD_POOL_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/utils.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/utils.cc
new file mode 100644
index 00000000000..961f37ae2f2
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/utils.cc
@@ -0,0 +1,127 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/windows/utils.h"
+
+// Windows headers
+#include <strsafe.h>
+
+// Standard C/C++ headers
+#include <codecvt>
+#include <exception>
+#include <string>
+
+// Third party headers
+#include "absl/strings/ascii.h"
+#include "absl/strings/str_format.h"
+
+// Nearby connections headers
+#include "internal/platform/implementation/crypto.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+std::string uint64_to_mac_address_string(uint64_t bluetoothAddress) {
+ std::string buffer = absl::StrFormat(
+ "%2llx:%2llx:%2llx:%2llx:%2llx:%2llx", bluetoothAddress >> 40,
+ (bluetoothAddress >> 32) & 0xff, (bluetoothAddress >> 24) & 0xff,
+ (bluetoothAddress >> 16) & 0xff, (bluetoothAddress >> 8) & 0xff,
+ bluetoothAddress & 0xff);
+
+ return absl::AsciiStrToUpper(buffer);
+}
+
+std::wstring string_to_wstring(std::string str) {
+ std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
+ return converter.from_bytes(str);
+}
+
+std::string wstring_to_string(std::wstring wstr) {
+ std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
+ return converter.to_bytes(wstr);
+}
+
+ByteArray Sha256(absl::string_view input, size_t size) {
+ ByteArray hash = location::nearby::Crypto::Sha256(input);
+ return ByteArray{hash.data(), size};
+}
+
+uint16 InspectableReader::ReadUint16(IInspectable inspectable) {
+ auto property_value =
+ inspectable.try_as<winrt::Windows::Foundation::IPropertyValue>();
+ if (property_value == nullptr) {
+ throw std::invalid_argument("no property value interface.");
+ }
+ if (property_value.Type() !=
+ winrt::Windows::Foundation::PropertyType::UInt16) {
+ throw std::invalid_argument("not uin16 data type.");
+ }
+
+ return property_value.GetUInt16();
+}
+
+uint32 InspectableReader::ReadUint32(IInspectable inspectable) {
+ auto property_value =
+ inspectable.try_as<winrt::Windows::Foundation::IPropertyValue>();
+ if (property_value == nullptr) {
+ throw std::invalid_argument("no property value interface.");
+ }
+ if (property_value.Type() !=
+ winrt::Windows::Foundation::PropertyType::UInt32) {
+ throw std::invalid_argument("not uin32 data type.");
+ }
+
+ return property_value.GetUInt32();
+}
+
+std::string InspectableReader::ReadString(IInspectable inspectable) {
+ auto property_value =
+ inspectable.try_as<winrt::Windows::Foundation::IPropertyValue>();
+ if (property_value == nullptr) {
+ throw std::invalid_argument("no property value interface.");
+ }
+ if (property_value.Type() !=
+ winrt::Windows::Foundation::PropertyType::String) {
+ throw std::invalid_argument("not string data type.");
+ }
+
+ return wstring_to_string(property_value.GetString().c_str());
+}
+
+std::vector<std::string> InspectableReader::ReadStringArray(
+ IInspectable inspectable) {
+ std::vector<std::string> result;
+ auto property_value =
+ inspectable.try_as<winrt::Windows::Foundation::IPropertyValue>();
+ if (property_value == nullptr) {
+ throw std::invalid_argument("no property value interface.");
+ }
+ if (property_value.Type() !=
+ winrt::Windows::Foundation::PropertyType::StringArray) {
+ throw std::invalid_argument("not string array data type.");
+ }
+
+ winrt::com_array<winrt::hstring> strings;
+ property_value.GetStringArray(strings);
+
+ for (winrt::hstring str : strings) {
+ result.push_back(winrt::to_string(str));
+ }
+ return result;
+}
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/utils.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/utils.h
new file mode 100644
index 00000000000..ffffde77824
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/utils.h
@@ -0,0 +1,65 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_UTILS_H_
+#define PLATFORM_IMPL_WINDOWS_UTILS_H_
+
+#include <Windows.h>
+#include <stdio.h>
+
+#include <string>
+
+#include "absl/strings/string_view.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Foundation.h"
+#include "internal/platform/implementation/windows/generated/winrt/base.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+using winrt::Windows::Foundation::IInspectable;
+
+std::string uint64_to_mac_address_string(uint64_t bluetoothAddress);
+
+// Helpers to windows platform
+std::wstring string_to_wstring(std::string str);
+std::string wstring_to_string(std::wstring wstr);
+ByteArray Sha256(absl::string_view input, size_t size);
+
+namespace Constants {
+// The Id of the Service Name SDP attribute
+const uint16_t SdpServiceNameAttributeId = 0x100;
+
+// The SDP Type of the Service Name SDP attribute.
+// The first byte in the SDP Attribute encodes the SDP Attribute Type as
+// follows:
+// - the Attribute Type size in the least significant 3 bits,
+// - the SDP Attribute Type value in the most significant 5 bits.
+const char SdpServiceNameAttributeType = (4 << 3) | 5;
+} // namespace Constants
+
+class InspectableReader {
+ public:
+ static uint16 ReadUint16(IInspectable inspectable);
+ static uint32 ReadUint32(IInspectable inspectable);
+ static std::string ReadString(IInspectable inspectable);
+ static std::vector<std::string> ReadStringArray(IInspectable inspectable);
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_WINDOWS_UTILS_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/utils_test.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/utils_test.cc
new file mode 100644
index 00000000000..524a096d6df
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/utils_test.cc
@@ -0,0 +1,31 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/windows/utils.h"
+
+#include "gtest/gtest.h"
+
+using location::nearby::windows::uint64_to_mac_address_string;
+
+TEST(UtilsTests, MacAddressToString) {
+ // Arrange
+ const uint64_t input = 0x000034363bc78c71;
+ std::string expected = "34:36:3B:C7:8C:71";
+
+ // Act
+ std::string result = uint64_to_mac_address_string(input);
+
+ // Assert
+ EXPECT_EQ(result, expected);
+}
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/webrtc.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/webrtc.h
new file mode 100644
index 00000000000..e82d8449c67
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/webrtc.h
@@ -0,0 +1,78 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_WEBRTC_H_
+#define PLATFORM_IMPL_WINDOWS_WEBRTC_H_
+
+#include "internal/platform/implementation/webrtc.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+class WebRtcSignalingMessenger : public api::WebRtcSignalingMessenger {
+ public:
+ // TODO(b/184975123): replace with real implementation.
+ ~WebRtcSignalingMessenger() override = default;
+
+ // TODO(b/184975123): replace with real implementation.
+ bool SendMessage(absl::string_view peer_id,
+ const ByteArray& message) override {
+ return false;
+ }
+
+ // TODO(b/184975123): replace with real implementation.
+ bool StartReceivingMessages(
+ api::WebRtcSignalingMessenger::OnSignalingMessageCallback
+ on_message_callback,
+ api::WebRtcSignalingMessenger::OnSignalingCompleteCallback
+ on_complete_callback) override {
+ return false;
+ }
+ // TODO(b/184975123): replace with real implementation.
+ void StopReceivingMessages() override {}
+};
+
+class WebRtcMedium : public api::WebRtcMedium {
+ public:
+ // TODO(b/184975123): replace with real implementation.
+ ~WebRtcMedium() override = default;
+
+ // Gets the default two-letter country code associated with current locale.
+ // For example, en_US locale resolves to "US".
+ // TODO(b/184975123): replace with real implementation.
+ const std::string GetDefaultCountryCode() override {
+ return "Un-implemented";
+ }
+
+ // Creates and returns a new webrtc::PeerConnectionInterface object via
+ // |callback|.
+ // TODO(b/184975123): replace with real implementation.
+ void CreatePeerConnection(webrtc::PeerConnectionObserver* observer,
+ PeerConnectionCallback callback) override {}
+
+ // Returns a signaling messenger for sending WebRTC signaling messages.
+ // TODO(b/184975123): replace with real implementation.
+ std::unique_ptr<api::WebRtcSignalingMessenger> GetSignalingMessenger(
+ absl::string_view self_id,
+ const connections::LocationHint& location_hint) override {
+ return nullptr;
+ }
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_WINDOWS_WEBRTC_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/wifi.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/wifi.h
new file mode 100644
index 00000000000..2fdfa27e64b
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/wifi.h
@@ -0,0 +1,98 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_WIFI_H_
+#define PLATFORM_IMPL_WINDOWS_WIFI_H_
+
+#include "internal/platform/implementation/wifi.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+// Represents a WiFi network found during a call to WifiMedium#scan().
+class WifiScanResult : public api::WifiScanResult {
+ public:
+ // TODO(b/184975123): replace with real implementation.
+ ~WifiScanResult() override = default;
+
+ // Gets the SSID of this WiFi network.
+ // TODO(b/184975123): replace with real implementation.
+ std::string GetSsid() const override { return "Un-implemented"; }
+ // Gets the signal strength of this WiFi network in dBm.
+ // TODO(b/184975123): replace with real implementation.
+ std::int32_t GetSignalStrengthDbm() const override { return 0; }
+ // Gets the frequency band of this WiFi network in MHz.
+ // TODO(b/184975123): replace with real implementation.
+ std::int32_t GetFrequencyMhz() const override { return 0; }
+ // Gets the authentication type of this WiFi network.
+ // TODO(b/184975123): replace with real implementation.
+ api::WifiAuthType GetAuthType() const override {
+ return api::WifiAuthType::kUnknown;
+ }
+};
+
+// Container of operations that can be performed over the WiFi medium.
+class WifiMedium : public api::WifiMedium {
+ public:
+ // TODO(b/184975123): replace with real implementation.
+ ~WifiMedium() override = default;
+
+ class ScanResultCallback : public api::WifiMedium::ScanResultCallback {
+ public:
+ // TODO(b/184975123): replace with real implementation.
+ ~ScanResultCallback() override = default;
+
+ // TODO(b/184975123): replace with real implementation.
+ void OnScanResults(
+ const std::vector<api::WifiScanResult>& scan_results) override {}
+ };
+
+ // Does not take ownership of the passed-in scan_result_callback -- destroying
+ // that is up to the caller.
+ // TODO(b/184975123): replace with real implementation.
+ bool Scan(const api::WifiMedium::ScanResultCallback& scan_result_callback)
+ override {
+ return false;
+ }
+
+ // If 'password' is an empty string, none has been provided. Returns
+ // WifiConnectionStatus::CONNECTED on success, or the appropriate failure code
+ // otherwise.
+ // TODO(b/184975123): replace with real implementation.
+ api::WifiConnectionStatus ConnectToNetwork(
+ absl::string_view ssid, absl::string_view password,
+ api::WifiAuthType auth_type) override {
+ return api::WifiConnectionStatus::kUnknown;
+ }
+
+ // Blocks until it's certain of there being a connection to the internet, or
+ // returns false if it fails to do so.
+ //
+ // How this method wants to verify said connection is totally up to it (so it
+ // can feel free to ping whatever server, download whatever resource, etc.
+ // that it needs to gain confidence that the internet is reachable hereon in).
+ // TODO(b/184975123): replace with real implementation.
+ bool VerifyInternetConnectivity() override { return false; }
+
+ // Returns the local device's IP address in the IPv4 dotted-quad format.
+ // TODO(b/184975123): replace with real implementation.
+ std::string GetIpAddress() override { return "Un-implemented"; }
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_WINDOWS_WIFI_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/wifi_lan.h b/chromium/third_party/nearby/src/internal/platform/implementation/windows/wifi_lan.h
new file mode 100644
index 00000000000..90cb4bcf5e8
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/wifi_lan.h
@@ -0,0 +1,348 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_IMPL_WINDOWS_WIFI_LAN_H_
+#define PLATFORM_IMPL_WINDOWS_WIFI_LAN_H_
+
+// Windows headers
+#include <windows.h> // NOLINT
+#include <win32/windns.h> // NOLINT
+
+// Standard C/C++ headers
+#include <exception>
+#include <functional>
+#include <memory>
+#include <string>
+
+// Nearby connections headers
+#include "absl/base/thread_annotations.h"
+#include "absl/container/flat_hash_map.h"
+#include "absl/container/flat_hash_set.h"
+#include "absl/synchronization/mutex.h"
+#include "absl/types/optional.h"
+#include "internal/platform/implementation/wifi_lan.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/input_stream.h"
+#include "internal/platform/output_stream.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/mutex.h"
+
+// WinRT headers
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Devices.Enumeration.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Foundation.Collections.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Foundation.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Networking.Connectivity.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Networking.ServiceDiscovery.Dnssd.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Networking.Sockets.h"
+#include "internal/platform/implementation/windows/generated/winrt/Windows.Storage.Streams.h"
+#include "internal/platform/implementation/windows/generated/winrt/base.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+using winrt::fire_and_forget;
+using winrt::Windows::Devices::Enumeration::DeviceInformation;
+using winrt::Windows::Devices::Enumeration::DeviceInformationKind;
+using winrt::Windows::Devices::Enumeration::DeviceInformationUpdate;
+using winrt::Windows::Devices::Enumeration::DeviceWatcher;
+using winrt::Windows::Foundation::IInspectable;
+using winrt::Windows::Foundation::Collections::IMapView;
+using winrt::Windows::Networking::HostName;
+using winrt::Windows::Networking::Connectivity::NetworkInformation;
+using winrt::Windows::Networking::ServiceDiscovery::Dnssd::
+ DnssdRegistrationResult;
+using winrt::Windows::Networking::ServiceDiscovery::Dnssd::
+ DnssdRegistrationStatus;
+using winrt::Windows::Networking::ServiceDiscovery::Dnssd::DnssdServiceInstance;
+using winrt::Windows::Networking::Sockets::StreamSocket;
+using winrt::Windows::Networking::Sockets::StreamSocketListener;
+using winrt::Windows::Networking::Sockets::
+ StreamSocketListenerConnectionReceivedEventArgs;
+using winrt::Windows::Networking::Sockets::StreamSocketListenerInformation;
+using winrt::Windows::Storage::Streams::Buffer;
+using winrt::Windows::Storage::Streams::DataReader;
+using winrt::Windows::Storage::Streams::IBuffer;
+using winrt::Windows::Storage::Streams::IInputStream;
+using winrt::Windows::Storage::Streams::InputStreamOptions;
+using winrt::Windows::Storage::Streams::IOutputStream;
+
+// WifiLanSocket wraps the socket functions to read and write stream.
+// In WiFi LAN, A WifiLanSocket will be passed to StartAcceptingConnections's
+// call back when StreamSocketListener got connect. When call API to connect to
+// remote WiFi LAN service, also will return a WifiLanSocket to caller.
+class WifiLanSocket : public api::WifiLanSocket {
+ public:
+ explicit WifiLanSocket(StreamSocket socket);
+ WifiLanSocket(WifiLanSocket&) = default;
+ WifiLanSocket(WifiLanSocket&&) = default;
+ ~WifiLanSocket() override;
+ WifiLanSocket& operator=(const WifiLanSocket&) = default;
+ WifiLanSocket& operator=(WifiLanSocket&&) = default;
+
+ // Returns the InputStream of the WifiLanSocket.
+ // On error, returned stream will report Exception::kIo on any operation.
+ //
+ // The returned object is not owned by the caller, and can be invalidated once
+ // the WifiLanSocket object is destroyed.
+ InputStream& GetInputStream() override;
+
+ // Returns the OutputStream of the WifiLanSocket.
+ // On error, returned stream will report Exception::kIo on any operation.
+ //
+ // The returned object is not owned by the caller, and can be invalidated once
+ // the WifiLanSocket object is destroyed.
+ OutputStream& GetOutputStream() override;
+
+ // Returns Exception::kIo on error, Exception::kSuccess otherwise.
+ Exception Close() override;
+
+ private:
+ // A simple wrapper to handle input stream of socket
+ class SocketInputStream : public InputStream {
+ public:
+ SocketInputStream(IInputStream input_stream);
+ ~SocketInputStream() = default;
+
+ ExceptionOr<ByteArray> Read(std::int64_t size) override;
+ ExceptionOr<size_t> Skip(size_t offset) override;
+ Exception Close() override;
+
+ private:
+ IInputStream input_stream_{nullptr};
+ };
+
+ // A simple wrapper to handle output stream of socket
+ class SocketOutputStream : public OutputStream {
+ public:
+ SocketOutputStream(IOutputStream output_stream);
+ ~SocketOutputStream() = default;
+
+ Exception Write(const ByteArray& data) override;
+ Exception Flush() override;
+ Exception Close() override;
+
+ private:
+ IOutputStream output_stream_{nullptr};
+ };
+
+ // Internal properties
+ StreamSocket stream_soket_{nullptr};
+ SocketInputStream input_stream_{nullptr};
+ SocketOutputStream output_stream_{nullptr};
+};
+
+// WifiLanServerSocket provides the support to server socket, this server socket
+// accepts connection from clients.
+class WifiLanServerSocket : public api::WifiLanServerSocket {
+ public:
+ explicit WifiLanServerSocket(int port = 0);
+ WifiLanServerSocket(WifiLanServerSocket&) = default;
+ WifiLanServerSocket(WifiLanServerSocket&&) = default;
+ ~WifiLanServerSocket() override;
+ WifiLanServerSocket& operator=(const WifiLanServerSocket&) = default;
+ WifiLanServerSocket& operator=(WifiLanServerSocket&&) = default;
+
+ // Returns ip address.
+ std::string GetIPAddress() const override;
+
+ // Returns port.
+ int GetPort() const override;
+
+ // Sets port
+ void SetPort(int port) { port_ = port; }
+
+ StreamSocketListener GetSocketListener() const {
+ return stream_socket_listener_;
+ }
+
+ // Blocks until either:
+ // - at least one incoming connection request is available, or
+ // - ServerSocket is closed.
+ // On success, returns connected socket, ready to exchange data.
+ // Returns nullptr on error.
+ // Once error is reported, it is permanent, and ServerSocket has to be closed.
+ std::unique_ptr<api::WifiLanSocket> Accept() override;
+
+ // Called by the server side of a connection before passing ownership of
+ // WifiLanServerSocker to user, to track validity of a pointer to this
+ // server socket.
+ void SetCloseNotifier(std::function<void()> notifier);
+
+ // Returns Exception::kIo on error, Exception::kSuccess otherwise.
+ Exception Close() override;
+
+ // Binds to local port
+ bool listen();
+
+ private:
+ // The listener is accepting incoming connections
+ fire_and_forget Listener_ConnectionReceived(
+ StreamSocketListener listener,
+ StreamSocketListenerConnectionReceivedEventArgs const& args);
+
+ // Retrieves IP addresses from local machine
+ std::vector<std::string> GetIpAddresses();
+
+ mutable absl::Mutex mutex_;
+ absl::CondVar cond_;
+ std::deque<StreamSocket> pending_sockets_ ABSL_GUARDED_BY(mutex_);
+ StreamSocketListener stream_socket_listener_{nullptr};
+ winrt::event_token listener_event_token_{};
+
+ // Close notifier
+ std::function<void()> close_notifier_ = nullptr;
+
+ // IP addresses of the computer. mDNS uses them to advertise.
+ std::vector<std::string> ip_addresses_{};
+
+ // Cache socket not be picked by upper layer
+ int port_ = 0;
+ bool closed_ = false;
+};
+
+// Container of operations that can be performed over the WifiLan medium.
+class WifiLanMedium : public api::WifiLanMedium {
+ public:
+ ~WifiLanMedium() override = default;
+
+ // Starts to advertising
+ bool StartAdvertising(const NsdServiceInfo& nsd_service_info) override;
+
+ // Stops to advertising
+ bool StopAdvertising(const NsdServiceInfo& nsd_service_info) override;
+
+ // Starts to discovery
+ bool StartDiscovery(const std::string& service_type,
+ DiscoveredServiceCallback callback) override;
+
+ // Returns true once WifiLan discovery for service_type is well and truly
+ // stopped; after this returns, there must be no more invocations of the
+ // DiscoveredServiceCallback passed in to StartDiscovery() for service_type.
+ bool StopDiscovery(const std::string& service_type) override;
+
+ std::unique_ptr<api::WifiLanSocket> ConnectToService(
+ const NsdServiceInfo& remote_service_info,
+ CancellationFlag* cancellation_flag) override;
+
+ std::unique_ptr<api::WifiLanSocket> ConnectToService(
+ const std::string& ip_address, int port,
+ CancellationFlag* cancellation_flag) override;
+
+ std::unique_ptr<api::WifiLanServerSocket> ListenForService(
+ int port = 0) override;
+
+ // DnsServiceDeRegister is a async process, after operation finish, callback
+ // will call this method to notify the waiting method StopAdvertising to
+ // continue.
+ void NotifyDnsServiceUnregistered(DWORD status);
+
+ absl::optional<std::pair<std::int32_t, std::int32_t>> GetDynamicPortRange()
+ override {
+ return absl::nullopt;
+ }
+
+ private:
+ // mDNS text attributes
+ static constexpr std::string_view KEY_ENDPOINT_INFO = "n";
+
+ // mDNS information for advertising and discovery
+ static constexpr std::wstring_view MDNS_HOST_NAME = L"Windows.local";
+ static constexpr std::string_view MDNS_INSTANCE_NAME_FORMAT = "%s.%slocal";
+ static constexpr std::string_view MDNS_DEVICE_SELECTOR_FORMAT =
+ "System.Devices.AepService.ProtocolId:=\"{4526e8c1-8aac-4153-9b16-"
+ "55e86ada0e54}\" "
+ "AND System.Devices.Dnssd.ServiceName:=\"%s\" AND "
+ "System.Devices.Dnssd.Domain:=\"local\"";
+
+ // Nsd status
+ static const int MEDIUM_STATUS_IDLE = 0;
+ static const int MEDIUM_STATUS_ACCEPTING = (1 << 0);
+ static const int MEDIUM_STATUS_ADVERTISING = (1 << 1);
+ static const int MEDIUM_STATUS_DISCOVERING = (1 << 2);
+
+ // In the class, not using ENUM to describe the mDNS states, because a little
+ // complicate to combine all states based on accepting, advertising and
+ // discovery.
+ bool IsIdle() { return medium_status_ == 0; }
+
+ bool IsAccepting() { return (medium_status_ & MEDIUM_STATUS_ACCEPTING) != 0; }
+
+ bool IsAdvertising() {
+ return (medium_status_ & MEDIUM_STATUS_ADVERTISING) != 0;
+ }
+
+ bool IsDiscovering() {
+ return (medium_status_ & MEDIUM_STATUS_DISCOVERING) != 0;
+ }
+
+ // From mDNS device information, to build NsdServiceInfo.
+ // the properties are from DeviceInformation and DeviceInformationUpdate.
+ // The API gets IP addresses, service name and text attributes of mDNS
+ // from these properties,
+ NsdServiceInfo GetNsdServiceInformation(
+ IMapView<winrt::hstring, IInspectable> properties);
+
+ // mDNS callbacks for advertising and discovery
+ fire_and_forget Watcher_DeviceAdded(DeviceWatcher sender,
+ DeviceInformation deviceInfo);
+ fire_and_forget Watcher_DeviceUpdated(
+ DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate);
+ fire_and_forget Watcher_DeviceRemoved(
+ DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate);
+ static void Advertising_StopCompleted(DWORD Status, PVOID pQueryContext,
+ PDNS_SERVICE_INSTANCE pInstance);
+
+ // Gets error message from exception pointer
+ std::string GetErrorMessage(std::exception_ptr eptr);
+
+ //
+ // Dns-sd related properties
+ //
+
+ // Advertising properties
+ DnssdServiceInstance dnssd_service_instance_{nullptr};
+ DnssdRegistrationResult dnssd_regirstraion_result_{nullptr};
+
+ // Stop advertising properties
+ DNS_SERVICE_INSTANCE dns_service_instance_{nullptr};
+ DNS_SERVICE_REGISTER_REQUEST dns_service_register_request_;
+ std::unique_ptr<std::wstring> dns_service_instance_name_{nullptr};
+ std::unique_ptr<CountDownLatch> dns_service_stop_latch_;
+ DWORD dns_service_stop_status_;
+
+ // Discovery properties
+ DeviceWatcher device_watcher_{nullptr};
+ winrt::event_token device_watcher_added_event_token;
+ winrt::event_token device_watcher_updated_event_token;
+ winrt::event_token device_watcher_removed_event_token;
+
+ // callback for discovery
+ api::WifiLanMedium::DiscoveredServiceCallback discovered_service_callback_;
+
+ // Protects to access some members
+ absl::Mutex mutex_;
+
+ // Medium Status
+ int medium_status_ = MEDIUM_STATUS_IDLE;
+
+ // Keep the server socket listener pointer
+ WifiLanServerSocket* server_socket_ptr_ ABSL_GUARDED_BY(mutex_) = nullptr;
+};
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_IMPL_WINDOWS_WIFI_LAN_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/wifi_lan_medium.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/wifi_lan_medium.cc
new file mode 100644
index 00000000000..c69eea5abad
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/wifi_lan_medium.cc
@@ -0,0 +1,487 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/windows/wifi_lan.h"
+
+// Windows headers
+#include <windows.h>
+
+// Standard C/C++ headers
+#include <codecvt>
+#include <locale>
+#include <string>
+
+// ABSL headers
+#include "absl/strings/str_format.h"
+
+// Nearby connections headers
+#include "internal/platform/cancellation_flag_listener.h"
+#include "internal/platform/implementation/windows/utils.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/mutex_lock.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+bool WifiLanMedium::StartAdvertising(const NsdServiceInfo& nsd_service_info) {
+ absl::MutexLock lock(&mutex_);
+
+ if (!IsAccepting()) {
+ NEARBY_LOGS(WARNING)
+ << "cannot start advertising without accepting connetions.";
+ return false;
+ }
+
+ if (IsAdvertising()) {
+ NEARBY_LOGS(WARNING)
+ << "cannot start advertising again when it is running.";
+ return false;
+ }
+
+ if (nsd_service_info.GetTxtRecord(KEY_ENDPOINT_INFO.data()).empty()) {
+ NEARBY_LOGS(ERROR) << "cannot start advertising without endpoint info.";
+ return false;
+ }
+
+ if (nsd_service_info.GetServiceName().empty()) {
+ NEARBY_LOGS(ERROR) << "cannot start advertising without service name.";
+ return false;
+ }
+
+ std::string instance_name = absl::StrFormat(
+ MDNS_INSTANCE_NAME_FORMAT.data(), nsd_service_info.GetServiceName(),
+ nsd_service_info.GetServiceType());
+
+ NEARBY_LOGS(INFO) << "mDNS instance name is " << instance_name;
+
+ dnssd_service_instance_ = DnssdServiceInstance{
+ string_to_wstring(instance_name),
+ nullptr, // let windows use default computer's local name
+ (uint16)nsd_service_info.GetPort()};
+
+ // Add TextRecords from NsdServiceInfo
+ auto text_attributes = dnssd_service_instance_.TextAttributes();
+
+ auto text_records = nsd_service_info.GetTxtRecords();
+ auto it = text_records.begin();
+ while (it != text_records.end()) {
+ text_attributes.Insert(string_to_wstring(it->first),
+ string_to_wstring(it->second));
+ it++;
+ }
+
+ dnssd_regirstraion_result_ = dnssd_service_instance_
+ .RegisterStreamSocketListenerAsync(
+ server_socket_ptr_->GetSocketListener())
+ .get();
+
+ if (dnssd_regirstraion_result_.HasInstanceNameChanged()) {
+ NEARBY_LOGS(WARNING) << "advertising instance name was changed due to have "
+ "same name instance was running.";
+ // stop the service and return false
+ StopAdvertising(nsd_service_info);
+ return false;
+ }
+
+ if (dnssd_regirstraion_result_.Status() == DnssdRegistrationStatus::Success) {
+ NEARBY_LOGS(INFO) << "started to advertising.";
+ medium_status_ |= MEDIUM_STATUS_ADVERTISING;
+ return true;
+ }
+
+ // Clean up
+ NEARBY_LOGS(ERROR)
+ << "failed to start advertising due to registration failure.";
+ dnssd_service_instance_ = nullptr;
+ dnssd_regirstraion_result_ = nullptr;
+ return false;
+}
+
+// Win32 call only can use globel function or static method in class
+void WifiLanMedium::Advertising_StopCompleted(DWORD Status, PVOID pQueryContext,
+ PDNS_SERVICE_INSTANCE pInstance) {
+ NEARBY_LOGS(INFO) << "unregister with status=" << Status;
+ try {
+ WifiLanMedium* medium = static_cast<WifiLanMedium*>(pQueryContext);
+ medium->NotifyDnsServiceUnregistered(Status);
+ } catch (...) {
+ NEARBY_LOGS(ERROR) << "failed to notify the stop of DNS service instance."
+ << Status;
+ }
+}
+
+void WifiLanMedium::NotifyDnsServiceUnregistered(DWORD status) {
+ if (dns_service_stop_latch_.get() != nullptr) {
+ dns_service_stop_status_ = status;
+ dns_service_stop_latch_.get()->CountDown();
+ }
+}
+
+bool WifiLanMedium::StopAdvertising(const NsdServiceInfo& nsd_service_info) {
+ // Need to use Win32 API to deregister the Dnssd instance
+ if (!IsAdvertising()) {
+ NEARBY_LOGS(WARNING)
+ << "Cannot stop advertising because no advertising is running.";
+ return false;
+ }
+
+ // Init DNS service instance
+ std::string instance_name = absl::StrFormat(
+ MDNS_INSTANCE_NAME_FORMAT.data(), nsd_service_info.GetServiceName(),
+ nsd_service_info.GetServiceType());
+ int port = nsd_service_info.GetPort();
+ dns_service_instance_name_ =
+ std::make_unique<std::wstring>(string_to_wstring(instance_name));
+
+ dns_service_instance_.pszInstanceName =
+ (LPWSTR)dns_service_instance_name_->c_str();
+ dns_service_instance_.pszHostName = (LPWSTR)MDNS_HOST_NAME.data();
+ dns_service_instance_.wPort = port;
+
+ // Init DNS service register request
+ dns_service_register_request_.Version = DNS_QUERY_REQUEST_VERSION1;
+ dns_service_register_request_.InterfaceIndex =
+ 0; // all interfaces will be considered
+ dns_service_register_request_.unicastEnabled = false;
+ dns_service_register_request_.hCredentials = NULL;
+ dns_service_register_request_.pServiceInstance = &dns_service_instance_;
+ dns_service_register_request_.pQueryContext = this; // callback use it
+ dns_service_register_request_.pRegisterCompletionCallback =
+ WifiLanMedium::Advertising_StopCompleted;
+
+ dns_service_stop_latch_ = std::make_unique<CountDownLatch>(1);
+ DWORD status = DnsServiceDeRegister(&dns_service_register_request_, nullptr);
+
+ if (status != DNS_REQUEST_PENDING) {
+ NEARBY_LOGS(ERROR) << "failed to stop mDNS advertising for service type ="
+ << nsd_service_info.GetServiceType();
+ return false;
+ }
+
+ // Wait for stop finish
+ dns_service_stop_latch_.get()->Await();
+ dns_service_stop_latch_ = nullptr;
+ if (dns_service_stop_status_ != 0) {
+ NEARBY_LOGS(INFO) << "failed to stop mDNS advertising for service type ="
+ << nsd_service_info.GetServiceType();
+ return false;
+ }
+
+ NEARBY_LOGS(INFO) << "succeeded to stop mDNS advertising for service type ="
+ << nsd_service_info.GetServiceType();
+ medium_status_ &= (~MEDIUM_STATUS_ADVERTISING);
+ return true;
+}
+
+// Returns true once the WifiLan discovery has been initiated.
+bool WifiLanMedium::StartDiscovery(const std::string& service_type,
+ DiscoveredServiceCallback callback) {
+ if (IsDiscovering()) {
+ NEARBY_LOGS(WARNING) << "discovery already running for service type ="
+ << service_type;
+ return false;
+ }
+
+ // In WifiLan::StartDiscovery(), service_type is appended with "._tcp." for
+ // ios and android platform. For windows, this has to be removed because
+ // "._tcp" will be appended in following "selector"
+ std::string service_type_trim = service_type;
+ if (service_type.size() > 5 &&
+ (service_type.rfind("_tcp.") == service_type.size() - 5)) {
+ service_type_trim.resize(service_type_trim.size() - 1);
+ }
+
+ std::string selector =
+ absl::StrFormat(MDNS_DEVICE_SELECTOR_FORMAT.data(), service_type_trim);
+
+ std::vector<winrt::hstring> requestedProperties{
+ L"System.Devices.IpAddress",
+ L"System.Devices.Dnssd.HostName",
+ L"System.Devices.Dnssd.InstanceName",
+ L"System.Devices.Dnssd.PortNumber",
+ L"System.Devices.Dnssd.ServiceName",
+ L"System.Devices.Dnssd.TextAttributes"};
+
+ device_watcher_ = DeviceInformation::CreateWatcher(
+ string_to_wstring(selector), requestedProperties,
+ DeviceInformationKind::AssociationEndpointService);
+
+ device_watcher_added_event_token =
+ device_watcher_.Added({this, &WifiLanMedium::Watcher_DeviceAdded});
+ device_watcher_updated_event_token =
+ device_watcher_.Updated({this, &WifiLanMedium::Watcher_DeviceUpdated});
+ device_watcher_removed_event_token =
+ device_watcher_.Removed({this, &WifiLanMedium::Watcher_DeviceRemoved});
+
+ device_watcher_.Start();
+ discovered_service_callback_ = std::move(callback);
+ medium_status_ |= MEDIUM_STATUS_DISCOVERING;
+
+ NEARBY_LOGS(INFO) << "started to discovery.";
+
+ return true;
+}
+
+// Returns true once WifiLan discovery for service_id is well and truly
+// stopped; after this returns, there must be no more invocations of the
+// DiscoveredServiceCallback passed in to StartDiscovery() for service_id.
+bool WifiLanMedium::StopDiscovery(const std::string& service_type) {
+ if (!IsDiscovering()) {
+ NEARBY_LOGS(WARNING) << "no discovering service to stop.";
+ return false;
+ }
+ device_watcher_.Stop();
+ device_watcher_.Added(device_watcher_added_event_token);
+ device_watcher_.Updated(device_watcher_updated_event_token);
+ device_watcher_.Removed(device_watcher_removed_event_token);
+ medium_status_ &= (~MEDIUM_STATUS_DISCOVERING);
+ device_watcher_ = nullptr;
+ return true;
+}
+
+std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
+ const NsdServiceInfo& remote_service_info,
+ CancellationFlag* cancellation_flag) {
+ NEARBY_LOGS(ERROR)
+ << "connect to service by NSD service info. service type is "
+ << remote_service_info.GetServiceType();
+
+ return ConnectToService(remote_service_info.GetIPAddress(),
+ remote_service_info.GetPort(), cancellation_flag);
+}
+
+std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
+ const std::string& ip_address, int port,
+ CancellationFlag* cancellation_flag) {
+ if (ip_address.empty() || port == 0) {
+ NEARBY_LOGS(ERROR) << "no valid service address and port to connect.";
+ return nullptr;
+ }
+
+ HostName host_name{string_to_wstring(ip_address)};
+ winrt::hstring service_name{winrt::to_hstring(port)};
+
+ StreamSocket socket{};
+
+ // setup cancel listener
+ if (cancellation_flag != nullptr) {
+ if (cancellation_flag->Cancelled()) {
+ NEARBY_LOGS(INFO) << "connect has been cancelled to service "
+ << ip_address << ":" << port;
+ return nullptr;
+ }
+
+ location::nearby::CancellationFlagListener cancellationFlagListener(
+ cancellation_flag, [socket]() { socket.CancelIOAsync().get(); });
+ }
+
+ // connection to the service
+ try {
+ socket.ConnectAsync(host_name, service_name).get();
+ // connected need to keep connection
+
+ std::unique_ptr<WifiLanSocket> wifi_lan_socket =
+ std::make_unique<WifiLanSocket>(socket);
+
+ NEARBY_LOGS(INFO) << "connected to remote service " << ip_address << ":"
+ << port;
+ return wifi_lan_socket;
+ } catch (...) {
+ NEARBY_LOGS(ERROR) << "failed to connect remote service " << ip_address
+ << ":" << port;
+ }
+
+ return nullptr;
+}
+
+std::unique_ptr<api::WifiLanServerSocket> WifiLanMedium::ListenForService(
+ int port) {
+ absl::MutexLock lock(&mutex_);
+
+ // check current status
+ if (IsAccepting()) {
+ NEARBY_LOGS(WARNING) << "accepting connections already started on port "
+ << server_socket_ptr_->GetPort();
+ return nullptr;
+ }
+
+ std::unique_ptr<WifiLanServerSocket> server_socket =
+ std::make_unique<WifiLanServerSocket>(port);
+ server_socket_ptr_ = server_socket.get();
+
+ server_socket->SetCloseNotifier([this]() {
+ absl::MutexLock lock(&mutex_);
+ NEARBY_LOGS(INFO) << "server socket was closed on port "
+ << server_socket_ptr_->GetPort();
+ medium_status_ &= (~MEDIUM_STATUS_ACCEPTING);
+ server_socket_ptr_ = nullptr;
+ });
+
+ if (server_socket->listen()) {
+ medium_status_ |= MEDIUM_STATUS_ACCEPTING;
+ NEARBY_LOGS(INFO) << "started to listen serive on port " << port;
+ return server_socket;
+ }
+
+ NEARBY_LOGS(ERROR) << "Failed to listen service on port " << port;
+
+ return nullptr;
+}
+
+NsdServiceInfo WifiLanMedium::GetNsdServiceInformation(
+ IMapView<winrt::hstring, IInspectable> properties) {
+ NsdServiceInfo nsd_service_info{};
+
+ // Service name information
+ IInspectable inspectable =
+ properties.TryLookup(L"System.Devices.Dnssd.InstanceName");
+ if (inspectable == nullptr) {
+ NEARBY_LOGS(WARNING)
+ << "no service name information in device information.";
+ return nsd_service_info;
+ }
+ nsd_service_info.SetServiceName(InspectableReader::ReadString(inspectable));
+
+ // Service type information
+ inspectable = properties.TryLookup(L"System.Devices.Dnssd.ServiceName");
+ if (inspectable == nullptr) {
+ NEARBY_LOGS(WARNING)
+ << "no service type information in device information.";
+ return nsd_service_info;
+ }
+
+ // In WifiLan::StartDiscovery(), service_type is appended with "._tcp." for
+ // ios and android platform. For windows, we only have "._tcp" as appendix.
+ // Here "." is added back to match the upper layer service_type, because
+ // service_type is used to get the corresponding call back function.
+ nsd_service_info.SetServiceType(
+ (InspectableReader::ReadString(inspectable)).append("."));
+
+ // IP Address information
+ inspectable = properties.TryLookup(L"System.Devices.IPAddress");
+ if (inspectable == nullptr) {
+ NEARBY_LOGS(WARNING) << "no IP address information in device information.";
+ return nsd_service_info;
+ }
+
+ auto ipaddresses = InspectableReader::ReadStringArray(inspectable);
+ if (ipaddresses.size() == 0) {
+ NEARBY_LOGS(WARNING) << "no IP address information in device information.";
+ return nsd_service_info;
+ }
+
+ std::string ip_address = ipaddresses[0];
+
+ // read IP port
+ inspectable = properties.TryLookup(L"System.Devices.Dnssd.PortNumber");
+ if (inspectable == nullptr) {
+ NEARBY_LOGS(WARNING) << "no IP port information in device information.";
+ return nsd_service_info;
+ }
+
+ int port = InspectableReader::ReadUint16(inspectable);
+ nsd_service_info.SetIPAddress(ip_address);
+ nsd_service_info.SetPort(port);
+
+ // read text record
+ inspectable = properties.TryLookup(L"System.Devices.Dnssd.TextAttributes");
+ if (inspectable == nullptr) {
+ NEARBY_LOGS(WARNING)
+ << "no text attributes information in device information.";
+ return nsd_service_info;
+ }
+
+ auto text_attributes = InspectableReader::ReadStringArray(inspectable);
+ for (auto text_attribute : text_attributes) {
+ // text attribute in format key=value
+ int pos = text_attribute.find("=");
+ if (pos <= 0 || pos == text_attribute.size() - 1) {
+ NEARBY_LOGS(WARNING) << "found invalid text attribute " << text_attribute;
+ continue;
+ }
+
+ std::string key = text_attribute.substr(0, pos);
+ std::string value = text_attribute.substr(pos + 1);
+ nsd_service_info.SetTxtRecord(key, value);
+ }
+
+ return nsd_service_info;
+}
+
+fire_and_forget WifiLanMedium::Watcher_DeviceAdded(
+ DeviceWatcher sender, DeviceInformation deviceInfo) {
+ // need to read IP address and port information from deviceInfo
+ NsdServiceInfo nsd_service_info =
+ GetNsdServiceInformation(deviceInfo.Properties());
+
+ NEARBY_LOGS(INFO) << "device added for service name "
+ << nsd_service_info.GetServiceName();
+
+ std::string endpoint =
+ nsd_service_info.GetTxtRecord(KEY_ENDPOINT_INFO.data());
+ if (endpoint.empty()) {
+ return fire_and_forget{};
+ }
+
+ discovered_service_callback_.service_discovered_cb(nsd_service_info);
+
+ return fire_and_forget();
+}
+fire_and_forget WifiLanMedium::Watcher_DeviceUpdated(
+ DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate) {
+ // TODO(b/200421481): discovery servcie callback needs to support device
+ // update.
+ NsdServiceInfo nsd_service_info =
+ GetNsdServiceInformation(deviceInfoUpdate.Properties());
+ NEARBY_LOGS(INFO) << "device updated for service name "
+ << nsd_service_info.GetServiceName();
+
+ return fire_and_forget();
+}
+fire_and_forget WifiLanMedium::Watcher_DeviceRemoved(
+ DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate) {
+ // need to read IP address and port information from deviceInfo
+ NsdServiceInfo nsd_service_info =
+ GetNsdServiceInformation(deviceInfoUpdate.Properties());
+
+ NEARBY_LOGS(INFO) << "device removed for service name "
+ << nsd_service_info.GetServiceName();
+
+ std::string endpoint =
+ nsd_service_info.GetTxtRecord(KEY_ENDPOINT_INFO.data());
+ if (endpoint.empty()) {
+ return fire_and_forget{};
+ }
+
+ discovered_service_callback_.service_lost_cb(nsd_service_info);
+
+ return fire_and_forget();
+}
+
+std::string WifiLanMedium::GetErrorMessage(std::exception_ptr eptr) {
+ try {
+ if (eptr) {
+ std::rethrow_exception(eptr);
+ } else {
+ return "";
+ }
+ } catch (const std::exception& e) {
+ return e.what();
+ }
+}
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/wifi_lan_server_socket.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/wifi_lan_server_socket.cc
new file mode 100644
index 00000000000..85112990dd1
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/wifi_lan_server_socket.cc
@@ -0,0 +1,180 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/windows/utils.h"
+#include "internal/platform/implementation/windows/wifi_lan.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+WifiLanServerSocket::WifiLanServerSocket(int port) : port_(port) {}
+
+WifiLanServerSocket::~WifiLanServerSocket() { Close(); }
+
+// Returns ip address.
+std::string WifiLanServerSocket::GetIPAddress() const {
+ if (stream_socket_listener_ == nullptr) {
+ return {};
+ }
+
+ auto host_names = NetworkInformation::GetHostNames();
+ for (auto host_name : host_names) {
+ if (host_name.IPInformation() != nullptr &&
+ host_name.IPInformation().NetworkAdapter() != nullptr) {
+ return wstring_to_string(host_name.ToString().c_str());
+ }
+ }
+
+ return {};
+}
+
+// Returns port.
+int WifiLanServerSocket::GetPort() const {
+ if (stream_socket_listener_ == nullptr) {
+ return 0;
+ }
+
+ return std::stoi(stream_socket_listener_.Information().LocalPort().c_str());
+}
+
+// Blocks until either:
+// - at least one incoming connection request is available, or
+// - ServerSocket is closed.
+// On success, returns connected socket, ready to exchange data.
+// Returns nullptr on error.
+// Once error is reported, it is permanent, and ServerSocket has to be closed.
+std::unique_ptr<api::WifiLanSocket> WifiLanServerSocket::Accept() {
+ absl::MutexLock lock(&mutex_);
+ while (!closed_ && pending_sockets_.empty()) {
+ cond_.Wait(&mutex_);
+ }
+ if (closed_) return {};
+
+ StreamSocket wifi_lan_socket = pending_sockets_.front();
+ pending_sockets_.pop_front();
+ return std::make_unique<WifiLanSocket>(wifi_lan_socket);
+}
+
+void WifiLanServerSocket::SetCloseNotifier(std::function<void()> notifier) {
+ close_notifier_ = std::move(notifier);
+}
+
+// Returns Exception::kIo on error, Exception::kSuccess otherwise.
+Exception WifiLanServerSocket::Close() {
+ try {
+ absl::MutexLock lock(&mutex_);
+ if (closed_) {
+ return {Exception::kSuccess};
+ }
+ if (stream_socket_listener_ != nullptr) {
+ stream_socket_listener_.ConnectionReceived(listener_event_token_);
+ stream_socket_listener_.Close();
+ stream_socket_listener_ = nullptr;
+
+ if (!pending_sockets_.empty()) {
+ auto it = pending_sockets_.begin();
+ while (it != pending_sockets_.end()) {
+ it->Close();
+ }
+ }
+
+ cond_.SignalAll();
+ }
+ closed_ = true;
+ if (close_notifier_ != nullptr) {
+ close_notifier_();
+ }
+ return {Exception::kSuccess};
+ } catch (...) {
+ return {Exception::kIo};
+ }
+}
+
+bool WifiLanServerSocket::listen() {
+ // Check IP address
+ ip_addresses_ = GetIpAddresses();
+
+ if (ip_addresses_.empty()) {
+ NEARBY_LOGS(WARNING) << "failed to start accepting connection without IP "
+ "addresses configured on computer.";
+ return false;
+ }
+
+ // Save connection callback
+ stream_socket_listener_ = StreamSocketListener();
+
+ // Setup callback
+ listener_event_token_ = stream_socket_listener_.ConnectionReceived(
+ {this, &WifiLanServerSocket::Listener_ConnectionReceived});
+
+ try {
+ stream_socket_listener_.BindServiceNameAsync(winrt::to_hstring(port_))
+ .get();
+ if (port_ == 0) {
+ port_ =
+ std::stoi(stream_socket_listener_.Information().LocalPort().c_str());
+ }
+
+ return true;
+ } catch (...) {
+ // Cannot bind to the preferred port, will let system to assign port.
+ NEARBY_LOGS(WARNING) << "cannot accept connection on preferred port.";
+ }
+
+ try {
+ stream_socket_listener_.BindServiceNameAsync({}).get();
+ // need to save the port information
+ port_ =
+ std::stoi(stream_socket_listener_.Information().LocalPort().c_str());
+ return true;
+ } catch (...) {
+ // Cannot bind to the preferred port, will let system to assign port.
+ NEARBY_LOGS(ERROR) << "cannot bind to any port.";
+ }
+
+ return false;
+}
+
+fire_and_forget WifiLanServerSocket::Listener_ConnectionReceived(
+ StreamSocketListener listener,
+ StreamSocketListenerConnectionReceivedEventArgs const& args) {
+ absl::MutexLock lock(&mutex_);
+
+ if (closed_) {
+ return fire_and_forget{};
+ }
+
+ pending_sockets_.push_back(args.Socket());
+ cond_.SignalAll();
+ return fire_and_forget{};
+}
+
+// Retrieves IP addresses from local machine
+std::vector<std::string> WifiLanServerSocket::GetIpAddresses() {
+ std::vector<std::string> result{};
+ auto host_names = NetworkInformation::GetHostNames();
+ for (auto host_name : host_names) {
+ if (host_name.IPInformation() != nullptr &&
+ host_name.IPInformation().NetworkAdapter() != nullptr) {
+ result.push_back(wstring_to_string(host_name.ToString().c_str()));
+ }
+ }
+ return result;
+}
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/implementation/windows/wifi_lan_socket.cc b/chromium/third_party/nearby/src/internal/platform/implementation/windows/wifi_lan_socket.cc
new file mode 100644
index 00000000000..64d07d0e9ef
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/implementation/windows/wifi_lan_socket.cc
@@ -0,0 +1,142 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/implementation/windows/wifi_lan.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace windows {
+
+WifiLanSocket::WifiLanSocket(StreamSocket socket) {
+ stream_soket_ = socket;
+ input_stream_ = SocketInputStream(socket.InputStream());
+ output_stream_ = SocketOutputStream(socket.OutputStream());
+}
+
+WifiLanSocket::~WifiLanSocket() {
+ if (stream_soket_ != nullptr) {
+ try {
+ Close();
+ } catch (...) {
+ NEARBY_LOGS(ERROR) << "Failed to destructor class WifiLanSocket.";
+ }
+ }
+}
+
+InputStream& WifiLanSocket::GetInputStream() { return input_stream_; }
+
+OutputStream& WifiLanSocket::GetOutputStream() { return output_stream_; }
+
+Exception WifiLanSocket::Close() {
+ try {
+ if (stream_soket_ != nullptr) {
+ stream_soket_.Close();
+ }
+ return {Exception::kSuccess};
+ } catch (...) {
+ return {Exception::kIo};
+ }
+}
+
+// SocketInputStream
+WifiLanSocket::SocketInputStream::SocketInputStream(IInputStream input_stream) {
+ input_stream_ = input_stream;
+}
+
+ExceptionOr<ByteArray> WifiLanSocket::SocketInputStream::Read(
+ std::int64_t size) {
+ try {
+ Buffer buffer = Buffer(size);
+
+ auto ibuffer =
+ input_stream_.ReadAsync(buffer, size, InputStreamOptions::None).get();
+
+ if (ibuffer.Length() != size) {
+ NEARBY_LOGS(WARNING) << "Only got part of data of needed.";
+ }
+
+ ByteArray data((char*)ibuffer.data(), ibuffer.Length());
+
+ return ExceptionOr(data);
+ } catch (...) {
+ return Exception{Exception::kIo};
+ }
+}
+
+ExceptionOr<size_t> WifiLanSocket::SocketInputStream::Skip(size_t offset) {
+ try {
+ Buffer buffer = Buffer(offset);
+
+ auto ibuffer =
+ input_stream_.ReadAsync(buffer, offset, InputStreamOptions::None).get();
+ return ExceptionOr((size_t)ibuffer.Length());
+ } catch (...) {
+ return Exception{Exception::kIo};
+ }
+}
+
+Exception WifiLanSocket::SocketInputStream::Close() {
+ try {
+ input_stream_.Close();
+ } catch (...) {
+ return {Exception::kIo};
+ }
+
+ return {Exception::kSuccess};
+}
+
+// SocketOutputStream
+WifiLanSocket::SocketOutputStream::SocketOutputStream(
+ IOutputStream output_stream) {
+ output_stream_ = output_stream;
+}
+
+Exception WifiLanSocket::SocketOutputStream::Write(const ByteArray& data) {
+ Buffer buffer = Buffer(data.size());
+ std::memcpy(buffer.data(), data.data(), data.size());
+ buffer.Length(data.size());
+
+ try {
+ output_stream_.WriteAsync(buffer).get();
+ } catch (...) {
+ return {Exception::kIo};
+ }
+
+ return {Exception::kSuccess};
+}
+
+Exception WifiLanSocket::SocketOutputStream::Flush() {
+ try {
+ output_stream_.FlushAsync().get();
+ } catch (...) {
+ return {Exception::kIo};
+ }
+
+ return {Exception::kSuccess};
+}
+
+Exception WifiLanSocket::SocketOutputStream::Close() {
+ try {
+ output_stream_.Close();
+ } catch (...) {
+ return {Exception::kIo};
+ }
+
+ return {Exception::kSuccess};
+}
+
+} // namespace windows
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/input_stream.cc b/chromium/third_party/nearby/src/internal/platform/input_stream.cc
new file mode 100644
index 00000000000..9bae0f7039d
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/input_stream.cc
@@ -0,0 +1,44 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/input_stream.h"
+
+#include <algorithm>
+#include <cstddef>
+#include <cstdint>
+
+#include "internal/platform/byte_array.h"
+#include "internal/platform/exception.h"
+
+namespace location {
+namespace nearby {
+namespace {
+constexpr size_t kSkipBufferSize = 64 * 1024;
+} // namespace
+
+ExceptionOr<size_t> InputStream::Skip(size_t offset) {
+ size_t bytes_left = offset;
+ while (bytes_left > 0) {
+ size_t chunk_size = std::min(bytes_left, kSkipBufferSize);
+ ExceptionOr<ByteArray> result = Read(chunk_size);
+ if (!result.ok()) {
+ return result.GetException();
+ }
+ bytes_left -= chunk_size;
+ }
+ return ExceptionOr<size_t>(offset);
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/input_stream.h b/chromium/third_party/nearby/src/internal/platform/input_stream.h
new file mode 100644
index 00000000000..905f5aa116a
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/input_stream.h
@@ -0,0 +1,46 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_BASE_INPUT_STREAM_H_
+#define PLATFORM_BASE_INPUT_STREAM_H_
+
+#include <cstdint>
+
+#include "internal/platform/byte_array.h"
+#include "internal/platform/exception.h"
+
+namespace location {
+namespace nearby {
+
+// An InputStream represents an input stream of bytes.
+//
+// https://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html
+class InputStream {
+ public:
+ virtual ~InputStream() = default;
+
+ // throws Exception::kIo
+ virtual ExceptionOr<ByteArray> Read(std::int64_t size) = 0;
+
+ // throws Exception::kIo
+ virtual ExceptionOr<size_t> Skip(size_t offset);
+
+ // throws Exception::kIo
+ virtual Exception Close() = 0;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_BASE_INPUT_STREAM_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/listeners.h b/chromium/third_party/nearby/src/internal/platform/listeners.h
index 987e4d66d51..987e4d66d51 100644
--- a/chromium/third_party/nearby/src/cpp/platform/base/listeners.h
+++ b/chromium/third_party/nearby/src/internal/platform/listeners.h
diff --git a/chromium/third_party/nearby/src/cpp/platform/public/lockable.h b/chromium/third_party/nearby/src/internal/platform/lockable.h
index 73d45721275..73d45721275 100644
--- a/chromium/third_party/nearby/src/cpp/platform/public/lockable.h
+++ b/chromium/third_party/nearby/src/internal/platform/lockable.h
diff --git a/chromium/third_party/nearby/src/internal/platform/logging.h b/chromium/third_party/nearby/src/internal/platform/logging.h
new file mode 100644
index 00000000000..794cd49ca73
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/logging.h
@@ -0,0 +1,88 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_BASE_LOGGING_H_
+#define PLATFORM_BASE_LOGGING_H_
+
+// logging.h is only included to allow logging clients to include CHECK's.
+// In Chrome this is base/check.h. See crbug/1212611.
+#ifdef NEARBY_CHROMIUM
+#include "base/check.h"
+#else
+#include "logging.h"
+#endif
+#include "internal/platform/implementation/log_message.h"
+#include "internal/platform/implementation/platform.h"
+
+namespace location {
+namespace nearby {
+
+// This class is used to explicitly ignore values in the conditional
+// logging macros. This avoids compiler warnings like "value computed
+// is not used" and "statement has no effect".
+class LogMessageVoidify {
+ public:
+ LogMessageVoidify() = default;
+ // This has to be an operator with a precedence lower than << but
+ // higher than ?:
+ void operator&(std::ostream&) {}
+};
+
+} // namespace nearby
+} // namespace location
+
+// Severity enum conversion
+#define NEARBY_SEVERITY_VERBOSE \
+ location::nearby::api::LogMessage::Severity::kVerbose
+#define NEARBY_SEVERITY_INFO location::nearby::api::LogMessage::Severity::kInfo
+#define NEARBY_SEVERITY_WARNING \
+ location::nearby::api::LogMessage::Severity::kWarning
+#define NEARBY_SEVERITY_ERROR \
+ location::nearby::api::LogMessage::Severity::kError
+#define NEARBY_SEVERITY_FATAL \
+ location::nearby::api::LogMessage::Severity::kFatal
+#if defined(_WIN32)
+// wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets substituted
+// with 0, and it expands to NEARBY_SEVERITY_0. To allow us to keep using this
+// syntax, we define this macro to do the same thing as NEARBY_SEVERITY_ERROR.
+#define NEARBY_SEVERITY_0 location::nearby::api::LogMessage::Severity::kError
+#endif // defined(_WIN32)
+#define NEARBY_SEVERITY(severity) NEARBY_SEVERITY_##severity
+
+// Log enabling
+#define NEARBY_LOG_IS_ON(severity) \
+ location::nearby::api::LogMessage::ShouldCreateLogMessage( \
+ NEARBY_SEVERITY(severity))
+
+#define NEARBY_LOG_SET_SEVERITY(severity) \
+ location::nearby::api::LogMessage::SetMinLogSeverity( \
+ NEARBY_SEVERITY(severity))
+
+// Log message creation
+#define NEARBY_LOG_MESSAGE(severity) \
+ location::nearby::api::ImplementationPlatform::CreateLogMessage( \
+ __FILE__, __LINE__, NEARBY_SEVERITY(severity))
+
+// Public APIs
+// The stream statement must come last or otherwise it won't compile.
+#define NEARBY_LOGS(severity) \
+ !(NEARBY_LOG_IS_ON(severity)) ? (void)0 \
+ : location::nearby::LogMessageVoidify() & \
+ NEARBY_LOG_MESSAGE(severity)->Stream()
+
+#define NEARBY_LOG(severity, ...) \
+ NEARBY_LOG_IS_ON(severity) \
+ ? NEARBY_LOG_MESSAGE(severity)->Print(__VA_ARGS__) : (void)0
+
+#endif // PLATFORM_BASE_LOGGING_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/logging2.h b/chromium/third_party/nearby/src/internal/platform/logging2.h
new file mode 100644
index 00000000000..2d20caa7bcd
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/logging2.h
@@ -0,0 +1,20 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_LOGGING_H_
+#define PLATFORM_PUBLIC_LOGGING_H_
+
+#include "internal/platform/logging.h"
+
+#endif // PLATFORM_PUBLIC_LOGGING_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/logging_test.cc b/chromium/third_party/nearby/src/internal/platform/logging_test.cc
new file mode 100644
index 00000000000..e4f5a82a545
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/logging_test.cc
@@ -0,0 +1,53 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/logging.h"
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+
+namespace {
+
+TEST(LoggingTest, CanLog) {
+ NEARBY_LOG_SET_SEVERITY(INFO);
+ int num = 42;
+ NEARBY_LOG(INFO, "The answer to everything: %d", num++);
+ EXPECT_EQ(num, 43);
+}
+
+TEST(LoggingTest, CanLog_LoggingDisabled) {
+ NEARBY_LOG_SET_SEVERITY(ERROR);
+ int num = 42;
+ NEARBY_LOG(INFO, "The answer to everything: %d", num++);
+ // num++ should not be evaluated
+ EXPECT_EQ(num, 42);
+}
+
+TEST(LoggingTest, CanStream) {
+ NEARBY_LOG_SET_SEVERITY(INFO);
+ int num = 42;
+ NEARBY_LOGS(INFO) << "The answer to everything: " << num++;
+ EXPECT_EQ(num, 43);
+}
+
+TEST(LoggingTest, CanStream_LoggingDisabled) {
+ NEARBY_LOG_SET_SEVERITY(ERROR);
+ int num = 42;
+ NEARBY_LOGS(INFO) << "The answer to everything: " << num++;
+ // num++ should not be evaluated
+ EXPECT_EQ(num, 42);
+}
+
+} // namespace
diff --git a/chromium/third_party/nearby/src/internal/platform/medium_environment.cc b/chromium/third_party/nearby/src/internal/platform/medium_environment.cc
new file mode 100644
index 00000000000..5d9f619e728
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/medium_environment.cc
@@ -0,0 +1,678 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/medium_environment.h"
+
+#include <atomic>
+#include <cinttypes>
+#include <functional>
+#include <new>
+#include <string>
+#include <type_traits>
+#include <utility>
+
+#include "internal/platform/feature_flags.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/prng.h"
+#include "internal/platform/count_down_latch.h"
+
+namespace location {
+namespace nearby {
+
+MediumEnvironment& MediumEnvironment::Instance() {
+ static std::aligned_storage_t<sizeof(MediumEnvironment),
+ alignof(MediumEnvironment)>
+ storage;
+ static MediumEnvironment* env = new (&storage) MediumEnvironment();
+ return *env;
+}
+
+void MediumEnvironment::Start(EnvironmentConfig config) {
+ if (!enabled_.exchange(true)) {
+ NEARBY_LOGS(INFO) << "MediumEnvironment::Start()";
+ config_ = std::move(config);
+ Reset();
+ }
+}
+
+void MediumEnvironment::Stop() {
+ if (enabled_.exchange(false)) {
+ NEARBY_LOGS(INFO) << "MediumEnvironment::Stop()";
+ Sync(false);
+ }
+}
+
+void MediumEnvironment::Reset() {
+ RunOnMediumEnvironmentThread([this]() {
+ NEARBY_LOGS(INFO) << "MediumEnvironment::Reset()";
+ bluetooth_adapters_.clear();
+ bluetooth_mediums_.clear();
+ ble_mediums_.clear();
+#ifndef NO_WEBRTC
+ webrtc_signaling_message_callback_.clear();
+ webrtc_signaling_complete_callback_.clear();
+#endif
+ wifi_lan_mediums_.clear();
+ use_valid_peer_connection_ = true;
+ peer_connection_latency_ = absl::ZeroDuration();
+ });
+ Sync();
+}
+
+void MediumEnvironment::Sync(bool enable_notifications) {
+ enable_notifications_ = enable_notifications;
+ NEARBY_LOGS(INFO) << "MediumEnvironment::sync=" << enable_notifications;
+ int count = 0;
+ do {
+ CountDownLatch latch(1);
+ count = job_count_ + 1;
+ // We are about to schedule one last job.
+ // When it is done, counter must be equal to count.
+ // However, if pending jobs schedule anything else,
+ // it will be pending after us.
+ // If we want to ensure we are completely idle, then we have to
+ // repeat sync, until this becomes true.
+ RunOnMediumEnvironmentThread([&latch]() { latch.CountDown(); });
+ latch.Await();
+ } while (count < job_count_);
+ NEARBY_LOGS(INFO) << "MediumEnvironment::Sync(): done [count=" << count
+ << "]";
+}
+
+const EnvironmentConfig& MediumEnvironment::GetEnvironmentConfig() {
+ return config_;
+}
+
+void MediumEnvironment::OnBluetoothAdapterChangedState(
+ api::BluetoothAdapter& adapter, api::BluetoothDevice& adapter_device,
+ std::string name, bool enabled, api::BluetoothAdapter::ScanMode mode) {
+ if (!enabled_) return;
+ CountDownLatch latch(1);
+ RunOnMediumEnvironmentThread([this, &adapter, &adapter_device,
+ name = std::move(name), enabled, mode,
+ &latch]() {
+ NEARBY_LOGS(INFO) << "[adapter=" << &adapter
+ << ", device=" << &adapter_device << "] update: name="
+ << ", enabled=" << enabled << ", mode=" << int32_t(mode);
+ for (auto& medium_info : bluetooth_mediums_) {
+ auto& info = medium_info.second;
+ // Do not send notification to medium that owns this adapter.
+ if (info.adapter == &adapter) continue;
+ NEARBY_LOGS(INFO) << "[adapter=" << &adapter
+ << ", device=" << &adapter_device
+ << "] notify: adapter=" << info.adapter;
+ OnBluetoothDeviceStateChanged(info, adapter_device, name, mode, enabled);
+ }
+ // We don't care if there is an adapter already since all we store is a
+ // pointer. Pointer must remain valid for the duration of a Core session
+ // (since it is owned by the correspoinding Medium, and mediums lifetime
+ // matches Core lifetime).
+ if (enabled) {
+ bluetooth_adapters_.emplace(&adapter, &adapter_device);
+ } else {
+ bluetooth_adapters_.erase(&adapter);
+ }
+ latch.CountDown();
+ });
+ latch.Await();
+}
+
+void MediumEnvironment::OnBluetoothDeviceStateChanged(
+ BluetoothMediumContext& info, api::BluetoothDevice& device,
+ const std::string& name, api::BluetoothAdapter::ScanMode mode,
+ bool enabled) {
+ if (!enabled_) return;
+ auto item = info.devices.find(&device);
+ if (item == info.devices.end()) {
+ NEARBY_LOGS(INFO) << "G3 OnBluetoothDeviceStateChanged [device impl="
+ << &device << "]: new device; notify="
+ << enable_notifications_.load();
+ if (mode == api::BluetoothAdapter::ScanMode::kConnectableDiscoverable &&
+ enabled) {
+ // New device is turned on, and is in discoverable state.
+ // Store device name, and report it as discovered.
+ info.devices.emplace(&device, name);
+ if (enable_notifications_) {
+ RunOnMediumEnvironmentThread(
+ [&info, &device]() { info.callback.device_discovered_cb(device); });
+ }
+ }
+ } else {
+ NEARBY_LOGS(INFO) << "G3 OnBluetoothDeviceStateChanged [device impl="
+ << &device << "]: existing device; notify="
+ << enable_notifications_.load();
+ auto& discovered_name = item->second;
+ if (mode == api::BluetoothAdapter::ScanMode::kConnectableDiscoverable &&
+ enabled) {
+ if (name != discovered_name) {
+ // Known device is turned on, and is in discoverable state.
+ // Store device name, and report it as renamed.
+ item->second = name;
+ if (enable_notifications_) {
+ RunOnMediumEnvironmentThread([&info, &device]() {
+ info.callback.device_name_changed_cb(device);
+ });
+ }
+ } else {
+ // Device is in discovery mode, so we are reporting it anyway.
+ if (enable_notifications_) {
+ RunOnMediumEnvironmentThread([&info, &device]() {
+ info.callback.device_discovered_cb(device);
+ });
+ }
+ }
+ }
+ if (!enabled) {
+ // Known device is turned off.
+ // Erase it from the map, and report as lost.
+ if (enable_notifications_) {
+ RunOnMediumEnvironmentThread(
+ [&info, &device]() { info.callback.device_lost_cb(device); });
+ }
+ info.devices.erase(item);
+ }
+ }
+}
+
+api::BluetoothDevice* MediumEnvironment::FindBluetoothDevice(
+ const std::string& mac_address) {
+ api::BluetoothDevice* device = nullptr;
+ CountDownLatch latch(1);
+ RunOnMediumEnvironmentThread([this, &device, &latch, &mac_address]() {
+ for (auto& item : bluetooth_mediums_) {
+ auto* adapter = item.second.adapter;
+ if (!adapter) continue;
+ if (adapter->GetMacAddress() == mac_address) {
+ device = bluetooth_adapters_[adapter];
+ break;
+ }
+ }
+ latch.CountDown();
+ });
+ latch.Await();
+ return device;
+}
+
+void MediumEnvironment::OnBlePeripheralStateChanged(
+ BleMediumContext& info, api::BlePeripheral& peripheral,
+ const std::string& service_id, bool fast_advertisement, bool enabled) {
+ if (!enabled_) return;
+ NEARBY_LOGS(INFO) << "G3 OnBleServiceStateChanged [peripheral impl="
+ << &peripheral << "]; context=" << &info
+ << "; service_id=" << service_id
+ << "; notify=" << enable_notifications_.load();
+ if (!enable_notifications_) return;
+ RunOnMediumEnvironmentThread([&info, enabled, &peripheral, service_id,
+ fast_advertisement]() {
+ NEARBY_LOGS(INFO) << "G3 [Run] OnBleServiceStateChanged [peripheral impl="
+ << &peripheral << "]; context=" << &info
+ << "; service_id=" << service_id
+ << "; notify=" << enabled;
+ if (enabled) {
+ info.discovery_callback.peripheral_discovered_cb(peripheral, service_id,
+ fast_advertisement);
+ } else {
+ info.discovery_callback.peripheral_lost_cb(peripheral, service_id);
+ }
+ });
+}
+
+void MediumEnvironment::OnWifiLanServiceStateChanged(
+ WifiLanMediumContext& info, const NsdServiceInfo& service_info,
+ bool enabled) {
+ if (!enabled_) return;
+ std::string service_type = service_info.GetServiceType();
+ auto item = info.discovered_services.find(service_type);
+ if (item == info.discovered_services.end()) {
+ NEARBY_LOGS(INFO) << "G3 OnWifiLanServiceStateChanged; context=" << &info
+ << "; service_type=" << service_type
+ << "; enabled=" << enabled
+ << "; notify=" << enable_notifications_.load();
+ if (enabled) {
+ // Find advertising service with matched service_type. Report it as
+ // discovered.
+ NsdServiceInfo discovered_service_info(service_info);
+ info.discovered_services.insert({service_type, discovered_service_info});
+ if (enable_notifications_) {
+ RunOnMediumEnvironmentThread(
+ [&info, discovered_service_info, service_type]() {
+ auto item = info.discovered_callbacks.find(service_type);
+ if (item != info.discovered_callbacks.end()) {
+ item->second.service_discovered_cb(discovered_service_info);
+ }
+ });
+ }
+ }
+ } else {
+ NEARBY_LOGS(INFO)
+ << "G3 OnWifiLanServiceStateChanged: exisitng service; context="
+ << &info << "; service_type=" << service_type << "; enabled=" << enabled
+ << "; notify=" << enable_notifications_.load();
+ if (enabled) {
+ if (enable_notifications_) {
+ RunOnMediumEnvironmentThread(
+ [&info, service_info = service_info, service_type]() {
+ auto item = info.discovered_callbacks.find(service_type);
+ if (item != info.discovered_callbacks.end()) {
+ item->second.service_discovered_cb(service_info);
+ }
+ });
+ }
+ } else {
+ // Known service is off.
+ // Erase it from the map, and report as lost.
+ if (enable_notifications_) {
+ RunOnMediumEnvironmentThread(
+ [&info, service_info = service_info, service_type]() {
+ auto item = info.discovered_callbacks.find(service_type);
+ if (item != info.discovered_callbacks.end()) {
+ item->second.service_lost_cb(service_info);
+ }
+ });
+ }
+ info.discovered_services.erase(item);
+ }
+ }
+}
+
+void MediumEnvironment::RunOnMediumEnvironmentThread(
+ std::function<void()> runnable) {
+ job_count_++;
+ executor_.Execute(std::move(runnable));
+}
+
+void MediumEnvironment::RegisterBluetoothMedium(
+ api::BluetoothClassicMedium& medium,
+ api::BluetoothAdapter& medium_adapter) {
+ if (!enabled_) return;
+ RunOnMediumEnvironmentThread([this, &medium, &medium_adapter]() {
+ auto& context = bluetooth_mediums_
+ .insert({&medium,
+ BluetoothMediumContext{
+ .adapter = &medium_adapter,
+ }})
+ .first->second;
+ auto* owned_adapter = context.adapter;
+ NEARBY_LOGS(INFO) << "Registered: medium=" << &medium
+ << "; adapter=" << owned_adapter;
+ for (auto& adapter_device : bluetooth_adapters_) {
+ auto& adapter = adapter_device.first;
+ auto& device = adapter_device.second;
+ if (adapter == nullptr) continue;
+ OnBluetoothDeviceStateChanged(context, *device, adapter->GetName(),
+ adapter->GetScanMode(),
+ adapter->IsEnabled());
+ }
+ });
+}
+
+void MediumEnvironment::UpdateBluetoothMedium(
+ api::BluetoothClassicMedium& medium, BluetoothDiscoveryCallback callback) {
+ if (!enabled_) return;
+ RunOnMediumEnvironmentThread(
+ [this, &medium, callback = std::move(callback)]() {
+ auto item = bluetooth_mediums_.find(&medium);
+ if (item == bluetooth_mediums_.end()) return;
+ auto& context = item->second;
+ context.callback = std::move(callback);
+ auto* owned_adapter = context.adapter;
+ NEARBY_LOGS(INFO) << "Updated: this=" << this << "; medium=" << &medium
+ << "; adapter=" << owned_adapter
+ << "; name=" << owned_adapter->GetName()
+ << "; enabled=" << owned_adapter->IsEnabled()
+ << "; mode=" << int32_t(owned_adapter->GetScanMode());
+ for (auto& adapter_device : bluetooth_adapters_) {
+ auto& adapter = adapter_device.first;
+ auto& device = adapter_device.second;
+ if (adapter == nullptr) continue;
+ OnBluetoothDeviceStateChanged(context, *device, adapter->GetName(),
+ adapter->GetScanMode(),
+ adapter->IsEnabled());
+ }
+ });
+}
+
+void MediumEnvironment::UnregisterBluetoothMedium(
+ api::BluetoothClassicMedium& medium) {
+ if (!enabled_) return;
+ RunOnMediumEnvironmentThread([this, &medium]() {
+ auto item = bluetooth_mediums_.extract(&medium);
+ if (item.empty()) return;
+ NEARBY_LOGS(INFO) << "Unregistered Bluetooth medium:" << &medium;
+ });
+}
+
+void MediumEnvironment::RegisterBleMedium(api::BleMedium& medium) {
+ if (!enabled_) return;
+ RunOnMediumEnvironmentThread([this, &medium]() {
+ ble_mediums_.insert({&medium, BleMediumContext{}});
+ NEARBY_LOGS(INFO) << "Registered: medium:" << &medium;
+ });
+}
+
+void MediumEnvironment::UpdateBleMediumForAdvertising(
+ api::BleMedium& medium, api::BlePeripheral& peripheral,
+ const std::string& service_id, bool fast_advertisement, bool enabled) {
+ if (!enabled_) return;
+ RunOnMediumEnvironmentThread([this, &medium, &peripheral, service_id,
+ fast_advertisement, enabled]() {
+ auto item = ble_mediums_.find(&medium);
+ if (item == ble_mediums_.end()) {
+ NEARBY_LOGS(INFO) << "UpdateBleMediumForAdvertising failed. There is no "
+ "medium registered.";
+ return;
+ }
+ auto& context = item->second;
+ context.ble_peripheral = &peripheral;
+ context.advertising = enabled;
+ context.fast_advertisement = fast_advertisement;
+ NEARBY_LOGS(INFO) << "Update Ble medium for advertising: this=" << this
+ << "; medium=" << &medium << "; service_id=" << service_id
+ << "; name=" << peripheral.GetName()
+ << "; fast_advertisement=" << fast_advertisement
+ << "; enabled=" << enabled;
+ for (auto& medium_info : ble_mediums_) {
+ auto& local_medium = medium_info.first;
+ auto& info = medium_info.second;
+ // Do not send notification to the same medium.
+ if (local_medium == &medium) continue;
+ OnBlePeripheralStateChanged(info, peripheral, service_id,
+ fast_advertisement, enabled);
+ }
+ });
+}
+
+void MediumEnvironment::UpdateBleMediumForScanning(
+ api::BleMedium& medium, const std::string& service_id,
+ const std::string& fast_advertisement_service_uuid,
+ BleDiscoveredPeripheralCallback callback, bool enabled) {
+ if (!enabled_) return;
+ RunOnMediumEnvironmentThread(
+ [this, &medium, service_id, fast_advertisement_service_uuid,
+ callback = std::move(callback), enabled]() {
+ auto item = ble_mediums_.find(&medium);
+ if (item == ble_mediums_.end()) {
+ NEARBY_LOGS(INFO)
+ << "UpdateBleMediumFoScanning failed. There is no medium "
+ "registered.";
+ return;
+ }
+ auto& context = item->second;
+ context.discovery_callback = std::move(callback);
+ NEARBY_LOGS(INFO) << "Update Ble medium for scanning: this=" << this
+ << "; medium=" << &medium
+ << "; service_id=" << service_id
+ << "; fast_advertisement_service_uuid="
+ << fast_advertisement_service_uuid
+ << "; enabled=" << enabled;
+ for (auto& medium_info : ble_mediums_) {
+ auto& local_medium = medium_info.first;
+ auto& info = medium_info.second;
+ // Do not send notification to the same medium.
+ if (local_medium == &medium) continue;
+ // Search advertising mediums and send notification.
+ if (info.advertising && enabled) {
+ OnBlePeripheralStateChanged(context, *(info.ble_peripheral),
+ service_id, info.fast_advertisement,
+ enabled);
+ }
+ }
+ });
+}
+
+void MediumEnvironment::UpdateBleMediumForAcceptedConnection(
+ api::BleMedium& medium, const std::string& service_id,
+ BleAcceptedConnectionCallback callback) {
+ if (!enabled_) return;
+ RunOnMediumEnvironmentThread(
+ [this, &medium, service_id, callback = std::move(callback)]() {
+ auto item = ble_mediums_.find(&medium);
+ if (item == ble_mediums_.end()) {
+ NEARBY_LOGS(INFO)
+ << "Update Ble medium failed. There is no medium registered.";
+ return;
+ }
+ auto& context = item->second;
+ context.accepted_connection_callback = std::move(callback);
+ NEARBY_LOGS(INFO) << "Update Ble medium for accepted callback: this="
+ << this << "; medium=" << &medium
+ << "; service_id=" << service_id;
+ });
+}
+
+void MediumEnvironment::UnregisterBleMedium(api::BleMedium& medium) {
+ if (!enabled_) return;
+ RunOnMediumEnvironmentThread([this, &medium]() {
+ auto item = ble_mediums_.extract(&medium);
+ if (item.empty()) return;
+ NEARBY_LOGS(INFO) << "Unregistered Ble medium";
+ });
+}
+
+void MediumEnvironment::CallBleAcceptedConnectionCallback(
+ api::BleMedium& medium, api::BleSocket& socket,
+ const std::string& service_id) {
+ if (!enabled_) return;
+ RunOnMediumEnvironmentThread(
+ [this, &medium, &socket, service_id]() {
+ auto item = ble_mediums_.find(&medium);
+ if (item == ble_mediums_.end()) {
+ NEARBY_LOGS(INFO)
+ << "Call AcceptedConnectionCallback failed. There is no medium "
+ "registered.";
+ return;
+ }
+ auto& info = item->second;
+ info.accepted_connection_callback.accepted_cb(socket, service_id);
+ });
+}
+#ifndef NO_WEBRTC
+void MediumEnvironment::RegisterWebRtcSignalingMessenger(
+ absl::string_view self_id, OnSignalingMessageCallback message_callback,
+ OnSignalingCompleteCallback complete_callback) {
+ if (!enabled_) return;
+ RunOnMediumEnvironmentThread([this, self_id{std::string(self_id)},
+ message_callback{std::move(message_callback)},
+ complete_callback{
+ std::move(complete_callback)}]() {
+ webrtc_signaling_message_callback_[self_id] = std::move(message_callback);
+ webrtc_signaling_complete_callback_[self_id] = std::move(complete_callback);
+ NEARBY_LOGS(INFO) << "Registered signaling message callback for id = "
+ << self_id;
+ });
+}
+
+void MediumEnvironment::UnregisterWebRtcSignalingMessenger(
+ absl::string_view self_id) {
+ if (!enabled_) return;
+ RunOnMediumEnvironmentThread([this, self_id{std::string(self_id)}]() {
+ auto message_callback_item =
+ webrtc_signaling_message_callback_.extract(self_id);
+ auto complete_callback_item =
+ webrtc_signaling_complete_callback_.extract(self_id);
+ NEARBY_LOGS(INFO) << "Unregistered signaling message callback for id = "
+ << self_id;
+ });
+}
+
+void MediumEnvironment::SendWebRtcSignalingMessage(absl::string_view peer_id,
+ const ByteArray& message) {
+ if (!enabled_) return;
+ RunOnMediumEnvironmentThread(
+ [this, peer_id{std::string(peer_id)}, message]() {
+ auto item = webrtc_signaling_message_callback_.find(peer_id);
+ if (item == webrtc_signaling_message_callback_.end()) {
+ NEARBY_LOGS(WARNING)
+ << "No callback registered for peer id = " << peer_id;
+ return;
+ }
+
+ item->second(message);
+ });
+}
+
+void MediumEnvironment::SendWebRtcSignalingComplete(absl::string_view peer_id,
+ bool success) {
+ if (!enabled_) return;
+ RunOnMediumEnvironmentThread(
+ [this, peer_id{std::string(peer_id)}, success]() {
+ auto item = webrtc_signaling_complete_callback_.find(peer_id);
+ if (item == webrtc_signaling_complete_callback_.end()) {
+ NEARBY_LOGS(WARNING)
+ << "No callback registered for peer id = " << peer_id;
+ return;
+ }
+
+ item->second(success);
+ });
+}
+#endif
+void MediumEnvironment::SetUseValidPeerConnection(
+ bool use_valid_peer_connection) {
+ use_valid_peer_connection_ = use_valid_peer_connection;
+}
+
+bool MediumEnvironment::GetUseValidPeerConnection() {
+ return use_valid_peer_connection_;
+}
+
+void MediumEnvironment::SetPeerConnectionLatency(
+ absl::Duration peer_connection_latency) {
+ peer_connection_latency_ = peer_connection_latency;
+}
+
+absl::Duration MediumEnvironment::GetPeerConnectionLatency() {
+ return peer_connection_latency_;
+}
+
+std::string MediumEnvironment::GetFakeIPAddress() const {
+ std::string ip_address;
+ ip_address.resize(4);
+ uint32_t raw_ip_addr = Prng().NextUint32();
+ ip_address[0] = static_cast<char>(raw_ip_addr >> 24);
+ ip_address[1] = static_cast<char>(raw_ip_addr >> 16);
+ ip_address[2] = static_cast<char>(raw_ip_addr >> 8);
+ ip_address[3] = static_cast<char>(raw_ip_addr >> 0);
+
+ return ip_address;
+}
+
+int MediumEnvironment::GetFakePort() const {
+ uint16_t port = Prng().NextUint32();
+
+ return port;
+}
+
+void MediumEnvironment::RegisterWifiLanMedium(api::WifiLanMedium& medium) {
+ if (!enabled_) return;
+ RunOnMediumEnvironmentThread([this, &medium]() {
+ wifi_lan_mediums_.insert({&medium, WifiLanMediumContext{}});
+ NEARBY_LOG(INFO, "Registered: medium=%p", &medium);
+ });
+}
+
+void MediumEnvironment::UpdateWifiLanMediumForAdvertising(
+ api::WifiLanMedium& medium, const NsdServiceInfo& service_info,
+ bool enabled) {
+ if (!enabled_) return;
+ RunOnMediumEnvironmentThread([this, &medium, service_info = service_info,
+ enabled]() {
+ std::string service_type = service_info.GetServiceType();
+ NEARBY_LOGS(INFO) << "Update WifiLan medium for advertising: this=" << this
+ << "; medium=" << &medium
+ << "; service_name=" << service_info.GetServiceName()
+ << "; service_type=" << service_type
+ << ", enabled=" << enabled;
+ for (auto& medium_info : wifi_lan_mediums_) {
+ auto& local_medium = medium_info.first;
+ auto& info = medium_info.second;
+ // Do not send notification to the same medium but update
+ // service info map.
+ if (local_medium == &medium) {
+ if (enabled) {
+ info.advertising_services.insert({service_type, service_info});
+ } else {
+ info.advertising_services.erase(service_type);
+ }
+ continue;
+ }
+ OnWifiLanServiceStateChanged(info, service_info, enabled);
+ }
+ });
+}
+
+void MediumEnvironment::UpdateWifiLanMediumForDiscovery(
+ api::WifiLanMedium& medium, WifiLanDiscoveredServiceCallback callback,
+ const std::string& service_type, bool enabled) {
+ if (!enabled_) return;
+ RunOnMediumEnvironmentThread([this, &medium, callback = std::move(callback),
+ service_type, enabled]() {
+ auto item = wifi_lan_mediums_.find(&medium);
+ if (item == wifi_lan_mediums_.end()) {
+ NEARBY_LOGS(INFO)
+ << "UpdateWifiLanMediumForDiscovery failed. There is no medium "
+ "registered.";
+ return;
+ }
+ auto& context = item->second;
+ context.discovered_callbacks.insert({service_type, std::move(callback)});
+ NEARBY_LOGS(INFO) << "Update WifiLan medium for discovery: this=" << this
+ << "; medium=" << &medium
+ << "; service_type=" << service_type
+ << "; enabled=" << enabled;
+ for (auto& medium_info : wifi_lan_mediums_) {
+ auto& local_medium = medium_info.first;
+ auto& info = medium_info.second;
+ // Do not send notification to the same medium.
+ if (local_medium == &medium) continue;
+ // Search advertising services and send notification.
+ for (auto& advertising_service : info.advertising_services) {
+ auto& service_info = advertising_service.second;
+ OnWifiLanServiceStateChanged(context, service_info, /*enabled=*/true);
+ }
+ }
+ });
+}
+
+void MediumEnvironment::UnregisterWifiLanMedium(api::WifiLanMedium& medium) {
+ if (!enabled_) return;
+ RunOnMediumEnvironmentThread([this, &medium]() {
+ auto item = wifi_lan_mediums_.extract(&medium);
+ if (item.empty()) return;
+ NEARBY_LOGS(INFO) << "Unregistered WifiLan medium";
+ });
+}
+
+api::WifiLanMedium* MediumEnvironment::GetWifiLanMedium(
+ const std::string& ip_address, int port) {
+ for (auto& medium_info : wifi_lan_mediums_) {
+ auto* medium_found = medium_info.first;
+ auto& info = medium_info.second;
+ for (auto& advertising_service : info.advertising_services) {
+ auto& service_info = advertising_service.second;
+ if (ip_address == service_info.GetIPAddress() &&
+ port == service_info.GetPort()) {
+ return medium_found;
+ }
+ }
+ }
+ return nullptr;
+}
+
+void MediumEnvironment::SetFeatureFlags(const FeatureFlags::Flags& flags) {
+ const_cast<FeatureFlags&>(FeatureFlags::GetInstance()).SetFlags(flags);
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/medium_environment.h b/chromium/third_party/nearby/src/internal/platform/medium_environment.h
new file mode 100644
index 00000000000..609e9595b10
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/medium_environment.h
@@ -0,0 +1,325 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_BASE_MEDIUM_ENVIRONMENT_H_
+#define PLATFORM_BASE_MEDIUM_ENVIRONMENT_H_
+
+#include <atomic>
+#include <memory>
+
+#include "absl/container/flat_hash_map.h"
+#include "absl/strings/string_view.h"
+#include "internal/platform/implementation/ble.h"
+#include "internal/platform/implementation/bluetooth_adapter.h"
+#include "internal/platform/implementation/bluetooth_classic.h"
+#ifndef NO_WEBRTC
+#include "internal/platform/implementation/webrtc.h"
+#endif
+#include "internal/platform/implementation/wifi_lan.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/feature_flags.h"
+#include "internal/platform/listeners.h"
+#include "internal/platform/nsd_service_info.h"
+#include "internal/platform/single_thread_executor.h"
+
+namespace location {
+namespace nearby {
+
+// Environment config that can control availability of certain mediums for
+// testing.
+struct EnvironmentConfig {
+ // Control whether WEB_RTC medium is enabled in the environment.
+ // This is currently set to false, due to http://b/139734036 that would lead
+ // to flaky tests.
+ bool webrtc_enabled = false;
+};
+
+// MediumEnvironment is a simulated environment which allows multiple instances
+// of simulated HW devices to "work" together as if they are physical.
+// For each medium type it provides necessary methods to implement
+// advertising, discovery and establishment of a data link.
+// NOTE: this code depends on public:types target.
+class MediumEnvironment {
+ public:
+ using BluetoothDiscoveryCallback =
+ api::BluetoothClassicMedium::DiscoveryCallback;
+ using BleDiscoveredPeripheralCallback =
+ api::BleMedium::DiscoveredPeripheralCallback;
+ using BleAcceptedConnectionCallback =
+ api::BleMedium::AcceptedConnectionCallback;
+#ifndef NO_WEBRTC
+ using OnSignalingMessageCallback =
+ api::WebRtcSignalingMessenger::OnSignalingMessageCallback;
+ using OnSignalingCompleteCallback =
+ api::WebRtcSignalingMessenger::OnSignalingCompleteCallback;
+#endif
+ using WifiLanDiscoveredServiceCallback =
+ api::WifiLanMedium::DiscoveredServiceCallback;
+
+ MediumEnvironment(const MediumEnvironment&) = delete;
+ MediumEnvironment& operator=(const MediumEnvironment&) = delete;
+
+ // Creates and returns a reference to the global test environment instance.
+ static MediumEnvironment& Instance();
+
+ // Global ON/OFF switch for medium environment.
+ // Start & Stop work as On/Off switch for this object.
+ // Default state (after creation) is ON, to make it compatible with early
+ // tests that are already using it and relying on it being ON.
+
+ // Enables Medium environment.
+ void Start(EnvironmentConfig config = EnvironmentConfig());
+ // Disables Medium environment.
+ void Stop();
+
+ // Clears state. No notifications are sent.
+ void Reset();
+
+ // Waits for all previously scheduled jobs to finish.
+ // This method works as a barrier that guarantees that after it returns, all
+ // the activities that started before it was called, or while it was running
+ // are ended. This means that system is at the state of relaxation when this
+ // code returns. It requires external stimulus to get out of relaxation state.
+ //
+ // If enable_notifications is true (default), simulation environment
+ // will send all future notification events to all registered objects,
+ // whenever protocol requires that. This is expected behavior.
+ // If enabled_notifications is false, future event notifications will not be
+ // sent to registered instances. This is useful for protocol shutdown,
+ // where we no longer care about notifications, and where notifications may
+ // otherwise be delivered after the notification source or target lifeteme has
+ // ended, and cause undefined behavior.
+ void Sync(bool enable_notifications = true);
+
+ // Adds an adapter to internal container.
+ // Notify BluetoothClassicMediums if any that adapter state has changed.
+ void OnBluetoothAdapterChangedState(api::BluetoothAdapter& adapter,
+ api::BluetoothDevice& adapter_device,
+ std::string name, bool enabled,
+ api::BluetoothAdapter::ScanMode mode);
+
+ // Adds medium-related info to allow for adapter discovery to work.
+ // This provides acccess to this medium from other mediums, when protocol
+ // expects they should communicate.
+ void RegisterBluetoothMedium(api::BluetoothClassicMedium& medium,
+ api::BluetoothAdapter& medium_adapter);
+
+ // Updates callback info to allow for dispatch of discovery events.
+ //
+ // Invokes callback asynchronously when any changes happen to discoverable
+ // devices, or if the defice is turned off, whether or not it is discoverable,
+ // if it was ever reported as discoverable.
+ //
+ // This should be called when discoverable state changes.
+ // with user-specified callback when discovery is enabled, and with default
+ // (empty) callback otherwise.
+ void UpdateBluetoothMedium(api::BluetoothClassicMedium& medium,
+ BluetoothDiscoveryCallback callback);
+
+ // Removes medium-related info. This should correspond to device power off.
+ void UnregisterBluetoothMedium(api::BluetoothClassicMedium& medium);
+
+ // Returns a Bluetooth Device object matching given mac address to nullptr.
+ api::BluetoothDevice* FindBluetoothDevice(const std::string& mac_address);
+
+ const EnvironmentConfig& GetEnvironmentConfig();
+#ifndef NO_WEBRTC
+ // Registers |message_callback| to receive messages sent to device with id
+ // |self_id|, and |complete_callback| to notify when signaling is complete.
+ void RegisterWebRtcSignalingMessenger(
+ absl::string_view self_id, OnSignalingMessageCallback message_callback,
+ OnSignalingCompleteCallback complete_callback);
+
+ // Unregisters the callback listening to incoming messages for |self_id|.
+ void UnregisterWebRtcSignalingMessenger(absl::string_view self_id);
+
+ // Simulates sending a signaling message |message| to device with id
+ // |peer_id|.
+ void SendWebRtcSignalingMessage(absl::string_view peer_id,
+ const ByteArray& message);
+
+ // Simulates sending an "signaling complete" signal to the WebRTC medium.
+ void SendWebRtcSignalingComplete(absl::string_view peer_id, bool success);
+#endif
+ // Used to set if WebRtcMedium should use a valid peer connection or nullptr
+ // in tests.
+ void SetUseValidPeerConnection(bool use_valid_peer_connection);
+
+ bool GetUseValidPeerConnection();
+
+ // Used to set latency when creating the peer connection in tests.
+ void SetPeerConnectionLatency(absl::Duration peer_connection_latency);
+
+ absl::Duration GetPeerConnectionLatency();
+
+ // Adds medium-related info to allow for scanning/advertising to work.
+ // This provides acccess to this medium from other mediums, when protocol
+ // expects they should communicate.
+ void RegisterBleMedium(api::BleMedium& medium);
+
+ // Updates advertising info to indicate the current medium is exposing
+ // advertising event.
+ void UpdateBleMediumForAdvertising(api::BleMedium& medium,
+ api::BlePeripheral& peripheral,
+ const std::string& service_id,
+ bool fast_advertisement, bool enabled);
+
+ // Updates discovery callback info to allow for dispatch of discovery events.
+ //
+ // Invokes callback asynchronously when any changes happen to discoverable
+ // devices, or if the defice is turned off, whether or not it is discoverable,
+ // if it was ever reported as discoverable.
+ //
+ // This should be called when discoverable state changes.
+ // with user-specified callback when discovery is enabled, and with default
+ // (empty) callback otherwise.
+ void UpdateBleMediumForScanning(
+ api::BleMedium& medium, const std::string& service_id,
+ const std::string& fast_advertisement_service_uuid,
+ BleDiscoveredPeripheralCallback callback, bool enabled);
+
+ // Updates Accepted connection callback info to allow for dispatch of
+ // advertising events.
+ void UpdateBleMediumForAcceptedConnection(
+ api::BleMedium& medium, const std::string& service_id,
+ BleAcceptedConnectionCallback callback);
+
+ // Removes medium-related info. This should correspond to device power off.
+ void UnregisterBleMedium(api::BleMedium& medium);
+
+ // Call back when advertising has created the server socket and is ready for
+ // connect.
+ void CallBleAcceptedConnectionCallback(api::BleMedium& medium,
+ api::BleSocket& socket,
+ const std::string& service_id);
+
+ // Adds medium-related info to allow for discovery/advertising to work.
+ // This provides acccess to this medium from other mediums, when protocol
+ // expects they should communicate.
+ void RegisterWifiLanMedium(api::WifiLanMedium& medium);
+
+ // Updates advertising info to indicate the current medium is exposing
+ // advertising event.
+ void UpdateWifiLanMediumForAdvertising(api::WifiLanMedium& medium,
+ const NsdServiceInfo& nsd_service_info,
+ bool enabled);
+
+ // Updates discovery callback info to allow for dispatch of discovery events.
+ //
+ // This should be called when discoverable state changes.
+ // with user-specified callback when discovery is enabled, and with default
+ // (empty) callback otherwise.
+ void UpdateWifiLanMediumForDiscovery(
+ api::WifiLanMedium& medium, WifiLanDiscoveredServiceCallback callback,
+ const std::string& service_type, bool enabled);
+
+ // Gets Fake IP address for WifiLan medium.
+ std::string GetFakeIPAddress() const;
+
+ // Gets Fake port number for WifiLan medium.
+ int GetFakePort() const;
+
+ // Removes medium-related info. This should correspond to device power off.
+ void UnregisterWifiLanMedium(api::WifiLanMedium& medium);
+
+ // Returns WifiLan medium whose advertising service matching IP address and
+ // port, or nullptr.
+ api::WifiLanMedium* GetWifiLanMedium(const std::string& ip_address, int port);
+
+ void SetFeatureFlags(const FeatureFlags::Flags& flags);
+
+ private:
+ struct BluetoothMediumContext {
+ BluetoothDiscoveryCallback callback;
+ api::BluetoothAdapter* adapter = nullptr;
+ // discovered device vs device name map.
+ absl::flat_hash_map<api::BluetoothDevice*, std::string> devices;
+ };
+
+ struct BleMediumContext {
+ BleDiscoveredPeripheralCallback discovery_callback;
+ BleAcceptedConnectionCallback accepted_connection_callback;
+ api::BlePeripheral* ble_peripheral = nullptr;
+ bool advertising = false;
+ bool fast_advertisement = false;
+ };
+
+ struct WifiLanMediumContext {
+ // advertising service type vs NsdServiceInfo map.
+ absl::flat_hash_map<std::string, NsdServiceInfo> advertising_services;
+ // discovered service type vs callback map.
+ absl::flat_hash_map<std::string, WifiLanDiscoveredServiceCallback>
+ discovered_callbacks;
+ // discovered service vs service type map.
+ absl::flat_hash_map<std::string, NsdServiceInfo> discovered_services;
+ };
+
+ // This is a singleton object, for which destructor will never be called.
+ // Constructor will be invoked once from Instance() static method.
+ // Object is create in-place (with a placement new) to guarantee that
+ // destructor is not scheduled for execution at exit.
+ MediumEnvironment() = default;
+ ~MediumEnvironment() = default;
+
+ void OnBluetoothDeviceStateChanged(BluetoothMediumContext& info,
+ api::BluetoothDevice& device,
+ const std::string& name,
+ api::BluetoothAdapter::ScanMode mode,
+ bool enabled);
+
+ void OnBlePeripheralStateChanged(BleMediumContext& info,
+ api::BlePeripheral& peripheral,
+ const std::string& service_id,
+ bool fast_advertisement, bool enabled);
+
+ void OnWifiLanServiceStateChanged(WifiLanMediumContext& info,
+ const NsdServiceInfo& service_info,
+ bool enabled);
+
+ void RunOnMediumEnvironmentThread(std::function<void()> runnable);
+
+ std::atomic_bool enabled_ = true;
+ std::atomic_int job_count_ = 0;
+ std::atomic_bool enable_notifications_ = false;
+ SingleThreadExecutor executor_;
+ EnvironmentConfig config_;
+
+ // The following data members are accessed in the context of a private
+ // executor_ thread.
+ absl::flat_hash_map<api::BluetoothAdapter*, api::BluetoothDevice*>
+ bluetooth_adapters_;
+ absl::flat_hash_map<api::BluetoothClassicMedium*, BluetoothMediumContext>
+ bluetooth_mediums_;
+
+ absl::flat_hash_map<api::BleMedium*, BleMediumContext> ble_mediums_;
+#ifndef NO_WEBRTC
+ // Maps peer id to callback for receiving signaling messages.
+ absl::flat_hash_map<std::string, OnSignalingMessageCallback>
+ webrtc_signaling_message_callback_;
+
+ // Maps peer id to callback for signaling complete events.
+ absl::flat_hash_map<std::string, OnSignalingCompleteCallback>
+ webrtc_signaling_complete_callback_;
+#endif
+ absl::flat_hash_map<api::WifiLanMedium*, WifiLanMediumContext>
+ wifi_lan_mediums_;
+
+ bool use_valid_peer_connection_ = true;
+ absl::Duration peer_connection_latency_ = absl::ZeroDuration();
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_BASE_MEDIUM_ENVIRONMENT_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/monitored_runnable.cc b/chromium/third_party/nearby/src/internal/platform/monitored_runnable.cc
new file mode 100644
index 00000000000..b8a38dfa617
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/monitored_runnable.cc
@@ -0,0 +1,59 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/monitored_runnable.h"
+
+#include "internal/platform/logging.h"
+#include "internal/platform/pending_job_registry.h"
+
+namespace location {
+namespace nearby {
+
+namespace {
+absl::Duration kMinReportedStartDelay = absl::Seconds(5);
+absl::Duration kMinReportedTaskDuration = absl::Seconds(10);
+} // namespace
+
+MonitoredRunnable::MonitoredRunnable(Runnable&& runnable)
+ : runnable_{runnable} {}
+
+MonitoredRunnable::MonitoredRunnable(const std::string& name,
+ Runnable&& runnable)
+ : name_{name}, runnable_{runnable} {
+ PendingJobRegistry::GetInstance().AddPendingJob(name_, post_time_);
+}
+
+MonitoredRunnable::~MonitoredRunnable() = default;
+
+void MonitoredRunnable::operator()() const {
+ auto start_time = SystemClock::ElapsedRealtime();
+ auto start_delay = start_time - post_time_;
+ if (start_delay >= kMinReportedStartDelay) {
+ NEARBY_LOGS(INFO) << "Task: \"" << name_ << "\" started after "
+ << absl::ToInt64Seconds(start_delay) << " seconds";
+ }
+ PendingJobRegistry::GetInstance().RemovePendingJob(name_, post_time_);
+ PendingJobRegistry::GetInstance().AddRunningJob(name_, post_time_);
+ runnable_();
+ auto task_duration = SystemClock::ElapsedRealtime() - start_time;
+ if (task_duration >= kMinReportedTaskDuration) {
+ NEARBY_LOGS(INFO) << "Task: \"" << name_ << "\" finished after "
+ << absl::ToInt64Seconds(task_duration) << " seconds";
+ }
+ PendingJobRegistry::GetInstance().RemoveRunningJob(name_, post_time_);
+ PendingJobRegistry::GetInstance().ListJobs();
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/monitored_runnable.h b/chromium/third_party/nearby/src/internal/platform/monitored_runnable.h
new file mode 100644
index 00000000000..61ff2ad0c3e
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/monitored_runnable.h
@@ -0,0 +1,48 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_MONITORED_RUNNABLE_H_
+#define PLATFORM_PUBLIC_MONITORED_RUNNABLE_H_
+
+#include <string>
+
+#include "absl/time/time.h"
+#include "internal/platform/runnable.h"
+#include "internal/platform/system_clock.h"
+
+namespace location {
+namespace nearby {
+
+// A runnable with extra logging
+// We log if the task has been waiting long on the executor or if it was running
+// for a long time. The latter isn't always an issue - some tasks are expected
+// to run for longer periods of time (minutes).
+class MonitoredRunnable {
+ public:
+ explicit MonitoredRunnable(Runnable&& runnable);
+ MonitoredRunnable(const std::string& name, Runnable&& runnable);
+ ~MonitoredRunnable();
+
+ void operator()() const;
+
+ private:
+ const std::string name_;
+ Runnable runnable_;
+ absl::Time post_time_ = SystemClock::ElapsedRealtime();
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_MONITORED_RUNNABLE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/multi_thread_executor.h b/chromium/third_party/nearby/src/internal/platform/multi_thread_executor.h
new file mode 100644
index 00000000000..4e6644bceab
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/multi_thread_executor.h
@@ -0,0 +1,43 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_MULTI_THREAD_EXECUTOR_H_
+#define PLATFORM_PUBLIC_MULTI_THREAD_EXECUTOR_H_
+
+#include "absl/base/thread_annotations.h"
+#include "internal/platform/implementation/platform.h"
+#include "internal/platform/submittable_executor.h"
+
+namespace location {
+namespace nearby {
+
+// An Executor that reuses a fixed number of threads operating off a shared
+// unbounded queue.
+//
+// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool-int-
+class ABSL_LOCKABLE MultiThreadExecutor final : public SubmittableExecutor {
+ public:
+ using Platform = api::ImplementationPlatform;
+ explicit MultiThreadExecutor(int max_parallelism)
+ : SubmittableExecutor(
+ Platform::CreateMultiThreadExecutor(max_parallelism)) {}
+ MultiThreadExecutor(MultiThreadExecutor&&) = default;
+ MultiThreadExecutor& operator=(MultiThreadExecutor&&) = default;
+ ~MultiThreadExecutor() override = default;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_MULTI_THREAD_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/multi_thread_executor_test.cc b/chromium/third_party/nearby/src/internal/platform/multi_thread_executor_test.cc
new file mode 100644
index 00000000000..44231e4180d
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/multi_thread_executor_test.cc
@@ -0,0 +1,138 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/multi_thread_executor.h"
+
+#include <atomic>
+#include <functional>
+
+#include "gtest/gtest.h"
+#include "absl/synchronization/mutex.h"
+#include "absl/time/clock.h"
+#include "absl/time/time.h"
+#include "internal/platform/exception.h"
+
+namespace location {
+namespace nearby {
+
+namespace {
+const int kMaxThreads = 5;
+}
+
+TEST(MultiThreadExecutorTest, ConsructorDestructorWorks) {
+ MultiThreadExecutor executor(kMaxThreads);
+}
+
+TEST(MultiThreadExecutorTest, CanExecute) {
+ absl::CondVar cond;
+ std::atomic_bool done = false;
+ MultiThreadExecutor executor(kMaxThreads);
+ executor.Execute([&done, &cond]() {
+ done = true;
+ cond.SignalAll();
+ });
+ absl::Mutex mutex;
+ {
+ absl::MutexLock lock(&mutex);
+ if (!done) {
+ cond.WaitWithTimeout(&mutex, absl::Seconds(1));
+ }
+ }
+ EXPECT_TRUE(done);
+}
+
+TEST(MultiThreadExecutorTest, JobsExecuteInParallel) {
+ absl::Mutex mutex;
+ absl::CondVar thread_cond;
+ absl::CondVar test_cond;
+ MultiThreadExecutor executor(kMaxThreads);
+ int count = 0;
+
+ for (int i = 0; i < kMaxThreads; ++i) {
+ executor.Execute([&count, &mutex, &test_cond, &thread_cond]() {
+ absl::MutexLock lock(&mutex);
+ count++;
+ test_cond.Signal();
+ thread_cond.Wait(&mutex);
+ count--;
+ test_cond.Signal();
+ });
+ }
+
+ {
+ absl::Duration duration = absl::Milliseconds(kMaxThreads * 100);
+ absl::MutexLock lock(&mutex);
+ while (count < kMaxThreads) {
+ absl::Time start = absl::Now();
+ if (test_cond.WaitWithTimeout(&mutex, duration)) break;
+ duration -= absl::Now() - start;
+ }
+ }
+
+ EXPECT_EQ(count, kMaxThreads);
+ thread_cond.SignalAll();
+
+ {
+ absl::Duration duration = absl::Milliseconds(kMaxThreads * 100);
+ absl::MutexLock lock(&mutex);
+ while (count > 0) {
+ absl::Time start = absl::Now();
+ if (test_cond.WaitWithTimeout(&mutex, duration)) break;
+ duration -= absl::Now() - start;
+ }
+ }
+ EXPECT_EQ(count, 0);
+}
+
+TEST(MultiThreadExecutorTest, CanSubmit) {
+ MultiThreadExecutor executor(kMaxThreads);
+ Future<bool> future;
+ bool submitted =
+ executor.Submit<bool>([]() { return ExceptionOr<bool>{true}; }, &future);
+ EXPECT_TRUE(submitted);
+ EXPECT_TRUE(future.Get().result());
+}
+
+struct ThreadCheckTestClass {
+ MultiThreadExecutor executor{kMaxThreads};
+ int value ABSL_GUARDED_BY(executor) = 0;
+
+ void incValue() ABSL_EXCLUSIVE_LOCKS_REQUIRED(executor) { value++; }
+ int getValue() ABSL_EXCLUSIVE_LOCKS_REQUIRED(executor) { return value; }
+};
+
+TEST(MultiThreadExecutorTest, ThreadCheck_ExecuteRunnable) {
+ ThreadCheckTestClass test_class;
+
+ test_class.executor.Execute(
+ [&test_class]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(test_class.executor) {
+ test_class.incValue();
+ });
+}
+
+TEST(MultiThreadExecutorTest, ThreadCheck_SubmitCallable) {
+ ThreadCheckTestClass test_class;
+ Future<int> future;
+
+ bool submitted = test_class.executor.Submit<int>(
+ [&test_class]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(test_class.executor) {
+ return ExceptionOr<int>{test_class.getValue()};
+ },
+ &future);
+
+ EXPECT_TRUE(submitted);
+ EXPECT_EQ(future.Get().result(), 0);
+}
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/mutex.h b/chromium/third_party/nearby/src/internal/platform/mutex.h
new file mode 100644
index 00000000000..e7b6b564e3d
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/mutex.h
@@ -0,0 +1,78 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_MUTEX_H_
+#define PLATFORM_PUBLIC_MUTEX_H_
+
+#include <memory>
+
+#include "absl/base/thread_annotations.h"
+#include "internal/platform/implementation/mutex.h"
+#include "internal/platform/implementation/platform.h"
+
+namespace location {
+namespace nearby {
+
+// This is a classic mutex can be acquired at most once.
+// Atttempt to acuire mutex from the same thread that is holding it will likely
+// cause a deadlock.
+class ABSL_LOCKABLE Mutex final {
+ public:
+ using Platform = api::ImplementationPlatform;
+ using Mode = api::Mutex::Mode;
+
+ explicit Mutex(bool check = true)
+ : impl_(Platform::CreateMutex(check ? Mode::kRegular
+ : Mode::kRegularNoCheck)) {}
+ Mutex(Mutex&&) = default;
+ Mutex& operator=(Mutex&&) = default;
+ ~Mutex() = default;
+
+ void Lock() ABSL_EXCLUSIVE_LOCK_FUNCTION() { impl_->Lock(); }
+ void Unlock() ABSL_UNLOCK_FUNCTION() { impl_->Unlock(); }
+
+ private:
+ friend class ConditionVariable;
+ friend class MutexLock;
+ std::unique_ptr<api::Mutex> impl_;
+};
+
+// This mutex is compatible with Java definition:
+// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/Lock.html
+// This mutex may be acuired multiple times by a thread that is already holding
+// it without blocking.
+// It needs to be released equal number of times before any other thread could
+// successfully acquire it.
+class ABSL_LOCKABLE RecursiveMutex final {
+ public:
+ using Platform = api::ImplementationPlatform;
+ using Mode = api::Mutex::Mode;
+
+ RecursiveMutex() : impl_(Platform::CreateMutex(Mode::kRecursive)) {}
+ RecursiveMutex(RecursiveMutex&&) = default;
+ RecursiveMutex& operator=(RecursiveMutex&&) = default;
+ ~RecursiveMutex() = default;
+
+ void Lock() ABSL_EXCLUSIVE_LOCK_FUNCTION() { impl_->Lock(); }
+ void Unlock() ABSL_UNLOCK_FUNCTION() { impl_->Unlock(); }
+
+ private:
+ friend class MutexLock;
+ std::unique_ptr<api::Mutex> impl_;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_MUTEX_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/mutex_lock.h b/chromium/third_party/nearby/src/internal/platform/mutex_lock.h
new file mode 100644
index 00000000000..463ef8b7af0
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/mutex_lock.h
@@ -0,0 +1,45 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_MUTEX_LOCK_H_
+#define PLATFORM_PUBLIC_MUTEX_LOCK_H_
+
+#include "absl/base/thread_annotations.h"
+#include "internal/platform/implementation/mutex.h"
+#include "internal/platform/mutex.h"
+
+namespace location {
+namespace nearby {
+
+// An RAII mechanism to acquire a Lock over a block of code.
+class ABSL_SCOPED_LOCKABLE MutexLock final {
+ public:
+ explicit MutexLock(Mutex* mutex) ABSL_EXCLUSIVE_LOCK_FUNCTION(mutex)
+ : mutex_(mutex->impl_.get()) {
+ mutex_->Lock();
+ }
+ explicit MutexLock(RecursiveMutex* mutex) ABSL_EXCLUSIVE_LOCK_FUNCTION(mutex)
+ : mutex_(mutex->impl_.get()) {
+ mutex_->Lock();
+ }
+ ~MutexLock() ABSL_UNLOCK_FUNCTION() { mutex_->Unlock(); }
+
+ private:
+ api::Mutex* mutex_;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_MUTEX_LOCK_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/mutex_test.cc b/chromium/third_party/nearby/src/internal/platform/mutex_test.cc
new file mode 100644
index 00000000000..31905d250a5
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/mutex_test.cc
@@ -0,0 +1,117 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/mutex.h"
+
+#include "gtest/gtest.h"
+#include "absl/synchronization/mutex.h"
+#include "absl/time/clock.h"
+#include "absl/time/time.h"
+#include "internal/platform/condition_variable.h"
+#include "internal/platform/single_thread_executor.h"
+
+namespace location {
+namespace nearby {
+namespace {
+
+class MutexTest : public testing::Test {
+ public:
+ void VerifyStepReached(int expected) {
+ absl::MutexLock lock(&step_mutex_);
+ absl::Time deadline = absl::Now() + kTimeToWait;
+ while (step_ != expected) {
+ if (step_cond_.WaitWithDeadline(&step_mutex_, deadline)) break;
+ }
+ EXPECT_EQ(step_, expected);
+ // Make sure we are not progressing further.
+ absl::SleepFor(kTimeToWait);
+ EXPECT_EQ(step_, expected);
+ }
+
+ protected:
+ SingleThreadExecutor executor_;
+ const absl::Duration kTimeToWait = absl::Milliseconds(500);
+ std::atomic_int step_ = 0;
+ absl::Mutex step_mutex_;
+ absl::CondVar step_cond_;
+};
+
+TEST_F(MutexTest, ConstructorDestructorWorks) {
+ Mutex test_mutex;
+ SUCCEED();
+}
+
+TEST_F(MutexTest, BasicLockingWorks) {
+ Mutex test_mutex;
+ test_mutex.Lock();
+ executor_.Execute([this, &test_mutex]() {
+ step_ = 1;
+ step_cond_.Signal();
+ test_mutex.Lock();
+ test_mutex.Unlock();
+ step_ = 2;
+ step_cond_.Signal();
+ });
+ VerifyStepReached(1);
+ test_mutex.Unlock();
+ VerifyStepReached(2);
+}
+
+#ifdef THREAD_SANITIZER
+TEST_F(MutexTest, DISABLED_DoubleLockIsDeadlock)
+ABSL_NO_THREAD_SAFETY_ANALYSIS {
+#else
+TEST_F(MutexTest, DoubleLockIsDeadlock) ABSL_NO_THREAD_SAFETY_ANALYSIS {
+#endif
+ Mutex test_mutex{/*check=*/false}; // Disable run-time deadlock detection.
+ test_mutex.Lock();
+ executor_.Execute([this, &test_mutex]() ABSL_NO_THREAD_SAFETY_ANALYSIS {
+ step_ = 1;
+ step_cond_.Signal(); // We entered executor.
+ test_mutex.Lock();
+ step_ = 2;
+ step_cond_.Signal(); // We acquired the test lock.
+ test_mutex.Lock(); // Deadlock. (Main thread should save us).
+ step_ = 3;
+ step_cond_.Signal(); // We are done.
+ });
+ VerifyStepReached(1);
+ test_mutex.Unlock(); // Let executor proceed to step 2.
+ VerifyStepReached(2);
+ test_mutex.Unlock(); // Bring executor out of deadlock.
+ VerifyStepReached(3);
+ test_mutex.Unlock(); // Unlock before shutdown.
+}
+
+TEST_F(MutexTest, DoubleLockIsNotDeadlock) {
+ RecursiveMutex test_mutex;
+ test_mutex.Lock();
+ executor_.Execute([this, &test_mutex]() ABSL_NO_THREAD_SAFETY_ANALYSIS {
+ step_ = 1;
+ step_cond_.Signal(); // We entered executor.
+ test_mutex.Lock();
+ test_mutex.Lock();
+ test_mutex.Unlock();
+ test_mutex.Unlock();
+ step_ = 2;
+ step_cond_.Signal(); // We are done.
+ });
+ VerifyStepReached(1);
+ test_mutex.Unlock(); // Let executor continue.
+ VerifyStepReached(2);
+}
+
+} // namespace
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/nsd_service_info.cc b/chromium/third_party/nearby/src/internal/platform/nsd_service_info.cc
new file mode 100644
index 00000000000..24624c301df
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/nsd_service_info.cc
@@ -0,0 +1,23 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/nsd_service_info.h"
+
+namespace location {
+namespace nearby {
+
+constexpr absl::string_view NsdServiceInfo::kNsdTypeFormat;
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/nsd_service_info.h b/chromium/third_party/nearby/src/internal/platform/nsd_service_info.h
index d870bd41f0b..d870bd41f0b 100644
--- a/chromium/third_party/nearby/src/cpp/platform/base/nsd_service_info.h
+++ b/chromium/third_party/nearby/src/internal/platform/nsd_service_info.h
diff --git a/chromium/third_party/nearby/src/internal/platform/output_stream.h b/chromium/third_party/nearby/src/internal/platform/output_stream.h
new file mode 100644
index 00000000000..fbc644e07fd
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/output_stream.h
@@ -0,0 +1,39 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_BASE_OUTPUT_STREAM_H_
+#define PLATFORM_BASE_OUTPUT_STREAM_H_
+
+#include "internal/platform/byte_array.h"
+#include "internal/platform/exception.h"
+
+namespace location {
+namespace nearby {
+
+// An OutputStream represents an output stream of bytes.
+//
+// https://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html
+class OutputStream {
+ public:
+ virtual ~OutputStream() = default;
+
+ virtual Exception Write(const ByteArray& data) = 0; // throws Exception::kIo
+ virtual Exception Flush() = 0; // throws Exception::kIo
+ virtual Exception Close() = 0; // throws Exception::kIo
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_BASE_OUTPUT_STREAM_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/payload_id.h b/chromium/third_party/nearby/src/internal/platform/payload_id.h
index d28eebe0356..d28eebe0356 100644
--- a/chromium/third_party/nearby/src/cpp/platform/base/payload_id.h
+++ b/chromium/third_party/nearby/src/internal/platform/payload_id.h
diff --git a/chromium/third_party/nearby/src/internal/platform/pending_job_registry.cc b/chromium/third_party/nearby/src/internal/platform/pending_job_registry.cc
new file mode 100644
index 00000000000..c546805c63e
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/pending_job_registry.cc
@@ -0,0 +1,91 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/pending_job_registry.h"
+
+#include "internal/platform/logging.h"
+#include "internal/platform/mutex_lock.h"
+#include "internal/platform/system_clock.h"
+
+namespace location {
+namespace nearby {
+
+namespace {
+absl::Duration kMinReportInterval = absl::Seconds(60);
+absl::Duration kReportPendingJobsOlderThan = absl::Seconds(40);
+absl::Duration kReportRunningJobsOlderThan = absl::Seconds(60);
+} // namespace
+
+PendingJobRegistry& PendingJobRegistry::GetInstance() {
+ static PendingJobRegistry* instance = new PendingJobRegistry();
+ return *instance;
+}
+
+PendingJobRegistry::PendingJobRegistry() = default;
+
+PendingJobRegistry::~PendingJobRegistry() = default;
+
+void PendingJobRegistry::AddPendingJob(const std::string& name,
+ absl::Time post_time) {
+ MutexLock lock(&mutex_);
+ pending_jobs_.emplace(CreateKey(name, post_time), post_time);
+}
+
+void PendingJobRegistry::RemovePendingJob(const std::string& name,
+ absl::Time post_time) {
+ MutexLock lock(&mutex_);
+ pending_jobs_.erase(CreateKey(name, post_time));
+}
+
+void PendingJobRegistry::AddRunningJob(const std::string& name,
+ absl::Time post_time) {
+ MutexLock lock(&mutex_);
+ running_jobs_.emplace(CreateKey(name, post_time),
+ SystemClock::ElapsedRealtime());
+}
+
+void PendingJobRegistry::RemoveRunningJob(const std::string& name,
+ absl::Time post_time) {
+ MutexLock lock(&mutex_);
+ running_jobs_.erase(CreateKey(name, post_time));
+}
+
+void PendingJobRegistry::ListJobs() {
+ auto current_time = SystemClock::ElapsedRealtime();
+ MutexLock lock(&mutex_);
+ if (current_time - list_jobs_time_ < kMinReportInterval) return;
+ for (auto& job : pending_jobs_) {
+ auto age = current_time - job.second;
+ if (age >= kReportPendingJobsOlderThan) {
+ NEARBY_LOGS(INFO) << "Task \"" << job.first << "\" is waiting for "
+ << absl::ToInt64Seconds(age) << " s";
+ }
+ }
+ for (auto& job : running_jobs_) {
+ auto age = current_time - job.second;
+ if (age >= kReportRunningJobsOlderThan) {
+ NEARBY_LOGS(INFO) << "Task \"" << job.first << "\" is running for "
+ << absl::ToInt64Seconds(age) << " s";
+ }
+ }
+ list_jobs_time_ = current_time;
+}
+
+std::string PendingJobRegistry::CreateKey(const std::string& name,
+ absl::Time post_time) {
+ return name + "." + std::to_string(absl::ToUnixNanos(post_time));
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/pending_job_registry.h b/chromium/third_party/nearby/src/internal/platform/pending_job_registry.h
new file mode 100644
index 00000000000..f2d85e4a37e
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/pending_job_registry.h
@@ -0,0 +1,55 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_PENDING_JOB_REGISTRY_H_
+#define PLATFORM_PUBLIC_PENDING_JOB_REGISTRY_H_
+
+#include "absl/base/thread_annotations.h"
+#include "absl/time/time.h"
+#include "internal/platform/mutex.h"
+
+namespace location {
+namespace nearby {
+
+// A global registry of running tasks. The goal is to help us monitor
+// tasks that are either waiting too long for their turn or they never finish
+class PendingJobRegistry {
+ public:
+ static PendingJobRegistry& GetInstance();
+
+ ~PendingJobRegistry();
+
+ void AddPendingJob(const std::string& name, absl::Time post_time);
+ void RemovePendingJob(const std::string& name, absl::Time post_time);
+ void AddRunningJob(const std::string& name, absl::Time post_time);
+ void RemoveRunningJob(const std::string& name, absl::Time post_time);
+ void ListJobs();
+
+ private:
+ PendingJobRegistry();
+
+ std::string CreateKey(const std::string& name, absl::Time post_time);
+
+ Mutex mutex_;
+ absl::flat_hash_map<const std::string, absl::Time> pending_jobs_
+ ABSL_GUARDED_BY(mutex_);
+ absl::flat_hash_map<const std::string, absl::Time> running_jobs_
+ ABSL_GUARDED_BY(mutex_);
+ absl::Time list_jobs_time_ ABSL_GUARDED_BY(mutex_) = absl::UnixEpoch();
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_PENDING_JOB_REGISTRY_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/pipe.cc b/chromium/third_party/nearby/src/internal/platform/pipe.cc
new file mode 100644
index 00000000000..59de0a15218
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/pipe.cc
@@ -0,0 +1,35 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/pipe.h"
+
+#include "internal/platform/implementation/condition_variable.h"
+#include "internal/platform/implementation/mutex.h"
+#include "internal/platform/implementation/platform.h"
+
+namespace location {
+namespace nearby {
+
+namespace {
+using Platform = api::ImplementationPlatform;
+}
+
+Pipe::Pipe() {
+ auto mutex = Platform::CreateMutex(api::Mutex::Mode::kRegular);
+ auto cond = Platform::CreateConditionVariable(mutex.get());
+ Setup(std::move(mutex), std::move(cond));
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/pipe.h b/chromium/third_party/nearby/src/internal/platform/pipe.h
new file mode 100644
index 00000000000..35d33b6f3ef
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/pipe.h
@@ -0,0 +1,36 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_PIPE_H_
+#define PLATFORM_PUBLIC_PIPE_H_
+
+#include "internal/platform/base_pipe.h"
+
+namespace location {
+namespace nearby {
+
+// See for details:
+// http://google3/platform/base/base_pipe.h
+class Pipe final : public BasePipe {
+ public:
+ Pipe();
+ ~Pipe() override = default;
+ Pipe(Pipe&&) = delete;
+ Pipe& operator=(Pipe&&) = delete;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_PIPE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/pipe_test.cc b/chromium/third_party/nearby/src/internal/platform/pipe_test.cc
new file mode 100644
index 00000000000..47c3f27cbaa
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/pipe_test.cc
@@ -0,0 +1,346 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/pipe.h"
+
+#include <pthread.h>
+
+#include <atomic>
+#include <cstring>
+#include <string>
+
+#include "gtest/gtest.h"
+#include "internal/platform/prng.h"
+#include "internal/platform/runnable.h"
+
+namespace location {
+namespace nearby {
+
+TEST(PipeTest, ConstructorDestructorWorks) {
+ Pipe pipe;
+ SUCCEED();
+}
+
+TEST(PipeTest, SimpleWriteRead) {
+ Pipe pipe;
+ InputStream& input_stream{pipe.GetInputStream()};
+ OutputStream& output_stream{pipe.GetOutputStream()};
+
+ std::string data("ABCD");
+ EXPECT_TRUE(output_stream.Write(ByteArray(data)).Ok());
+
+ ExceptionOr<ByteArray> read_data = input_stream.Read(Pipe::kChunkSize);
+ EXPECT_TRUE(read_data.ok());
+ EXPECT_EQ(data, std::string(read_data.result()));
+}
+
+TEST(PipeTest, WriteEndClosedBeforeRead) {
+ Pipe pipe;
+ InputStream& input_stream{pipe.GetInputStream()};
+ OutputStream& output_stream{pipe.GetOutputStream()};
+
+ std::string data("ABCD");
+ EXPECT_TRUE(output_stream.Write(ByteArray(data)).Ok());
+
+ // Close the write end before the read end has even begun reading.
+ EXPECT_TRUE(output_stream.Close().Ok());
+
+ // We should still be able to read what was written.
+ ExceptionOr<ByteArray> read_data = input_stream.Read(Pipe::kChunkSize);
+ EXPECT_TRUE(read_data.ok());
+ EXPECT_EQ(data, std::string(read_data.result()));
+
+ // And after that, we should get our indication that all the data that could
+ // ever be read, has already been read.
+ read_data = input_stream.Read(Pipe::kChunkSize);
+ EXPECT_TRUE(read_data.ok());
+ EXPECT_TRUE(read_data.result().Empty());
+}
+
+TEST(PipeTest, ReadEndClosedBeforeWrite) {
+ Pipe pipe;
+ InputStream& input_stream{pipe.GetInputStream()};
+ OutputStream& output_stream{pipe.GetOutputStream()};
+
+ // Close the read end before the write end has even begun writing.
+ EXPECT_TRUE(input_stream.Close().Ok());
+
+ std::string data("ABCD");
+ EXPECT_TRUE(output_stream.Write(ByteArray(data)).Raised(Exception::kIo));
+}
+
+TEST(PipeTest, SizedReadMoreThanFirstChunkSize) {
+ Pipe pipe;
+ InputStream& input_stream{pipe.GetInputStream()};
+ OutputStream& output_stream{pipe.GetOutputStream()};
+
+ std::string data("ABCD");
+ EXPECT_TRUE(output_stream.Write(ByteArray(data)).Ok());
+
+ // Even though we ask for double of what's there in the first chunk, we should
+ // get back only what's there in that first chunk, and that's alright.
+ ExceptionOr<ByteArray> read_data = input_stream.Read(data.size() * 2);
+ EXPECT_TRUE(read_data.ok());
+ EXPECT_EQ(data, std::string(read_data.result()));
+}
+
+TEST(PipeTest, SizedReadLessThanFirstChunkSize) {
+ Pipe pipe;
+ InputStream& input_stream{pipe.GetInputStream()};
+ OutputStream& output_stream{pipe.GetOutputStream()};
+
+ std::string data_first_part("ABCD");
+ std::string data_second_part("EFGHIJ");
+ std::string data = data_first_part + data_second_part;
+ EXPECT_TRUE(output_stream.Write(ByteArray(data)).Ok());
+
+ // When we ask for less than what's there in the first chunk, we should get
+ // back exactly what we asked for, with the remainder still being available
+ // for the next read.
+ std::int64_t desired_size = data_first_part.size();
+ ExceptionOr<ByteArray> first_read_data = input_stream.Read(desired_size);
+ EXPECT_TRUE(first_read_data.ok());
+ EXPECT_EQ(data_first_part, std::string(first_read_data.result()));
+
+ // Now read the remainder, and get everything that ought to have been left.
+ ExceptionOr<ByteArray> second_read_data = input_stream.Read(Pipe::kChunkSize);
+ EXPECT_TRUE(second_read_data.ok());
+ EXPECT_EQ(data_second_part, std::string(second_read_data.result()));
+}
+
+TEST(PipeTest, ReadAfterInputStreamClosed) {
+ Pipe pipe;
+ InputStream& input_stream{pipe.GetInputStream()};
+
+ input_stream.Close();
+
+ ExceptionOr<ByteArray> read_data = input_stream.Read(Pipe::kChunkSize);
+ EXPECT_TRUE(!read_data.ok());
+ EXPECT_TRUE(read_data.GetException().Raised(Exception::kIo));
+}
+
+TEST(PipeTest, WriteAfterOutputStreamClosed) {
+ Pipe pipe;
+ OutputStream& output_stream{pipe.GetOutputStream()};
+
+ output_stream.Close();
+
+ std::string data("ABCD");
+ EXPECT_TRUE(output_stream.Write(ByteArray(data)).Raised(Exception::kIo));
+}
+
+TEST(PipeTest, RepeatedClose) {
+ Pipe pipe;
+ InputStream& input_stream{pipe.GetInputStream()};
+ OutputStream& output_stream{pipe.GetOutputStream()};
+
+ EXPECT_TRUE(output_stream.Close().Ok());
+ EXPECT_TRUE(output_stream.Close().Ok());
+ EXPECT_TRUE(output_stream.Close().Ok());
+
+ EXPECT_TRUE(input_stream.Close().Ok());
+ EXPECT_TRUE(input_stream.Close().Ok());
+ EXPECT_TRUE(input_stream.Close().Ok());
+}
+
+class Thread {
+ public:
+ Thread() : thread_(), attr_(), runnable_() {
+ pthread_attr_init(&attr_);
+ pthread_attr_setdetachstate(&attr_, PTHREAD_CREATE_JOINABLE);
+ }
+ ~Thread() { pthread_attr_destroy(&attr_); }
+
+ void Start(Runnable runnable) {
+ runnable_ = runnable;
+
+ pthread_create(&thread_, &attr_, Thread::Body, this);
+ }
+
+ void Join() { pthread_join(thread_, nullptr); }
+
+ private:
+ static void* Body(void* args) {
+ reinterpret_cast<Thread*>(args)->runnable_();
+ return nullptr;
+ }
+
+ pthread_t thread_;
+ pthread_attr_t attr_;
+ Runnable runnable_;
+};
+
+TEST(PipeTest, ReadBlockedUntilWrite) {
+ using CrossThreadBool = std::atomic_bool;
+
+ class ReaderRunnable {
+ public:
+ ReaderRunnable(InputStream* input_stream,
+ absl::string_view expected_read_data,
+ CrossThreadBool* ok_for_read_to_unblock)
+ : input_stream_(input_stream),
+ expected_read_data_(expected_read_data),
+ ok_for_read_to_unblock_(ok_for_read_to_unblock) {}
+ ~ReaderRunnable() = default;
+
+ // Signature "void()" satisfies Runnable.
+ void operator()() {
+ ExceptionOr<ByteArray> read_data = input_stream_->Read(Pipe::kChunkSize);
+
+ // Make sure read() doesn't return before it's appropriate.
+ if (!*ok_for_read_to_unblock_) {
+ FAIL() << "read() unblocked before it was supposed to.";
+ }
+
+ // And then run our normal set of checks to make sure the read() was
+ // successful.
+ EXPECT_TRUE(read_data.ok());
+ EXPECT_EQ(expected_read_data_, std::string(read_data.result()));
+ }
+
+ private:
+ InputStream* input_stream_;
+ const std::string expected_read_data_;
+ CrossThreadBool* ok_for_read_to_unblock_;
+ };
+
+ Pipe pipe;
+ OutputStream& output_stream{pipe.GetOutputStream()};
+
+ // State shared between this thread (the writer) and reader_thread.
+ CrossThreadBool ok_for_read_to_unblock = false;
+ std::string data("ABCD");
+
+ // Kick off reader_thread.
+ Thread reader_thread;
+ reader_thread.Start(
+ ReaderRunnable(&pipe.GetInputStream(), data, &ok_for_read_to_unblock));
+
+ // Introduce a delay before we actually write anything.
+ absl::SleepFor(absl::Seconds(5));
+ // Mark that we're done with the delay, and that the write is about to occur
+ // (this is slightly earlier than it ought to be, but there's no way to
+ // atomically set this from within the implementation of write(), and doing it
+ // after is too late for the purposes of this test).
+ ok_for_read_to_unblock = true;
+
+ // Perform the actual write.
+ EXPECT_TRUE(output_stream.Write(ByteArray(data)).Ok());
+
+ // And wait for reader_thread to finish.
+ reader_thread.Join();
+}
+
+TEST(PipeTest, ConcurrentWriteAndRead) {
+ class BaseRunnable {
+ protected:
+ explicit BaseRunnable(const std::vector<std::string>& chunks)
+ : chunks_(chunks), prng_() {}
+ virtual ~BaseRunnable() = default;
+
+ void RandomSleep() {
+ // Generate a random sleep between 100 and 1000 milliseconds.
+ absl::SleepFor(absl::Milliseconds(BoundedUint32(100, 1000)));
+ }
+
+ const std::vector<std::string>& chunks_;
+
+ private:
+ // Both ends of the bounds are inclusive.
+ std::uint32_t BoundedUint32(std::uint32_t lower_bound,
+ std::uint32_t upper_bound) {
+ return (prng_.NextUint32() % (upper_bound - lower_bound + 1)) +
+ lower_bound;
+ }
+
+ Prng prng_;
+ };
+
+ class WriterRunnable : public BaseRunnable {
+ public:
+ WriterRunnable(OutputStream* output_stream,
+ const std::vector<std::string>& chunks)
+ : BaseRunnable(chunks), output_stream_(output_stream) {}
+ ~WriterRunnable() override = default;
+
+ void operator()() {
+ for (auto& chunk : chunks_) {
+ RandomSleep(); // Random pauses before each write.
+ EXPECT_TRUE(output_stream_->Write(ByteArray(chunk)).Ok());
+ }
+
+ RandomSleep(); // A random pause before closing the writer end.
+ EXPECT_TRUE(output_stream_->Close().Ok());
+ }
+
+ private:
+ OutputStream* output_stream_;
+ };
+
+ class ReaderRunnable : public BaseRunnable {
+ public:
+ ReaderRunnable(InputStream* input_stream,
+ const std::vector<std::string>& chunks)
+ : BaseRunnable(chunks), input_stream_(input_stream) {}
+ ~ReaderRunnable() override = default;
+
+ void operator()() {
+ // First, calculate what we expect to receive, in total.
+ std::string expected_data;
+ for (auto& chunk : chunks_) {
+ expected_data += chunk;
+ }
+
+ // Then, start actually receiving.
+ std::string actual_data;
+ while (true) {
+ RandomSleep(); // Random pauses before each read.
+ ExceptionOr<ByteArray> read_data =
+ input_stream_->Read(Pipe::kChunkSize);
+ if (read_data.ok()) {
+ ByteArray result = read_data.result();
+ if (result.Empty()) {
+ break; // Normal exit from the read loop.
+ }
+ actual_data += std::string(result);
+ } else {
+ break; // Erroneous exit from the read loop.
+ }
+ }
+
+ // And once we're done, check that we got everything we expected.
+ EXPECT_EQ(expected_data, actual_data);
+ }
+
+ private:
+ InputStream* input_stream_;
+ };
+
+ Pipe pipe;
+
+ std::vector<std::string> chunks;
+ chunks.push_back("ABCD");
+ chunks.push_back("EFGH");
+ chunks.push_back("IJKL");
+
+ Thread writer_thread;
+ Thread reader_thread;
+ writer_thread.Start(WriterRunnable(&pipe.GetOutputStream(), chunks));
+ reader_thread.Start(ReaderRunnable(&pipe.GetInputStream(), chunks));
+ writer_thread.Join();
+ reader_thread.Join();
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/prng.cc b/chromium/third_party/nearby/src/internal/platform/prng.cc
new file mode 100644
index 00000000000..4f8af54f2a0
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/prng.cc
@@ -0,0 +1,59 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/prng.h"
+
+#include <limits>
+
+#include "absl/time/clock.h"
+
+namespace location {
+namespace nearby {
+
+#define UNSIGNED_INT_BITMASK (std::numeric_limits<unsigned int>::max())
+
+Prng::Prng() {
+ // absl::GetCurrentTimeNanos() returns 64 bits, but srand() wants an unsigned
+ // int, so we may have to lose some of those 64 bits.
+ //
+ // The lower bits of the current-time-in-nanos are likely to have more entropy
+ // than the upper bits, so choose the former.
+ srand(static_cast<unsigned int>(absl::GetCurrentTimeNanos() &
+ UNSIGNED_INT_BITMASK));
+}
+
+Prng::~Prng() {
+ // Nothing to do.
+}
+
+#define RANDOM_BYTE (rand() & 0x0FF) // NOLINT
+
+std::int32_t Prng::NextInt32() {
+ return (static_cast<std::int32_t>(RANDOM_BYTE) << 24) |
+ (static_cast<std::int32_t>(RANDOM_BYTE) << 16) |
+ (static_cast<std::int32_t>(RANDOM_BYTE) << 8) |
+ (static_cast<std::int32_t>(RANDOM_BYTE));
+}
+
+std::uint32_t Prng::NextUint32() {
+ return static_cast<std::uint32_t>(NextInt32());
+}
+
+std::int64_t Prng::NextInt64() {
+ return (static_cast<std::int64_t>(NextInt32()) << 32) |
+ (static_cast<std::int64_t>(NextUint32()));
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/prng.h b/chromium/third_party/nearby/src/internal/platform/prng.h
index a4afb491eb4..a4afb491eb4 100644
--- a/chromium/third_party/nearby/src/cpp/platform/base/prng.h
+++ b/chromium/third_party/nearby/src/internal/platform/prng.h
diff --git a/chromium/third_party/nearby/src/internal/platform/prng_test.cc b/chromium/third_party/nearby/src/internal/platform/prng_test.cc
new file mode 100644
index 00000000000..0f4e663ece3
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/prng_test.cc
@@ -0,0 +1,87 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/prng.h"
+
+#include "gtest/gtest.h"
+
+namespace location {
+namespace nearby {
+
+enum class TestMode {
+ kUpperHalfOfInt64,
+ kLowerHalfOfInt64,
+ kInt32,
+ kUint32,
+};
+
+TEST(PrngTest, NextInt32) {
+ std::int32_t i = Prng().NextInt32();
+ EXPECT_LE(i, std::numeric_limits<std::int32_t>::max());
+ EXPECT_GE(i, std::numeric_limits<std::int32_t>::min());
+}
+
+TEST(PrngTest, NextUInt32) {
+ std::uint32_t i = Prng().NextUint32();
+ EXPECT_LE(i, std::numeric_limits<std::uint32_t>::max());
+ EXPECT_GE(i, std::numeric_limits<std::uint32_t>::min());
+}
+
+TEST(PrngTest, NextInt64) {
+ std::int64_t i = Prng().NextInt64();
+ EXPECT_LE(i, std::numeric_limits<std::int64_t>::max());
+ EXPECT_GE(i, std::numeric_limits<std::int64_t>::min());
+}
+
+void ValidateRandom(TestMode mode) {
+ int count_all_zeros = 0;
+ int count_all_ones = 0;
+ std::uint32_t i;
+ Prng prng;
+ for (int count = 0; count < 100; ++count) {
+ switch (mode) {
+ case TestMode::kUpperHalfOfInt64:
+ i = static_cast<std::uint32_t>(prng.NextInt64() >> 32);
+ break;
+ case TestMode::kLowerHalfOfInt64:
+ i = static_cast<std::uint32_t>(prng.NextInt64());
+ break;
+ case TestMode::kInt32:
+ i = static_cast<std::uint32_t>(prng.NextInt32());
+ break;
+ case TestMode::kUint32:
+ i = static_cast<std::uint32_t>(prng.NextUint32());
+ break;
+ }
+ if (!i) count_all_zeros++;
+ if (i == 0xFFFFFFFF) count_all_ones++;
+ }
+ EXPECT_LE(count_all_zeros, 1);
+ EXPECT_LE(count_all_ones, 1);
+}
+
+TEST(PrngTest, ValidateUpperHalfOfInt64) {
+ ValidateRandom(TestMode::kUpperHalfOfInt64);
+}
+
+TEST(PrngTest, ValidateLowerHalfOfInt64) {
+ ValidateRandom(TestMode::kLowerHalfOfInt64);
+}
+
+TEST(PrngTest, ValidateInt32) { ValidateRandom(TestMode::kInt32); }
+
+TEST(PrngTest, ValidateUint32) { ValidateRandom(TestMode::kUint32); }
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/runnable.h b/chromium/third_party/nearby/src/internal/platform/runnable.h
index 24f2349ce25..24f2349ce25 100644
--- a/chromium/third_party/nearby/src/cpp/platform/base/runnable.h
+++ b/chromium/third_party/nearby/src/internal/platform/runnable.h
diff --git a/chromium/third_party/nearby/src/internal/platform/scheduled_executor.h b/chromium/third_party/nearby/src/internal/platform/scheduled_executor.h
new file mode 100644
index 00000000000..47d87085de8
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/scheduled_executor.h
@@ -0,0 +1,109 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_SCHEDULED_EXECUTOR_H_
+#define PLATFORM_PUBLIC_SCHEDULED_EXECUTOR_H_
+
+#include <cstdint>
+#include <functional>
+#include <memory>
+
+#include "absl/base/thread_annotations.h"
+#include "absl/time/time.h"
+#include "internal/platform/implementation/platform.h"
+#include "internal/platform/implementation/scheduled_executor.h"
+#include "internal/platform/runnable.h"
+#include "internal/platform/cancelable.h"
+#include "internal/platform/cancellable_task.h"
+#include "internal/platform/lockable.h"
+#include "internal/platform/monitored_runnable.h"
+#include "internal/platform/mutex.h"
+#include "internal/platform/mutex_lock.h"
+#include "internal/platform/thread_check_callable.h"
+#include "internal/platform/thread_check_runnable.h"
+
+namespace location {
+namespace nearby {
+
+// An Executor that can schedule commands to run after a given delay, or to
+// execute periodically.
+//
+// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html
+class ABSL_LOCKABLE ScheduledExecutor final : public Lockable {
+ public:
+ using Platform = api::ImplementationPlatform;
+
+ ScheduledExecutor() : impl_(Platform::CreateScheduledExecutor()) {}
+ ScheduledExecutor(ScheduledExecutor&& other) { *this = std::move(other); }
+ ~ScheduledExecutor() {
+ MutexLock lock(&mutex_);
+ DoShutdown();
+ }
+
+ ScheduledExecutor& operator=(ScheduledExecutor&& other)
+ ABSL_LOCKS_EXCLUDED(mutex_) {
+ MutexLock lock(&mutex_);
+ {
+ MutexLock other_lock(&other.mutex_);
+ impl_ = std::move(other.impl_);
+ }
+ return *this;
+ }
+ void Execute(const std::string& name, Runnable&& runnable)
+ ABSL_LOCKS_EXCLUDED(mutex_) {
+ MutexLock lock(&mutex_);
+ if (impl_)
+ impl_->Execute(MonitoredRunnable(
+ name, ThreadCheckRunnable(this, std::move(runnable))));
+ }
+
+ void Execute(Runnable&& runnable) ABSL_LOCKS_EXCLUDED(mutex_) {
+ MutexLock lock(&mutex_);
+ if (impl_) impl_->Execute(ThreadCheckRunnable(this, std::move(runnable)));
+ }
+
+ void Shutdown() ABSL_LOCKS_EXCLUDED(mutex_) {
+ MutexLock lock(&mutex_);
+ DoShutdown();
+ }
+
+ Cancelable Schedule(Runnable&& runnable, absl::Duration duration)
+ ABSL_LOCKS_EXCLUDED(mutex_) {
+ MutexLock lock(&mutex_);
+ if (impl_) {
+ auto task = std::make_shared<CancellableTask>(
+ ThreadCheckRunnable(this, std::move(runnable)));
+ return Cancelable(task,
+ impl_->Schedule([task]() { (*task)(); }, duration));
+ } else {
+ return Cancelable();
+ }
+ }
+
+ private:
+ void DoShutdown() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_) {
+ if (impl_) {
+ impl_->Shutdown();
+ impl_.reset();
+ }
+ }
+
+ mutable Mutex mutex_;
+ std::unique_ptr<api::ScheduledExecutor> ABSL_GUARDED_BY(mutex_) impl_;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_SCHEDULED_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/scheduled_executor_test.cc b/chromium/third_party/nearby/src/internal/platform/scheduled_executor_test.cc
new file mode 100644
index 00000000000..675cf36fca6
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/scheduled_executor_test.cc
@@ -0,0 +1,206 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/scheduled_executor.h"
+
+#include <atomic>
+#include <functional>
+
+#include "gtest/gtest.h"
+#include "absl/synchronization/mutex.h"
+#include "absl/time/clock.h"
+#include "absl/time/time.h"
+#include "internal/platform/exception.h"
+#include "internal/platform/count_down_latch.h"
+
+namespace location {
+namespace nearby {
+
+// kShortDelay must be significant enough to guarantee that OS under heavy load
+// should be able to execute the non-blocking test paths within this time.
+absl::Duration kShortDelay = absl::Milliseconds(100);
+
+// kLongDelay must be long enough to make sure that under OS under heavy load
+// will let kShortDelay fire and jobs scheduled before the kLongDelay fires.
+absl::Duration kLongDelay = 10 * kShortDelay;
+
+TEST(ScheduledExecutorTest, ConsructorDestructorWorks) {
+ ScheduledExecutor executor;
+}
+
+TEST(ScheduledExecutorTest, CanExecute) {
+ absl::Mutex mutex;
+ absl::CondVar cond;
+ std::atomic_bool done = false;
+ ScheduledExecutor executor;
+ executor.Execute([&done, &cond]() {
+ done = true;
+ cond.SignalAll();
+ });
+ {
+ absl::MutexLock lock(&mutex);
+ if (!done) {
+ cond.WaitWithTimeout(&mutex, kLongDelay);
+ }
+ }
+ EXPECT_TRUE(done);
+}
+
+TEST(ScheduledExecutorTest, CanSchedule) {
+ ScheduledExecutor executor;
+ std::atomic_int value = 0;
+ absl::Mutex mutex;
+ absl::CondVar cond;
+ // schedule job due in kLongDelay.
+ executor.Schedule(
+ [&value, &cond]() {
+ EXPECT_EQ(value, 1);
+ value = 5;
+ cond.Signal();
+ },
+ kLongDelay);
+ // schedule job due in kShortDelay; must fire before the first one.
+ executor.Schedule(
+ [&value]() {
+ EXPECT_EQ(value, 0);
+ value = 1;
+ },
+ kShortDelay);
+ {
+ // wait for the final job to unblock us; wait longer than kLongDelay.
+ absl::MutexLock lock(&mutex);
+ cond.WaitWithTimeout(&mutex, 2 * kLongDelay);
+ }
+ EXPECT_EQ(value, 5);
+}
+
+TEST(ScheduledExecutorTest, CanCancel) {
+ ScheduledExecutor executor;
+ std::atomic_int value = 0;
+ Cancelable cancelable =
+ executor.Schedule([&value]() { value += 1; }, kShortDelay);
+ EXPECT_EQ(value, 0);
+ EXPECT_TRUE(cancelable.Cancel());
+ absl::SleepFor(kLongDelay);
+ EXPECT_EQ(value, 0);
+}
+
+TEST(ScheduledExecutorTest, CanCancelTwice) {
+ ScheduledExecutor executor;
+ std::atomic_int value = 0;
+ Cancelable cancelable =
+ executor.Schedule([&value]() { value += 1; }, kShortDelay);
+ EXPECT_EQ(value, 0);
+
+ cancelable.Cancel();
+ cancelable.Cancel();
+
+ absl::SleepFor(kLongDelay);
+ EXPECT_EQ(value, 0);
+}
+
+TEST(ScheduledExecutorTest, FailToCancel) {
+ absl::Mutex mutex;
+ absl::CondVar cond;
+ ScheduledExecutor executor;
+ std::atomic_int value = 0;
+ // Schedule job in kShortDelay, which will we will attempt to cancel later.
+ Cancelable cancelable =
+ executor.Schedule([&value]() { value += 1; }, kShortDelay);
+ // schedule another job to test results of the first one, in kLongDelay.
+ executor.Schedule(
+ [&cancelable, &cond]() {
+ EXPECT_FALSE(cancelable.Cancel());
+ // Wake up main thread.
+ cond.Signal();
+ },
+ kLongDelay);
+ {
+ absl::MutexLock lock(&mutex);
+ cond.Wait(&mutex);
+ }
+ EXPECT_EQ(value, 1);
+}
+
+TEST(ScheduledExecutorTest,
+ CancelWhileRunning_TaskCompletesBeforeCancelReturns) {
+ CountDownLatch start_latch(1);
+ ScheduledExecutor executor;
+ std::atomic_int value = 0;
+ // A task that takes a little bit of time to complete
+ Cancelable cancelable = executor.Schedule(
+ [&start_latch, &value]() {
+ start_latch.CountDown();
+ absl::SleepFor(kLongDelay);
+ value += 1;
+ },
+ absl::ZeroDuration());
+
+ start_latch.Await();
+ cancelable.Cancel();
+
+ EXPECT_EQ(value, 1);
+}
+
+TEST(ScheduledExecutorTest,
+ CancelTwiceWhileRunning_TaskCompletesBeforeCancelReturns) {
+ CountDownLatch start_latch(1);
+ ScheduledExecutor executor;
+ std::atomic_int value = 0;
+ // A task that takes a little bit of time to complete
+ Cancelable cancelable = executor.Schedule(
+ [&start_latch, &value]() {
+ start_latch.CountDown();
+ absl::SleepFor(kLongDelay);
+ value += 1;
+ },
+ absl::ZeroDuration());
+
+ start_latch.Await();
+
+ cancelable.Cancel();
+ cancelable.Cancel();
+
+ EXPECT_EQ(value, 1);
+}
+
+struct ThreadCheckTestClass {
+ ScheduledExecutor executor;
+ int value ABSL_GUARDED_BY(executor) = 0;
+
+ void incValue() ABSL_EXCLUSIVE_LOCKS_REQUIRED(executor) { value++; }
+ int getValue() ABSL_EXCLUSIVE_LOCKS_REQUIRED(executor) { return value; }
+};
+
+TEST(ScheduledExecutorTest, ThreadCheck_Execute) {
+ ThreadCheckTestClass test_class;
+
+ test_class.executor.Execute(
+ [&test_class]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(test_class.executor) {
+ test_class.incValue();
+ });
+}
+
+TEST(ScheduledExecutorTest, ThreadCheck_Schedule) {
+ ThreadCheckTestClass test_class;
+
+ test_class.executor.Schedule(
+ [&test_class]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(test_class.executor) {
+ test_class.incValue();
+ },
+ absl::ZeroDuration());
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/settable_future.h b/chromium/third_party/nearby/src/internal/platform/settable_future.h
new file mode 100644
index 00000000000..1265559beba
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/settable_future.h
@@ -0,0 +1,128 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_SETTABLE_FUTURE_H_
+#define PLATFORM_PUBLIC_SETTABLE_FUTURE_H_
+
+#include <utility>
+
+#include "internal/platform/condition_variable.h"
+#include "internal/platform/mutex.h"
+#include "internal/platform/mutex_lock.h"
+#include "internal/platform/system_clock.h"
+
+namespace location {
+namespace nearby {
+
+template <typename T>
+class SettableFuture : public api::SettableFuture<T> {
+ public:
+ SettableFuture() = default;
+ ~SettableFuture() override = default;
+
+ bool Set(T value) override {
+ MutexLock lock(&mutex_);
+ if (!done_) {
+ value_ = std::move(value);
+ done_ = true;
+ exception_ = {Exception::kSuccess};
+ completed_.Notify();
+ InvokeAllLocked();
+ return true;
+ }
+ return false;
+ }
+
+ void AddListener(Runnable runnable, api::Executor* executor) override {
+ MutexLock lock(&mutex_);
+ if (done_) {
+ executor->Execute(std::move(runnable));
+ } else {
+ listeners_.emplace_back(std::make_pair(executor, std::move(runnable)));
+ }
+ }
+
+ bool IsSet() const {
+ MutexLock lock(&mutex_);
+ return done_;
+ }
+
+ bool SetException(Exception exception) override {
+ MutexLock lock(&mutex_);
+ return SetExceptionLocked(exception);
+ }
+
+ ExceptionOr<T> Get() override {
+ MutexLock lock(&mutex_);
+ while (!done_) {
+ completed_.Wait();
+ }
+ return exception_.value != Exception::kSuccess
+ ? ExceptionOr<T>{exception_.value}
+ : ExceptionOr<T>{value_};
+ }
+
+ ExceptionOr<T> Get(absl::Duration timeout) override {
+ MutexLock lock(&mutex_);
+ while (!done_) {
+ absl::Time start_time = SystemClock::ElapsedRealtime();
+ if (completed_.Wait(timeout).Raised(Exception::kInterrupted)) {
+ SetExceptionLocked({Exception::kInterrupted});
+ break;
+ }
+ absl::Duration spent = SystemClock::ElapsedRealtime() - start_time;
+ if (spent < timeout) {
+ timeout -= spent;
+ } else if (!done_) {
+ SetExceptionLocked({Exception::kTimeout});
+ break;
+ }
+ }
+ return exception_.value != Exception::kSuccess
+ ? ExceptionOr<T>{exception_.value}
+ : ExceptionOr<T>{value_};
+ }
+
+ private:
+ bool SetExceptionLocked(Exception exception) {
+ if (!done_) {
+ exception_ = exception.value != Exception::kSuccess
+ ? exception
+ : Exception{Exception::kFailed};
+ done_ = true;
+ completed_.Notify();
+ InvokeAllLocked();
+ }
+ return true;
+ }
+
+ void InvokeAllLocked() {
+ for (auto& item : listeners_) {
+ item.first->Execute(std::move(item.second));
+ }
+ listeners_.clear();
+ }
+
+ mutable Mutex mutex_;
+ ConditionVariable completed_{&mutex_};
+ std::vector<std::pair<api::Executor*, std::function<void()>>> listeners_;
+ bool done_{false};
+ T value_;
+ Exception exception_{Exception::kFailed};
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_SETTABLE_FUTURE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/single_thread_executor.h b/chromium/third_party/nearby/src/internal/platform/single_thread_executor.h
new file mode 100644
index 00000000000..cc8159893d5
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/single_thread_executor.h
@@ -0,0 +1,41 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_SINGLE_THREAD_EXECUTOR_H_
+#define PLATFORM_PUBLIC_SINGLE_THREAD_EXECUTOR_H_
+
+#include "absl/base/thread_annotations.h"
+#include "internal/platform/submittable_executor.h"
+
+namespace location {
+namespace nearby {
+
+// An Executor that uses a single worker thread operating off an unbounded
+// queue.
+//
+// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newSingleThreadExecutor--
+class ABSL_LOCKABLE SingleThreadExecutor final : public SubmittableExecutor {
+ public:
+ using Platform = api::ImplementationPlatform;
+ SingleThreadExecutor()
+ : SubmittableExecutor(Platform::CreateSingleThreadExecutor()) {}
+ ~SingleThreadExecutor() override = default;
+ SingleThreadExecutor(SingleThreadExecutor&&) = default;
+ SingleThreadExecutor& operator=(SingleThreadExecutor&&) = default;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_SINGLE_THREAD_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/single_thread_executor_test.cc b/chromium/third_party/nearby/src/internal/platform/single_thread_executor_test.cc
new file mode 100644
index 00000000000..653629360e4
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/single_thread_executor_test.cc
@@ -0,0 +1,139 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/single_thread_executor.h"
+
+#include <atomic>
+#include <functional>
+#include <string>
+
+#include "gtest/gtest.h"
+#include "absl/synchronization/mutex.h"
+#include "absl/time/clock.h"
+#include "internal/platform/exception.h"
+
+namespace location {
+namespace nearby {
+
+TEST(SingleThreadExecutorTest, ConsructorDestructorWorks) {
+ SingleThreadExecutor executor;
+}
+
+TEST(SingleThreadExecutorTest, CanExecute) {
+ absl::CondVar cond;
+ std::atomic_bool done = false;
+ SingleThreadExecutor executor;
+ executor.Execute([&done, &cond]() {
+ done = true;
+ cond.SignalAll();
+ });
+ absl::Mutex mutex;
+ {
+ absl::MutexLock lock(&mutex);
+ if (!done) {
+ cond.WaitWithTimeout(&mutex, absl::Seconds(1));
+ }
+ }
+ EXPECT_TRUE(done);
+}
+
+TEST(SingleThreadExecutorTest, CanExecuteNamedTask) {
+ absl::CondVar cond;
+ std::atomic_bool done = false;
+ SingleThreadExecutor executor;
+ executor.Execute("my task", [&done, &cond]() {
+ done = true;
+ cond.SignalAll();
+ });
+ absl::Mutex mutex;
+ {
+ absl::MutexLock lock(&mutex);
+ if (!done) {
+ cond.WaitWithTimeout(&mutex, absl::Seconds(1));
+ }
+ }
+ EXPECT_TRUE(done);
+}
+
+TEST(SingleThreadExecutorTest, JobsExecuteInOrder) {
+ std::vector<int> results;
+ SingleThreadExecutor executor;
+
+ for (int i = 0; i < 10; ++i) {
+ executor.Execute([i, &results]() { results.push_back(i); });
+ }
+
+ absl::CondVar cond;
+ std::atomic_bool done = false;
+ executor.Execute([&done, &cond]() {
+ done = true;
+ cond.SignalAll();
+ });
+ absl::Mutex mutex;
+ {
+ absl::MutexLock lock(&mutex);
+ if (!done) {
+ cond.WaitWithTimeout(&mutex, absl::Seconds(1));
+ }
+ }
+ EXPECT_TRUE(done);
+ EXPECT_EQ(results, (std::vector<int>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}));
+}
+
+TEST(SingleThreadExecutorTest, CanSubmit) {
+ SingleThreadExecutor executor;
+ Future<bool> future;
+ bool submitted =
+ executor.Submit<bool>([]() { return ExceptionOr<bool>{true}; }, &future);
+ EXPECT_TRUE(submitted);
+ EXPECT_TRUE(future.Get().result());
+}
+
+struct ThreadCheckTestClass {
+ SingleThreadExecutor executor;
+ int value ABSL_GUARDED_BY(executor) = 0;
+
+ void incValue() ABSL_EXCLUSIVE_LOCKS_REQUIRED(executor) { value++; }
+ int getValue() ABSL_EXCLUSIVE_LOCKS_REQUIRED(executor) { return value; }
+};
+
+TEST(SingleThreadExecutorTest, ThreadCheck_ExecuteRunnable) {
+ ThreadCheckTestClass test_class;
+
+ test_class.executor.Execute(
+ [&test_class]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(test_class.executor) {
+ test_class.incValue();
+ });
+}
+
+TEST(SingleThreadExecutorTest, ThreadCheck_SubmitCallable) {
+ ThreadCheckTestClass test_class;
+ test_class.executor.Execute(
+ [&test_class]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(test_class.executor) {
+ test_class.incValue();
+ });
+ Future<int> future;
+
+ bool submitted = test_class.executor.Submit<int>(
+ [&test_class]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(test_class.executor) {
+ return ExceptionOr<int>{test_class.getValue()};
+ },
+ &future);
+
+ EXPECT_TRUE(submitted);
+ EXPECT_EQ(future.Get().result(), 1);
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/socket.h b/chromium/third_party/nearby/src/internal/platform/socket.h
new file mode 100644
index 00000000000..1d746f690c0
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/socket.h
@@ -0,0 +1,39 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_BASE_SOCKET_H_
+#define PLATFORM_BASE_SOCKET_H_
+
+#include "internal/platform/input_stream.h"
+#include "internal/platform/output_stream.h"
+
+namespace location {
+namespace nearby {
+
+// A socket is an endpoint for communication between two machines.
+//
+// https://docs.oracle.com/javase/8/docs/api/java/net/Socket.html
+class Socket {
+ public:
+ virtual ~Socket() = default;
+
+ virtual InputStream& GetInputStream() = 0;
+ virtual OutputStream& GetOutputStream() = 0;
+ virtual void Close() = 0;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_BASE_SOCKET_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/submittable_executor.h b/chromium/third_party/nearby/src/internal/platform/submittable_executor.h
new file mode 100644
index 00000000000..12cbfd5bcab
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/submittable_executor.h
@@ -0,0 +1,130 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_SUBMITTABLE_EXECUTOR_H_
+#define PLATFORM_PUBLIC_SUBMITTABLE_EXECUTOR_H_
+
+#include <cstddef>
+#include <functional>
+#include <memory>
+#include <utility>
+
+#include "absl/base/thread_annotations.h"
+#include "internal/platform/implementation/executor.h"
+#include "internal/platform/implementation/submittable_executor.h"
+#include "internal/platform/callable.h"
+#include "internal/platform/runnable.h"
+#include "internal/platform/future.h"
+#include "internal/platform/lockable.h"
+#include "internal/platform/monitored_runnable.h"
+#include "internal/platform/mutex.h"
+#include "internal/platform/mutex_lock.h"
+#include "internal/platform/thread_check_callable.h"
+#include "internal/platform/thread_check_runnable.h"
+
+namespace location {
+namespace nearby {
+
+inline int GetCurrentTid() { return api::GetCurrentTid(); }
+
+// Main interface to be used by platform as a base class for
+// - MultiThreadExecutor
+// - SingleThreadExecutor
+class ABSL_LOCKABLE SubmittableExecutor : public api::SubmittableExecutor,
+ public Lockable {
+ public:
+ ~SubmittableExecutor() override {
+ MutexLock lock(&mutex_);
+ DoShutdown();
+ }
+ SubmittableExecutor(SubmittableExecutor&& other) { *this = std::move(other); }
+ SubmittableExecutor& operator=(SubmittableExecutor&& other)
+ ABSL_LOCKS_EXCLUDED(mutex_) {
+ MutexLock lock(&mutex_);
+ {
+ MutexLock other_lock(&other.mutex_);
+ impl_ = std::move(other.impl_);
+ }
+ return *this;
+ }
+ void Execute(const std::string& name, Runnable&& runnable)
+ ABSL_LOCKS_EXCLUDED(mutex_) {
+ MutexLock lock(&mutex_);
+ if (impl_)
+ impl_->Execute(MonitoredRunnable(
+ name, ThreadCheckRunnable(this, std::move(runnable))));
+ }
+
+ void Execute(Runnable&& runnable) ABSL_LOCKS_EXCLUDED(mutex_) override {
+ MutexLock lock(&mutex_);
+ if (impl_)
+ impl_->Execute(
+ MonitoredRunnable(ThreadCheckRunnable(this, std::move(runnable))));
+ }
+
+ void Shutdown() ABSL_LOCKS_EXCLUDED(mutex_) override {
+ MutexLock lock(&mutex_);
+ DoShutdown();
+ }
+
+ // Submits a callable for execution.
+ // When execution completes, return value is assigned to the passed future.
+ // Future must outlive the whole execution chain.
+ template <typename T>
+ bool Submit(Callable<T>&& callable, Future<T>* future)
+ ABSL_LOCKS_EXCLUDED(mutex_) {
+ MutexLock lock(&mutex_);
+ bool submitted =
+ DoSubmit([callable = ThreadCheckCallable<T>(this, std::move(callable)),
+ future]() {
+ ExceptionOr<T> result = callable();
+ if (result.ok()) {
+ future->Set(result.result());
+ } else {
+ future->SetException({result.exception()});
+ }
+ });
+ if (!submitted) {
+ // complete immediately with kExecution exception value.
+ future->SetException({Exception::kExecution});
+ }
+ return submitted;
+ }
+
+ protected:
+ explicit SubmittableExecutor(std::unique_ptr<api::SubmittableExecutor> impl)
+ : impl_(std::move(impl)) {}
+
+ private:
+ void DoShutdown() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_) {
+ if (impl_) {
+ impl_->Shutdown();
+ impl_.reset();
+ }
+ }
+ // Submit a callable (with no delay).
+ // Returns true, if callable was submitted, false otherwise.
+ // Callable is not submitted if shutdown is in progress.
+ bool DoSubmit(Runnable&& wrapped_callable)
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_) override {
+ return impl_ ? impl_->DoSubmit(std::move(wrapped_callable)) : false;
+ }
+ mutable Mutex mutex_;
+ std::unique_ptr<api::SubmittableExecutor> ABSL_GUARDED_BY(mutex_) impl_;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_SUBMITTABLE_EXECUTOR_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/system_clock.h b/chromium/third_party/nearby/src/internal/platform/system_clock.h
new file mode 100644
index 00000000000..7f6ae620912
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/system_clock.h
@@ -0,0 +1,20 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_SYSTEM_CLOCK_H_
+#define PLATFORM_PUBLIC_SYSTEM_CLOCK_H_
+
+#include "internal/platform/implementation/system_clock.h"
+
+#endif // PLATFORM_PUBLIC_SYSTEM_CLOCK_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/thread_check_callable.h b/chromium/third_party/nearby/src/internal/platform/thread_check_callable.h
new file mode 100644
index 00000000000..f9a4e003def
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/thread_check_callable.h
@@ -0,0 +1,46 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_THREAD_CHECK_CALLABLE_H_
+#define PLATFORM_PUBLIC_THREAD_CHECK_CALLABLE_H_
+
+#include "absl/base/thread_annotations.h"
+#include "internal/platform/callable.h"
+#include "internal/platform/lockable.h"
+
+namespace location {
+namespace nearby {
+
+// A callable that acquires a lockable resource while running.
+// This class helps with thread safety analysis.
+template <typename T>
+class ThreadCheckCallable {
+ public:
+ ThreadCheckCallable(const Lockable *lockable, Callable<T> &&callable)
+ : lockable_{lockable}, callable_{callable} {}
+
+ ExceptionOr<T> operator()() const {
+ ThreadLockHolder thread_lock(lockable_);
+ return callable_();
+ }
+
+ private:
+ Lockable const *lockable_;
+ Callable<T> callable_;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_THREAD_CHECK_CALLABLE_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/thread_check_nocompile.cc b/chromium/third_party/nearby/src/internal/platform/thread_check_nocompile.cc
new file mode 100644
index 00000000000..90bde99f9a5
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/thread_check_nocompile.cc
@@ -0,0 +1,83 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "absl/time/time.h"
+#include "internal/platform/scheduled_executor.h"
+#include "internal/platform/single_thread_executor.h"
+
+// Snippets of invalid code that should trigger an error during thread
+// safety analysis at compile time.
+// See https://g3doc.corp.google.com/googletest/g3doc/cpp_nc_test.md
+namespace location {
+namespace nearby {
+
+#ifdef TEST_EXECUTE_MISSING_METHOD_ANNOTATION
+struct ThreadCheckTestClass {
+ SingleThreadExecutor executor;
+ int value ABSL_GUARDED_BY(executor) = 0;
+
+ void incValue() { value++; }
+};
+
+void TestExecute_MissingMethodAnnotation() {
+ ThreadCheckTestClass test_class;
+
+ test_class.executor.Execute(
+ [&test_class]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(test_class.executor) {
+ test_class.incValue();
+ });
+}
+#endif // TEST_EXECUTE_MISSING_METHOD_ANNOTATION
+
+#ifdef TEST_SUBMIT_MISSING_METHOD_ANNOTATION
+struct ThreadCheckTestClass {
+ SingleThreadExecutor executor;
+ int value ABSL_GUARDED_BY(executor) = 0;
+
+ int getValue() { return value; }
+};
+
+void TestSubmit_MissingMethodAnnotation() {
+ ThreadCheckTestClass test_class;
+ Future<int> future;
+
+ test_class.executor.Submit<int>(
+ [&test_class]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(test_class.executor) {
+ return ExceptionOr<int>{test_class.getValue()};
+ },
+ &future);
+}
+#endif // TEST_SUBMIT_MISSING_METHOD_ANNOTATION
+
+#ifdef TEST_SCHEDULE_MISSING_METHOD_ANNOTATION
+struct ThreadCheckTestClass {
+ ScheduledExecutor executor;
+ int value ABSL_GUARDED_BY(executor) = 0;
+
+ void incValue() { value++; }
+};
+
+void TestSchedule_MissingMethodAnnotation() {
+ ThreadCheckTestClass test_class;
+
+ test_class.executor.Schedule(
+ [&test_class]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(test_class.executor) {
+ test_class.incValue();
+ },
+ absl::ZeroDuration());
+}
+#endif // TEST_SCHEDULE_MISSING_METHOD_ANNOTATION
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/thread_check_nocompile_test.py b/chromium/third_party/nearby/src/internal/platform/thread_check_nocompile_test.py
new file mode 100644
index 00000000000..8260404952e
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/thread_check_nocompile_test.py
@@ -0,0 +1,26 @@
+"""Negative tests for thread safety analysis in executors implementation."""
+
+from google3.testing.pybase import fake_target_util
+from google3.testing.pybase import googletest
+
+
+class ThreadCheckNocompileTest(googletest.TestCase):
+ """Negative tests for thread safety analysis in executors implementation."""
+
+ def testCompilerErrors(self):
+ """Runs a list of tests to verify that erroneous code leads to expected compiler messages."""
+ test_specs = [
+ ('EXECUTE_MISSING_METHOD_ANNOTATION', [r'-Wthread-safety-analysis']),
+ ('SUBMIT_MISSING_METHOD_ANNOTATION', [r'-Wthread-safety-analysis']),
+ ('SCHEDULE_MISSING_METHOD_ANNOTATION', [r'-Wthread-safety-analysis']),
+ # Tests that compiling a valid C++ succeeds.
+ ('SANITY', None) # None means that the compilation should succeed.
+ ]
+ fake_target_util.AssertCcCompilerErrors(
+ self,
+ 'internal/platform/thread_check_nocompile',
+ 'thread_check_nocompile.o', test_specs)
+
+
+if __name__ == '__main__':
+ googletest.main()
diff --git a/chromium/third_party/nearby/src/internal/platform/thread_check_runnable.h b/chromium/third_party/nearby/src/internal/platform/thread_check_runnable.h
new file mode 100644
index 00000000000..df40d98762b
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/thread_check_runnable.h
@@ -0,0 +1,47 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_THREAD_CHECK_RUNNABLE_H_
+#define PLATFORM_PUBLIC_THREAD_CHECK_RUNNABLE_H_
+
+#include <utility>
+
+#include "absl/base/thread_annotations.h"
+#include "internal/platform/runnable.h"
+#include "internal/platform/lockable.h"
+
+namespace location {
+namespace nearby {
+
+// A runnable that acquires a lockable resource while running.
+// This class helps with thread safety analysis.
+class ThreadCheckRunnable {
+ public:
+ ThreadCheckRunnable(const Lockable *lockable, Runnable &&runnable)
+ : lockable_{lockable}, runnable_{runnable} {}
+
+ void operator()() const {
+ ThreadLockHolder thread_lock(lockable_);
+ runnable_();
+ }
+
+ private:
+ Lockable const *lockable_;
+ Runnable runnable_;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_THREAD_CHECK_RUNNABLE_H_
diff --git a/chromium/third_party/nearby/src/cpp/platform/base/types.h b/chromium/third_party/nearby/src/internal/platform/types.h
index d082b262373..d082b262373 100644
--- a/chromium/third_party/nearby/src/cpp/platform/base/types.h
+++ b/chromium/third_party/nearby/src/internal/platform/types.h
diff --git a/chromium/third_party/nearby/src/internal/platform/webrtc.h b/chromium/third_party/nearby/src/internal/platform/webrtc.h
new file mode 100644
index 00000000000..8d5ef58ff58
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/webrtc.h
@@ -0,0 +1,99 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_WEBRTC_H_
+#define PLATFORM_PUBLIC_WEBRTC_H_
+
+#include <memory>
+
+#include "internal/platform/implementation/platform.h"
+#include "internal/platform/implementation/webrtc.h"
+#include "webrtc/api/peer_connection_interface.h"
+
+namespace location {
+namespace nearby {
+
+class WebRtcSignalingMessenger final {
+ public:
+ using OnSignalingMessageCallback =
+ api::WebRtcSignalingMessenger::OnSignalingMessageCallback;
+ using OnSignalingCompleteCallback =
+ api::WebRtcSignalingMessenger::OnSignalingCompleteCallback;
+
+ explicit WebRtcSignalingMessenger(
+ std::unique_ptr<api::WebRtcSignalingMessenger> messenger)
+ : impl_(std::move(messenger)) {}
+ ~WebRtcSignalingMessenger() = default;
+ WebRtcSignalingMessenger(WebRtcSignalingMessenger&&) = default;
+ WebRtcSignalingMessenger operator=(WebRtcSignalingMessenger&&) = delete;
+
+ bool SendMessage(absl::string_view peer_id, const ByteArray& message) {
+ return impl_->SendMessage(peer_id, message);
+ }
+
+ bool StartReceivingMessages(
+ OnSignalingMessageCallback on_message_callback,
+ OnSignalingCompleteCallback on_complete_callback) {
+ return impl_->StartReceivingMessages(on_message_callback,
+ on_complete_callback);
+ }
+
+ void StopReceivingMessages() { impl_->StopReceivingMessages(); }
+
+ bool IsValid() const { return impl_ != nullptr; }
+
+ private:
+ std::unique_ptr<api::WebRtcSignalingMessenger> impl_;
+};
+
+class WebRtcMedium final {
+ public:
+ using PeerConnectionCallback = api::WebRtcMedium::PeerConnectionCallback;
+
+ WebRtcMedium() : impl_(api::ImplementationPlatform::CreateWebRtcMedium()) {}
+ ~WebRtcMedium() = default;
+ WebRtcMedium(WebRtcMedium&&) = delete;
+ WebRtcMedium& operator=(WebRtcMedium&&) = delete;
+
+ // Gets the default two-letter country code associated with current locale.
+ // For example, en_US locale resolves to "US".
+ const std::string GetDefaultCountryCode() {
+ return impl_->GetDefaultCountryCode();
+ }
+
+ // Creates and returns a new webrtc::PeerConnectionInterface object via
+ // |callback|.
+ void CreatePeerConnection(webrtc::PeerConnectionObserver* observer,
+ PeerConnectionCallback callback) {
+ impl_->CreatePeerConnection(observer, std::move(callback));
+ }
+
+ // Returns a signaling messenger for sending WebRTC signaling messages.
+ std::unique_ptr<WebRtcSignalingMessenger> GetSignalingMessenger(
+ absl::string_view self_id,
+ const connections::LocationHint& location_hint) {
+ return std::make_unique<WebRtcSignalingMessenger>(
+ impl_->GetSignalingMessenger(self_id, location_hint));
+ }
+
+ bool IsValid() const { return impl_ != nullptr; }
+
+ private:
+ std::unique_ptr<api::WebRtcMedium> impl_;
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_WEBRTC_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/wifi_lan.cc b/chromium/third_party/nearby/src/internal/platform/wifi_lan.cc
new file mode 100644
index 00000000000..481509f2ec4
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/wifi_lan.cc
@@ -0,0 +1,146 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/wifi_lan.h"
+
+#include "internal/platform/mutex_lock.h"
+
+namespace location {
+namespace nearby {
+
+bool WifiLanMedium::StartAdvertising(const NsdServiceInfo& nsd_service_info) {
+ return impl_->StartAdvertising(nsd_service_info);
+}
+
+bool WifiLanMedium::StopAdvertising(const NsdServiceInfo& nsd_service_info) {
+ return impl_->StopAdvertising(nsd_service_info);
+}
+
+bool WifiLanMedium::StartDiscovery(const std::string& service_id,
+ const std::string& service_type,
+ DiscoveredServiceCallback callback) {
+ {
+ MutexLock lock(&mutex_);
+ if (discovery_callbacks_.contains(service_type)) {
+ NEARBY_LOGS(INFO) << "WifiLan Discovery already start with service_type="
+ << service_type << "; impl=" << &GetImpl();
+ return false;
+ }
+ }
+ api::WifiLanMedium::DiscoveredServiceCallback api_callback = {
+ .service_discovered_cb =
+ [this](NsdServiceInfo service_info) {
+ MutexLock lock(&mutex_);
+ std::string service_type = service_info.GetServiceType();
+ auto pair = discovery_services_.insert(service_type);
+ if (!pair.second) {
+ NEARBY_LOGS(INFO)
+ << "Discovering (again) service_info=" << &service_info
+ << ", service_type=" << service_type
+ << ", service_name=" << service_info.GetServiceName();
+ return;
+ }
+ NEARBY_LOGS(INFO)
+ << "Adding service_info=" << &service_info
+ << ", service_type=" << service_type
+ << ", service_name=" << service_info.GetServiceName();
+ // Callback service found.
+ const auto& it = discovery_callbacks_.find(service_type);
+ if (it != discovery_callbacks_.end()) {
+ std::string service_id = it->second->service_id;
+ DiscoveredServiceCallback medium_callback =
+ it->second->medium_callback;
+ medium_callback.service_discovered_cb(service_info, service_id);
+ } else {
+ NEARBY_LOGS(ERROR)
+ << "There is no callback found for service_type="
+ << service_type;
+ }
+ },
+ .service_lost_cb =
+ [this](NsdServiceInfo service_info) {
+ MutexLock lock(&mutex_);
+ std::string service_type = service_info.GetServiceType();
+ auto item = discovery_services_.extract(service_type);
+ if (item.empty()) return;
+ NEARBY_LOGS(INFO)
+ << "Removing service_info=" << &service_info
+ << ", service_type=" << service_type
+ << ", service_info_name=" << service_info.GetServiceName();
+ // Callback service lost.
+ const auto& it = discovery_callbacks_.find(service_type);
+ if (it != discovery_callbacks_.end()) {
+ std::string service_id = it->second->service_id;
+ DiscoveredServiceCallback medium_callback =
+ it->second->medium_callback;
+ medium_callback.service_lost_cb(service_info, service_id);
+ }
+ },
+ };
+ {
+ // Insert callback to the map first no matter it succeeds or not.
+ MutexLock lock(&mutex_);
+ auto pair = discovery_callbacks_.insert(
+ {service_type, absl::make_unique<DiscoveryCallbackInfo>()});
+ auto& context = *pair.first->second;
+ context.medium_callback = std::move(callback);
+ context.service_id = service_id;
+ }
+
+ bool success = impl_->StartDiscovery(service_type, std::move(api_callback));
+ if (!success) {
+ // If failed, then revert back the insertion.
+ MutexLock lock(&mutex_);
+ discovery_callbacks_.erase(service_type);
+ }
+ NEARBY_LOGS(INFO) << "WifiLan Discovery started for service_type="
+ << service_type << ", impl=" << &GetImpl()
+ << ", success=" << success;
+ return success;
+}
+
+bool WifiLanMedium::StopDiscovery(const std::string& service_type) {
+ MutexLock lock(&mutex_);
+ if (!discovery_callbacks_.contains(service_type)) {
+ return false;
+ }
+ discovery_callbacks_.erase(service_type);
+ if (discovery_services_.contains(service_type)) {
+ discovery_services_.erase(service_type);
+ }
+ NEARBY_LOGS(INFO) << "WifiLan Discovery disabled for service_type="
+ << service_type << ", impl=" << &GetImpl();
+ return impl_->StopDiscovery(service_type);
+}
+
+WifiLanSocket WifiLanMedium::ConnectToService(
+ const NsdServiceInfo& remote_service_info,
+ CancellationFlag* cancellation_flag) {
+ NEARBY_LOGS(INFO) << "WifiLanMedium::ConnectToService: remote_service_name="
+ << remote_service_info.GetServiceName();
+ return WifiLanSocket(
+ impl_->ConnectToService(remote_service_info, cancellation_flag));
+}
+
+WifiLanSocket WifiLanMedium::ConnectToService(
+ const std::string& ip_address, int port,
+ CancellationFlag* cancellation_flag) {
+ NEARBY_LOGS(INFO) << "WifiLanMedium::ConnectToService: ip address="
+ << ip_address << ", port=" << port;
+ return WifiLanSocket(
+ impl_->ConnectToService(ip_address, port, cancellation_flag));
+}
+
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/platform/wifi_lan.h b/chromium/third_party/nearby/src/internal/platform/wifi_lan.h
new file mode 100644
index 00000000000..4ec61ae5539
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/wifi_lan.h
@@ -0,0 +1,210 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef PLATFORM_PUBLIC_WIFI_LAN_H_
+#define PLATFORM_PUBLIC_WIFI_LAN_H_
+
+#include "absl/container/flat_hash_map.h"
+#include "internal/platform/implementation/platform.h"
+#include "internal/platform/implementation/wifi_lan.h"
+#include "internal/platform/byte_array.h"
+#include "internal/platform/cancellation_flag.h"
+#include "internal/platform/input_stream.h"
+#include "internal/platform/nsd_service_info.h"
+#include "internal/platform/output_stream.h"
+#include "internal/platform/logging.h"
+#include "internal/platform/mutex.h"
+
+namespace location {
+namespace nearby {
+
+class WifiLanSocket final {
+ public:
+ WifiLanSocket() = default;
+ WifiLanSocket(const WifiLanSocket&) = default;
+ WifiLanSocket& operator=(const WifiLanSocket&) = default;
+ ~WifiLanSocket() = default;
+ explicit WifiLanSocket(std::unique_ptr<api::WifiLanSocket> socket)
+ : impl_(std::move(socket)) {}
+
+ // Returns the InputStream of the WifiLanSocket.
+ // On error, returned stream will report Exception::kIo on any operation.
+ //
+ // The returned object is not owned by the caller, and can be invalidated once
+ // the WifiLanSocket object is destroyed.
+ InputStream& GetInputStream() { return impl_->GetInputStream(); }
+
+ // Returns the OutputStream of the WifiLanSocket.
+ // On error, returned stream will report Exception::kIo on any operation.
+ //
+ // The returned object is not owned by the caller, and can be invalidated once
+ // the WifiLanSocket object is destroyed.
+ OutputStream& GetOutputStream() { return impl_->GetOutputStream(); }
+
+ // Returns Exception::kIo on error, Exception::kSuccess otherwise.
+ Exception Close() { return impl_->Close(); }
+
+ // Returns true if a socket is usable. If this method returns false,
+ // it is not safe to call any other method.
+ // NOTE(socket validity):
+ // Socket created by a default public constructor is not valid, because
+ // it is missing platform implementation.
+ // The only way to obtain a valid socket is through connection, such as
+ // an object returned by WifiLanMedium::Connect
+ // These methods may also return an invalid socket if connection failed for
+ // any reason.
+ bool IsValid() const { return impl_ != nullptr; }
+
+ // Returns reference to platform implementation.
+ // This is used to communicate with platform code, and for debugging purposes.
+ // Returned reference will remain valid for while WifiLanSocket object is
+ // itself valid. Typically WifiLanSocket lifetime matches duration of the
+ // connection, and is controlled by end user, since they hold the instance.
+ api::WifiLanSocket& GetImpl() { return *impl_; }
+
+ private:
+ std::shared_ptr<api::WifiLanSocket> impl_;
+};
+
+class WifiLanServerSocket final {
+ public:
+ WifiLanServerSocket() = default;
+ WifiLanServerSocket(const WifiLanServerSocket&) = default;
+ WifiLanServerSocket& operator=(const WifiLanServerSocket&) = default;
+ ~WifiLanServerSocket() = default;
+ explicit WifiLanServerSocket(std::unique_ptr<api::WifiLanServerSocket> socket)
+ : impl_(std::move(socket)) {}
+
+ // Returns ip address.
+ std::string GetIPAddress() { return impl_->GetIPAddress(); }
+
+ // Returns port.
+ int GetPort() { return impl_->GetPort(); }
+
+ // Blocks until either:
+ // - at least one incoming connection request is available, or
+ // - ServerSocket is closed.
+ // On success, returns connected socket, ready to exchange data.
+ // Returns nullptr on error.
+ // Once error is reported, it is permanent, and ServerSocket has to be closed.
+ WifiLanSocket Accept() {
+ std::unique_ptr<api::WifiLanSocket> socket = impl_->Accept();
+ if (!socket) {
+ NEARBY_LOGS(INFO)
+ << "WifiLanServerSocket Accept() failed on server socket: " << this;
+ }
+ return WifiLanSocket(std::move(socket));
+ }
+
+ // Returns Exception::kIo on error, Exception::kSuccess otherwise.
+ Exception Close() {
+ NEARBY_LOGS(INFO) << "WifiLanServerSocket Closing:: " << this;
+ return impl_->Close();
+ }
+
+ bool IsValid() const { return impl_ != nullptr; }
+ api::WifiLanServerSocket& GetImpl() { return *impl_; }
+
+ private:
+ std::shared_ptr<api::WifiLanServerSocket> impl_;
+};
+
+// Container of operations that can be performed over the WifiLan medium.
+class WifiLanMedium {
+ public:
+ using Platform = api::ImplementationPlatform;
+
+ struct DiscoveredServiceCallback {
+ std::function<void(NsdServiceInfo service_info,
+ const std::string& service_type)>
+ service_discovered_cb =
+ DefaultCallback<NsdServiceInfo, const std::string&>();
+ std::function<void(NsdServiceInfo service_info,
+ const std::string& service_type)>
+ service_lost_cb = DefaultCallback<NsdServiceInfo, const std::string&>();
+ };
+
+ struct DiscoveryCallbackInfo {
+ std::string service_id;
+ DiscoveredServiceCallback medium_callback;
+ };
+
+ WifiLanMedium() : impl_(Platform::CreateWifiLanMedium()) {}
+ ~WifiLanMedium() = default;
+
+ // Starts WifiLan advertising.
+ //
+ // nsd_service_info - NsdServiceInfo data that's advertised through mDNS
+ // service.
+ // On success if the service is now advertising.
+ // On error if the service cannot start to advertise or the nsd_type in
+ // NsdServiceInfo has been passed previously which StopAdvertising is not
+ // been called.
+ bool StartAdvertising(const NsdServiceInfo& nsd_service_info);
+
+ // Stops WifiLan advertising.
+ //
+ // nsd_service_info - NsdServiceInfo data that's advertised through mDNS
+ // service.
+ // On success if the service stops advertising.
+ // On error if the service cannot stop advertising or the nsd_type in
+ // NsdServiceInfo cannot be found.
+ bool StopAdvertising(const NsdServiceInfo& nsd_service_info);
+
+ // Returns true once the WifiLan discovery has been initiated.
+ bool StartDiscovery(const std::string& service_id,
+ const std::string& service_type,
+ DiscoveredServiceCallback callback);
+
+ // Returns true once service_type is associated to existing callback. If the
+ // callback is the last found then WifiLan discovery will be stopped.
+ bool StopDiscovery(const std::string& service_type);
+
+ // Returns a new WifiLanSocket.
+ // On Success, WifiLanSocket::IsValid() returns true.
+ WifiLanSocket ConnectToService(const NsdServiceInfo& remote_service_info,
+ CancellationFlag* cancellation_flag);
+
+ // Returns a new WifiLanSocket by ip address and port.
+ // On Success, WifiLanSocket::IsValid()returns true.
+ WifiLanSocket ConnectToService(const std::string& ip_address, int port,
+ CancellationFlag* cancellation_flag);
+
+ // Returns a new WifiLanServerSocket.
+ // On Success, WifiLanServerSocket::IsValid() returns true.
+ WifiLanServerSocket ListenForService(int port = 0) {
+ return WifiLanServerSocket(impl_->ListenForService(port));
+ }
+
+ // Returns the port range as a pair of min and max port.
+ absl::optional<std::pair<std::int32_t, std::int32_t>> GetDynamicPortRange() {
+ return impl_->GetDynamicPortRange();
+ }
+
+ bool IsValid() const { return impl_ != nullptr; }
+
+ api::WifiLanMedium& GetImpl() { return *impl_; }
+
+ private:
+ Mutex mutex_;
+ std::unique_ptr<api::WifiLanMedium> impl_;
+ absl::flat_hash_map<std::string, std::unique_ptr<DiscoveryCallbackInfo>>
+ discovery_callbacks_ ABSL_GUARDED_BY(mutex_);
+ absl::flat_hash_set<std::string> discovery_services_ ABSL_GUARDED_BY(mutex_);
+};
+
+} // namespace nearby
+} // namespace location
+
+#endif // PLATFORM_PUBLIC_WIFI_LAN_H_
diff --git a/chromium/third_party/nearby/src/internal/platform/wifi_lan_test.cc b/chromium/third_party/nearby/src/internal/platform/wifi_lan_test.cc
new file mode 100644
index 00000000000..f96cf15eec4
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/platform/wifi_lan_test.cc
@@ -0,0 +1,391 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "internal/platform/wifi_lan.h"
+
+#include <memory>
+
+#include "gmock/gmock.h"
+#include "protobuf-matchers/protocol-buffer-matchers.h"
+#include "gtest/gtest.h"
+#include "absl/strings/string_view.h"
+#include "internal/platform/medium_environment.h"
+#include "internal/platform/count_down_latch.h"
+#include "internal/platform/logging.h"
+
+namespace location {
+namespace nearby {
+namespace {
+
+using FeatureFlags = FeatureFlags::Flags;
+
+constexpr FeatureFlags kTestCases[] = {
+ FeatureFlags{
+ .enable_cancellation_flag = true,
+ },
+ FeatureFlags{
+ .enable_cancellation_flag = false,
+ },
+};
+
+constexpr absl::Duration kWaitDuration = absl::Milliseconds(1000);
+constexpr absl::string_view kServiceId{"service_id"};
+constexpr absl::string_view kServiceType{"_service.tcp_"};
+constexpr absl::string_view kServiceInfoName{"Simulated service info name"};
+constexpr absl::string_view kEndpointName{"Simulated endpoint name"};
+constexpr absl::string_view kEndpointInfoKey{"n"};
+
+class WifiLanMediumTest : public ::testing::TestWithParam<FeatureFlags> {
+ protected:
+ using DiscoveredServiceCallback = WifiLanMedium::DiscoveredServiceCallback;
+
+ WifiLanMediumTest() { env_.Stop(); }
+
+ MediumEnvironment& env_{MediumEnvironment::Instance()};
+};
+
+TEST_P(WifiLanMediumTest, CanConnectToService) {
+ FeatureFlags feature_flags = GetParam();
+ env_.SetFeatureFlags(feature_flags);
+ env_.Start();
+ WifiLanMedium wifi_lan_a;
+ WifiLanMedium wifi_lan_b;
+ std::string service_id(kServiceId);
+ std::string service_type(kServiceType);
+ std::string service_info_name(kServiceInfoName);
+ std::string endpoint_info_name(kEndpointName);
+ CountDownLatch discovered_latch(1);
+ CountDownLatch lost_latch(1);
+
+ WifiLanServerSocket server_socket = wifi_lan_b.ListenForService();
+ EXPECT_TRUE(server_socket.IsValid());
+
+ NsdServiceInfo nsd_service_info;
+ nsd_service_info.SetServiceName(service_info_name);
+ nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
+ endpoint_info_name);
+ nsd_service_info.SetServiceType(service_type);
+ nsd_service_info.SetIPAddress(server_socket.GetIPAddress());
+ nsd_service_info.SetPort(server_socket.GetPort());
+ wifi_lan_b.StartAdvertising(nsd_service_info);
+
+ NsdServiceInfo discovered_service_info;
+ wifi_lan_a.StartDiscovery(
+ service_id, service_type,
+ DiscoveredServiceCallback{
+ .service_discovered_cb =
+ [&discovered_latch, &discovered_service_info](
+ NsdServiceInfo service_info,
+ const std::string& service_type) {
+ discovered_service_info = service_info;
+ discovered_latch.CountDown();
+ },
+ .service_lost_cb =
+ [&lost_latch](NsdServiceInfo service_info,
+ const std::string& service_type) {
+ lost_latch.CountDown();
+ },
+ });
+ EXPECT_TRUE(discovered_latch.Await(absl::Milliseconds(1000)).result());
+ WifiLanSocket socket_a;
+ WifiLanSocket socket_b;
+ EXPECT_FALSE(socket_a.IsValid());
+ EXPECT_FALSE(socket_b.IsValid());
+ {
+ CancellationFlag flag;
+ SingleThreadExecutor server_executor;
+ SingleThreadExecutor client_executor;
+ client_executor.Execute([&wifi_lan_a, &socket_a,
+ discovered_service_info = discovered_service_info,
+ service_type, &server_socket, &flag]() {
+ socket_a = wifi_lan_a.ConnectToService(discovered_service_info, &flag);
+ if (!socket_a.IsValid()) {
+ server_socket.Close();
+ }
+ });
+ server_executor.Execute([&socket_b, &server_socket]() {
+ socket_b = server_socket.Accept();
+ if (!socket_b.IsValid()) {
+ server_socket.Close();
+ }
+ });
+ }
+ EXPECT_TRUE(socket_a.IsValid());
+ EXPECT_TRUE(socket_b.IsValid());
+ server_socket.Close();
+ env_.Stop();
+}
+
+TEST_P(WifiLanMediumTest, CanCancelConnect) {
+ FeatureFlags feature_flags = GetParam();
+ env_.SetFeatureFlags(feature_flags);
+ env_.Start();
+ WifiLanMedium wifi_lan_a;
+ WifiLanMedium wifi_lan_b;
+ std::string service_id(kServiceId);
+ std::string service_type(kServiceType);
+ std::string service_info_name(kServiceInfoName);
+ std::string endpoint_info_name(kEndpointName);
+ CountDownLatch discovered_latch(1);
+ CountDownLatch lost_latch(1);
+
+ WifiLanServerSocket server_socket = wifi_lan_b.ListenForService();
+ EXPECT_TRUE(server_socket.IsValid());
+
+ NsdServiceInfo nsd_service_info;
+ nsd_service_info.SetServiceName(service_info_name);
+ nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
+ endpoint_info_name);
+ nsd_service_info.SetServiceType(service_type);
+ nsd_service_info.SetIPAddress(server_socket.GetIPAddress());
+ nsd_service_info.SetPort(server_socket.GetPort());
+ wifi_lan_b.StartAdvertising(nsd_service_info);
+
+ NsdServiceInfo discovered_service_info;
+ wifi_lan_a.StartDiscovery(
+ service_id, service_type,
+ DiscoveredServiceCallback{
+ .service_discovered_cb =
+ [&discovered_latch, &discovered_service_info](
+ NsdServiceInfo service_info,
+ const std::string& service_type) {
+ discovered_service_info = service_info;
+ discovered_latch.CountDown();
+ },
+ .service_lost_cb =
+ [&lost_latch](NsdServiceInfo service_info,
+ const std::string& service_type) {
+ lost_latch.CountDown();
+ },
+ });
+ EXPECT_TRUE(discovered_latch.Await(absl::Milliseconds(1000)).result());
+ WifiLanSocket socket_a;
+ WifiLanSocket socket_b;
+ EXPECT_FALSE(socket_a.IsValid());
+ EXPECT_FALSE(socket_b.IsValid());
+ {
+ CancellationFlag flag(true);
+ SingleThreadExecutor server_executor;
+ SingleThreadExecutor client_executor;
+ client_executor.Execute([&wifi_lan_a, &socket_a,
+ discovered_service_info = discovered_service_info,
+ service_type, &server_socket, &flag]() {
+ socket_a = wifi_lan_a.ConnectToService(discovered_service_info, &flag);
+ if (!socket_a.IsValid()) {
+ server_socket.Close();
+ }
+ });
+ server_executor.Execute([&socket_b, &server_socket]() {
+ socket_b = server_socket.Accept();
+ if (!socket_b.IsValid()) {
+ server_socket.Close();
+ }
+ });
+ }
+ // If FeatureFlag is disabled, Cancelled is false as no-op.
+ if (!feature_flags.enable_cancellation_flag) {
+ EXPECT_TRUE(socket_a.IsValid());
+ EXPECT_TRUE(socket_b.IsValid());
+ } else {
+ EXPECT_FALSE(socket_a.IsValid());
+ EXPECT_FALSE(socket_b.IsValid());
+ }
+ server_socket.Close();
+ env_.Stop();
+}
+
+INSTANTIATE_TEST_SUITE_P(ParametrisedWifiLanMediumTest, WifiLanMediumTest,
+ ::testing::ValuesIn(kTestCases));
+
+TEST_F(WifiLanMediumTest, ConstructorDestructorWorks) {
+ env_.Start();
+ WifiLanMedium wifi_lan_a;
+ WifiLanMedium wifi_lan_b;
+
+ // Make sure we can create functional mediums.
+ ASSERT_TRUE(wifi_lan_a.IsValid());
+ ASSERT_TRUE(wifi_lan_b.IsValid());
+
+ // Make sure we can create 2 distinct mediums.
+ EXPECT_NE(&wifi_lan_a.GetImpl(), &wifi_lan_b.GetImpl());
+ env_.Stop();
+}
+
+TEST_F(WifiLanMediumTest, CanStartAdvertising) {
+ env_.Start();
+ WifiLanMedium wifi_lan_a;
+ std::string service_type(kServiceType);
+ std::string service_info_name(kServiceInfoName);
+ std::string endpoint_info_name(kEndpointName);
+
+ WifiLanServerSocket server_socket = wifi_lan_a.ListenForService();
+ EXPECT_TRUE(server_socket.IsValid());
+
+ NsdServiceInfo nsd_service_info;
+ nsd_service_info.SetServiceName(service_info_name);
+ nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
+ endpoint_info_name);
+ nsd_service_info.SetServiceType(service_type);
+ EXPECT_TRUE(wifi_lan_a.StartAdvertising(nsd_service_info));
+ EXPECT_TRUE(wifi_lan_a.StopAdvertising(nsd_service_info));
+ env_.Stop();
+}
+
+TEST_F(WifiLanMediumTest, CanStartMultipleAdvertising) {
+ env_.Start();
+ WifiLanMedium wifi_lan_a;
+ std::string service_type_1(kServiceType);
+ std::string service_type_2("_service_1.tcp_");
+ std::string service_info_name_1(kServiceInfoName);
+ std::string service_info_name_2(kServiceInfoName);
+ std::string endpoint_info_name(kEndpointName);
+
+ WifiLanServerSocket server_socket = wifi_lan_a.ListenForService();
+ EXPECT_TRUE(server_socket.IsValid());
+
+ NsdServiceInfo nsd_service_info_1;
+ nsd_service_info_1.SetServiceName(service_info_name_1);
+ nsd_service_info_1.SetTxtRecord(std::string(kEndpointInfoKey),
+ endpoint_info_name);
+ nsd_service_info_1.SetServiceType(service_type_1);
+
+ NsdServiceInfo nsd_service_info_2;
+ nsd_service_info_2.SetServiceName(service_info_name_2);
+ nsd_service_info_2.SetTxtRecord(std::string(kEndpointInfoKey),
+ endpoint_info_name);
+ nsd_service_info_2.SetServiceType(service_type_2);
+
+ EXPECT_TRUE(wifi_lan_a.StartAdvertising(nsd_service_info_1));
+ EXPECT_TRUE(wifi_lan_a.StartAdvertising(nsd_service_info_2));
+ EXPECT_TRUE(wifi_lan_a.StopAdvertising(nsd_service_info_1));
+ EXPECT_TRUE(wifi_lan_a.StopAdvertising(nsd_service_info_2));
+ env_.Stop();
+}
+
+TEST_F(WifiLanMediumTest, CanStartDiscovery) {
+ env_.Start();
+ WifiLanMedium wifi_lan_a;
+ std::string service_id(kServiceId);
+ std::string service_type(kServiceType);
+
+ EXPECT_TRUE(wifi_lan_a.StartDiscovery(service_id, service_type,
+ DiscoveredServiceCallback{}));
+ EXPECT_TRUE(wifi_lan_a.StopDiscovery(service_type));
+ env_.Stop();
+}
+
+TEST_F(WifiLanMediumTest, CanStartMultipleDiscovery) {
+ env_.Start();
+ WifiLanMedium wifi_lan_a;
+ std::string service_id_1(kServiceId);
+ std::string service_id_2("service_id_2");
+ std::string service_type_1(kServiceType);
+ std::string service_type_2("_service_1.tcp_");
+
+ EXPECT_TRUE(wifi_lan_a.StartDiscovery(service_id_1, service_type_1,
+ DiscoveredServiceCallback{}));
+ EXPECT_TRUE(wifi_lan_a.StartDiscovery(service_id_2, service_type_2,
+ DiscoveredServiceCallback{}));
+ EXPECT_TRUE(wifi_lan_a.StopDiscovery(service_type_1));
+ EXPECT_TRUE(wifi_lan_a.StopDiscovery(service_type_2));
+ env_.Stop();
+}
+
+TEST_F(WifiLanMediumTest, CanAdvertiseThatOtherMediumDiscover) {
+ env_.Start();
+ WifiLanMedium wifi_lan_a;
+ WifiLanMedium wifi_lan_b;
+ std::string service_id(kServiceId);
+ std::string service_type(kServiceType);
+ std::string service_info_name(kServiceInfoName);
+ std::string endpoint_info_name(kEndpointName);
+ CountDownLatch discovered_latch(1);
+ CountDownLatch lost_latch(1);
+
+ wifi_lan_b.StartDiscovery(
+ service_id, service_type,
+ DiscoveredServiceCallback{
+ .service_discovered_cb =
+ [&discovered_latch](NsdServiceInfo service_info,
+ const std::string& service_type) {
+ discovered_latch.CountDown();
+ },
+ .service_lost_cb =
+ [&lost_latch](NsdServiceInfo service_info,
+ const std::string& service_id) {
+ lost_latch.CountDown();
+ },
+ });
+
+ WifiLanServerSocket server_socket = wifi_lan_a.ListenForService();
+ EXPECT_TRUE(server_socket.IsValid());
+
+ NsdServiceInfo nsd_service_info;
+ nsd_service_info.SetServiceName(service_info_name);
+ nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
+ endpoint_info_name);
+ nsd_service_info.SetServiceType(service_type);
+ EXPECT_TRUE(wifi_lan_a.StartAdvertising(nsd_service_info));
+ EXPECT_TRUE(discovered_latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(wifi_lan_a.StopAdvertising(nsd_service_info));
+ EXPECT_TRUE(lost_latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(wifi_lan_b.StopDiscovery(service_type));
+ env_.Stop();
+}
+
+TEST_F(WifiLanMediumTest, CanDiscoverThatOtherMediumAdvertise) {
+ env_.Start();
+ WifiLanMedium wifi_lan_a;
+ WifiLanMedium wifi_lan_b;
+ std::string service_id(kServiceId);
+ std::string service_type(kServiceType);
+ std::string service_info_name(kServiceInfoName);
+ std::string endpoint_info_name(kEndpointName);
+ CountDownLatch discovered_latch(1);
+ CountDownLatch lost_latch(1);
+
+ wifi_lan_a.StartDiscovery(
+ service_id, service_type,
+ DiscoveredServiceCallback{
+ .service_discovered_cb =
+ [&discovered_latch](NsdServiceInfo service_info,
+ const std::string& service_type) {
+ discovered_latch.CountDown();
+ },
+ .service_lost_cb =
+ [&lost_latch](NsdServiceInfo service_info,
+ const std::string& service_type) {
+ lost_latch.CountDown();
+ },
+ });
+
+ WifiLanServerSocket server_socket = wifi_lan_a.ListenForService();
+ EXPECT_TRUE(server_socket.IsValid());
+
+ NsdServiceInfo nsd_service_info;
+ nsd_service_info.SetServiceName(service_info_name);
+ nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
+ endpoint_info_name);
+ nsd_service_info.SetServiceType(service_type);
+ EXPECT_TRUE(wifi_lan_b.StartAdvertising(nsd_service_info));
+ EXPECT_TRUE(discovered_latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(wifi_lan_b.StopAdvertising(nsd_service_info));
+ EXPECT_TRUE(lost_latch.Await(kWaitDuration).result());
+ EXPECT_TRUE(wifi_lan_a.StopDiscovery(service_type));
+ env_.Stop();
+}
+
+} // namespace
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/internal/proto/analytics/BUILD b/chromium/third_party/nearby/src/internal/proto/analytics/BUILD
new file mode 100644
index 00000000000..17d5cb14255
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/proto/analytics/BUILD
@@ -0,0 +1,62 @@
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+load("//tools/build_defs/proto/cpp:cc_proto_library.bzl", "cc_proto_library")
+
+licenses(["notice"])
+
+package(default_visibility = ["//visibility:public"])
+
+proto_library(
+ name = "connections_log_proto",
+ srcs = [
+ "connections_log.proto",
+ ],
+ deps = [
+ "//proto:connections_enums_proto",
+ "//proto/errorcode:error_code_enums_proto",
+ ],
+)
+
+cc_proto_library(
+ name = "connections_log_cc_proto",
+ visibility = [
+ "//connections:__subpackages__",
+ "//internal/analytics:__subpackages__",
+ ],
+ deps = [":connections_log_proto"],
+)
+
+java_lite_proto_library(
+ name = "connections_log_java_proto_lite",
+ deps = [":connections_log_proto"],
+)
+
+cc_test(
+ name = "proto_analytics_test",
+ size = "small",
+ srcs = [
+ "connections_log_test.cc",
+ ],
+ shard_count = 16,
+ deps = [
+ ":connections_log_cc_proto",
+ "//internal/platform:logging",
+ "//internal/platform/implementation/g3", # build_cleaner: keep
+ "//proto:connections_enums_cc_proto",
+ "@com_github_protobuf_matchers//protobuf-matchers",
+ "@com_google_googletest//:gtest_main",
+ "@com_google_protobuf//:protobuf",
+ ],
+)
diff --git a/chromium/third_party/nearby/src/internal/proto/analytics/connections_log.proto b/chromium/third_party/nearby/src/internal/proto/analytics/connections_log.proto
new file mode 100644
index 00000000000..e2d48921fcd
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/proto/analytics/connections_log.proto
@@ -0,0 +1,445 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+syntax = "proto2";
+
+package location.nearby.analytics.proto;
+
+
+import "proto/connections_enums.proto";
+import "proto/errorcode/error_code_enums.proto";
+
+option optimize_for = LITE_RUNTIME;
+option java_package = "com.google.location.nearby.analytics.proto";
+option java_outer_classname = "ConnectionsLogProto";
+option objc_class_prefix = "GNCP";
+
+// Top-level log proto for Nearby Connections.
+// LINT.IfChange(ConnectionsLog)
+message ConnectionsLog {
+ // The type of this log.
+ optional location.nearby.proto.connections.EventType event_type = 1;
+
+ // Non-null for EventType.CLIENT_SESSION.
+ // Encapsulates all client activity between connecting to and disconnecting
+ // from the Nearby Connections API via Client.
+ optional ClientSession client_session = 2;
+
+ // The version of Nearby Connections. E.g. "v1.0.4".
+ optional string version = 3 ;
+
+ // For EventType.ERROR_CODE
+ optional ErrorCode error_code = 4;
+
+ // Indicates the source of the log.
+ optional location.nearby.proto.connections.LogSource log_source = 5;
+
+ // Encapsulates one session of a client connected to Nearby Connections API.
+ message ClientSession {
+ // Elapsed time in milliseconds between Client connect and
+ // disconnect.
+ optional int64 duration_millis = 1;
+
+ // Zero or more StrategySessions.
+ repeated StrategySession strategy_session = 2;
+ }
+
+ // One round of a particular Strategy done by a client.
+ message StrategySession {
+ // Elapsed time in milliseconds between a call to startAdvertising/Discovery
+ // and the end of this particular Strategy. A StrategySession may end due to
+ // - the client disconnecting from Client;
+ // - a call to stopAllEndpoints, which disconnects all endpoints and
+ // stops any advertising/discovery;
+ // - a new call to startAdvertising/Discovery.
+ optional int64 duration_millis = 1;
+
+ // The Strategy used for this session.
+ optional location.nearby.proto.connections.ConnectionsStrategy strategy = 2;
+
+ // The role(s) played by this device during this StrategySession.
+ repeated location.nearby.proto.connections.SessionRole role = 3;
+
+ // One or more of the following *Phase is present, depending on the role(s).
+
+ // Encapsulates discovery information.
+ repeated DiscoveryPhase discovery_phase = 4;
+ // Encapsulates advertising information.
+ repeated AdvertisingPhase advertising_phase = 5;
+
+ // Attempts at establishing a connection to another device.
+ repeated ConnectionAttempt connection_attempt = 6;
+
+ // Successful and accepted connections to another device.
+ repeated EstablishedConnection established_connection = 7;
+
+ // Attempts to upgrade a connection from one medium to another.
+ repeated BandwidthUpgradeAttempt upgrade_attempt = 9;
+
+ // The build version of the user's device (Same value as the Build number in
+ // Settings -> about phone).
+ optional string build_version = 10
+ ;
+ }
+
+ // Encapsulates activity during a period of discovery.
+ message DiscoveryPhase {
+ // Elapsed time in milliseconds between startDiscovery and stopDiscovery.
+ optional int64 duration_millis = 1;
+
+ // The Medium(s) used for discovery.
+ repeated location.nearby.proto.connections.Medium medium = 2;
+
+ // Discovered endpoints during this round of discovery.
+ repeated DiscoveredEndpoint discovered_endpoint = 3;
+
+ // Attempted ConnectionRequests (requested by the client). They may or
+ // may not reach the other endpoint.
+ repeated ConnectionRequest sent_connection_request = 4;
+
+ // UWB ranging related data during discovery (May range with multiple
+ // endpoints)
+ repeated UwbRangingProcess uwb_ranging = 5;
+
+ // The SendingEvent flow id.
+ optional int64 client_flow_id = 6 ;
+
+ // Encapsulates additional discovery information.
+ optional DiscoveryMetadata discovery_metadata = 7;
+ }
+
+ // An endpoint discovered on a particular medium during discovery.
+ message DiscoveredEndpoint {
+ // The medium on which this endpoint was discovered.
+ optional location.nearby.proto.connections.Medium medium = 1;
+
+ // Elapsed time between the call to startDiscovery() and the time at which
+ // this endpoint was discovered.
+ optional int64 latency_millis = 2;
+ }
+
+ // Encapsulates activity during UWB ranging.
+ message UwbRangingProcess {
+ // Elapsed time in milliseconds between startRanging and stopRanging.
+ optional int64 duration_millis = 1;
+
+ // UWB raw ranging data received during discovery. This is optional. Only
+ // certain devices (Debug/Testing etc.) will log the raw data.
+ repeated RawUwbRangingEvent uwb_ranging_data = 2;
+
+ // Number of ranging data received
+ optional int32 number_of_ranging_data = 3;
+
+ // The minimum distance during a UWB ranging session
+ optional int32 distance_min = 4;
+
+ // The maximum distance during a UWB ranging session
+ optional int32 distance_max = 5;
+
+ // The average distance during a UWB ranging session
+ optional int32 distance_ave = 6;
+
+ // The distance variance during a UWB ranging session
+ optional int32 distance_variance = 7;
+
+ // The minimum AoA during a UWB ranging session
+ optional int32 azimuth_min = 8;
+
+ // The maximum AoA during a UWB ranging session
+ optional int32 azimuth_max = 9;
+
+ // The average AoA during a UWB ranging session
+ optional int32 azimuth_ave = 10;
+
+ // The AoA variance during a UWB ranging session
+ optional int32 azimuth_variance = 11;
+ }
+
+ // Ranging data received during discovery phase.
+ message RawUwbRangingEvent {
+ // Distance in cm
+ optional int32 distance = 1;
+
+ // Azimuth angle in degree
+ optional int32 azimuth_angle = 2;
+
+ // Polar angle in degree (0 if the device doesn't support it)
+ optional int32 polar_angle = 3;
+ }
+
+ // Encapsulates activity during a period of advertising.
+ message AdvertisingPhase {
+ // Elapsed time in milliseconds between startAdvertising and
+ // stopAdvertising.
+ optional int64 duration_millis = 1;
+
+ // The Medium(s) used for advertising.
+ repeated location.nearby.proto.connections.Medium medium = 2;
+
+ // Received ConnectionRequests from remote endpoints.
+ repeated ConnectionRequest received_connection_request = 3;
+
+ // The ReceivingEvent flow id.
+ optional int64 client_flow_id = 4 ;
+
+ // Encapsulates additional advertising information.
+ optional AdvertisingMetadata advertising_metadata = 5;
+ }
+
+ // A request to connect, corresponding to the API's concept of
+ // request/accept/rejectConnection().
+ message ConnectionRequest {
+ // Elapsed time in milliseconds between the connection request being
+ // initiated and the responses being received.
+ optional int64 duration_millis = 1;
+
+ // Elapsed time in milliseconds between the start of the containing
+ // Advertising/DiscoveryPhase and the start of this ConnectionRequest, i.e.
+ // the time at which the request is sent (on the discoverer, at the request
+ // of the client) or received (on the advertiser, over the wire from the
+ // remote endpoint).
+ optional int64 request_delay_millis = 2;
+
+ // The local endpoint's response to this connection request.
+ optional location.nearby.proto.connections.ConnectionRequestResponse
+ local_response = 3;
+
+ // The remote endpoint's response to this connection request.
+ optional location.nearby.proto.connections.ConnectionRequestResponse
+ remote_response = 4;
+
+ // The SendingEvent flow id.
+ optional int64 client_flow_id = 5 ;
+ }
+
+ // An attempt to connect to an endpoint over a particular medium.
+ message ConnectionAttempt {
+ // Elapsed time in milliseconds between starting the connection attempt
+ // and succeeding/failing.
+ optional int64 duration_millis = 1;
+
+ // The type of connection attempt.
+ optional location.nearby.proto.connections.ConnectionAttemptType type = 2;
+
+ // The direction (incoming vs outgoing) of this attempt.
+ optional location.nearby.proto.connections.ConnectionAttemptDirection
+ direction = 3;
+
+ // The Medium of this connection attempt.
+ optional location.nearby.proto.connections.Medium medium = 4;
+
+ // The result of the connection attempt.
+ optional location.nearby.proto.connections.ConnectionAttemptResult
+ attempt_result = 5;
+
+ // The ReceivingEvent flow id.
+ optional int64 client_flow_id = 6 ;
+
+ // The token used to identify this connection pair.
+ optional string connection_token = 7
+ ;
+
+ // Encapsulates additional connection information.
+ optional ConnectionAttemptMetadata connection_attempt_metadata = 8;
+ }
+
+ // A successfully-established connection over a particular medium.
+ message EstablishedConnection {
+ // Elapsed time in milliseconds that the connection is active.
+ optional int64 duration_millis = 1;
+
+ // The Medium of this connection.
+ optional location.nearby.proto.connections.Medium medium = 2;
+
+ // Payloads sent over this connection.
+ repeated Payload sent_payload = 3;
+
+ // Payloads received over this connection.
+ repeated Payload received_payload = 4;
+
+ // The reason this connection was disconnected.
+ optional location.nearby.proto.connections.DisconnectionReason
+ disconnection_reason = 5;
+
+ // The SendingEvent flow id.
+ optional int64 client_flow_id = 6 ;
+
+ // The token use to identify this established connection.
+ optional string connection_token = 7
+ ;
+ }
+
+ // A Payload transferred (or attempted to be transferred) between devices.
+ message Payload {
+ // Elapsed time in milliseconds that num_bytes_transferred took to transfer.
+ optional int64 duration_millis = 1;
+
+ // The type of this payload.
+ optional location.nearby.proto.connections.PayloadType type = 2;
+
+ // Total size of the payload in bytes.
+ optional int64 total_size_bytes = 3;
+
+ // Total number of bytes transferred successfully.
+ optional int64 num_bytes_transferred = 4;
+
+ // The number of chunks used to transfer num_bytes_transferred.
+ optional int32 num_chunks = 5;
+
+ // The end status of the payload transfer.
+ optional location.nearby.proto.connections.PayloadStatus status = 6;
+ }
+
+ // An attempt to upgrade an existing connection from one medium to another.
+ message BandwidthUpgradeAttempt {
+ // The direction (incoming vs outgoing) of the upgrade attempt.
+ optional location.nearby.proto.connections.ConnectionAttemptDirection
+ direction = 1;
+
+ // Elapsed time in milliseconds of the upgrade attempt.
+ optional int64 duration_millis = 2;
+
+ // The original medium (e.g. bluetooth).
+ optional location.nearby.proto.connections.Medium from_medium = 3;
+
+ // The new medium that we're hoping to upgrade to (e.g. wifi).
+ optional location.nearby.proto.connections.Medium to_medium = 4;
+
+ // The result of the upgrade attempt.
+ optional location.nearby.proto.connections.BandwidthUpgradeResult
+ upgrade_result = 5;
+
+ // If upgrade_result is not success, the stage at which the error occurred.
+ optional location.nearby.proto.connections.BandwidthUpgradeErrorStage
+ error_stage = 6;
+
+ // The SendingEvent flow id.
+ optional int64 client_flow_id = 7 ;
+
+ // The token used to identify this upgrade pair.
+ optional string connection_token = 8
+ ;
+ }
+
+ // Next Id: 17
+ message ErrorCode {
+ // The direction (incoming vs outgoing) of this error.
+ optional location.nearby.proto.connections.ConnectionAttemptDirection
+ direction = 1;
+ optional string service_id = 2;
+ // The error medium (e.g. bluetooth).
+ optional location.nearby.proto.connections.Medium medium = 3;
+ // The event which the error occurs on.
+ optional location.nearby.errorcode.proto.Event event = 4;
+ // The error description.
+ optional location.nearby.errorcode.proto.Description description = 5;
+ // The flow id which the error occurs on.
+ optional int64 flow_id = 6 ;
+
+ // Error code value
+ oneof ErrorCodeDetail {
+ location.nearby.errorcode.proto.CommonError common_error = 7;
+ location.nearby.errorcode.proto.StartAdvertisingError
+ start_advertising_error = 8;
+ location.nearby.errorcode.proto.StartDiscoveringError
+ start_discovering_error = 9;
+ location.nearby.errorcode.proto.StopAdvertisingError
+ stop_advertising_error = 10;
+ location.nearby.errorcode.proto.StopDiscoveringError
+ stop_discovering_error = 11;
+ location.nearby.errorcode.proto.StartListeningIncomingConnectionError
+ start_listening_incoming_connection_error = 12;
+ location.nearby.errorcode.proto.StopListeningIncomingConnectionError
+ stop_listening_incoming_connection_error = 13;
+ location.nearby.errorcode.proto.ConnectError connect_error = 14;
+ location.nearby.errorcode.proto.DisconnectError disconnect_error = 15;
+ }
+
+ // The token use to identify this established connection.
+ optional string connection_token = 16
+ ;
+ }
+
+ // Some additional information to keep with the advertising phase.
+ message AdvertisingMetadata {
+ // The bluetooth low energy extended advertisement support status.
+ optional bool supports_extended_ble_advertisements = 1;
+
+ // The frequency of the connected WiFi AP.
+ optional int32 connected_ap_frequency = 2;
+
+ // The NFC (Near Field Communication) support status
+ optional bool supports_nfc_technology = 3;
+ }
+
+ // Some additional information to keep with the discovery phase.
+ message DiscoveryMetadata {
+ // The bluetooth low energy extended advertisement support status.
+ optional bool supports_extended_ble_advertisements = 1;
+
+ // The frequency of the connected WiFi AP.
+ optional int32 connected_ap_frequency = 2;
+
+ // The NFC (Near Field Communication) support status
+ optional bool supports_nfc_technology = 3;
+ }
+
+ // Some additional information to keep with the connection attempt.
+ message ConnectionAttemptMetadata {
+ // The technology used by the mediums.
+ optional location.nearby.proto.connections.ConnectionTechnology technology =
+ 1;
+
+ // The wifi band used by the wifi mediums.
+ optional location.nearby.proto.connections.ConnectionBand band = 2;
+
+ // The frequency used by the wifi mediums.
+ optional int32 frequency = 3;
+
+ // The MCC (Mobile country code) MNC (Mobile network code) of the network
+ // operator.
+ optional string network_operator = 4
+ ;
+
+ // The upper-case ISO 3166-1 alpha-2 country code of:
+ // 1. the current connected WiFi network
+ // 2. or the current registered operator's MCC (Mobile Country Code)
+ // 3. or empty string.
+ optional string country_code = 5 ;
+
+ // The TDLS status used by the wifi lan medium,
+ // TDLS, shortened from Tunneled Direct Link Setup, is "a seamless way to
+ // stream media and other data faster between devices already on the same
+ // Wi-Fi network." Devices using it communicate directly with one another,
+ // without involving the wireless network's router.
+ optional bool is_tdls_used = 6;
+
+ // The try times for this hosted group or connection operation.
+ optional int32 try_counts = 7;
+
+ // The enabled status of the wifi hotspot(tethering) when doing this
+ // connection attempt.
+ optional bool wifi_hotspot_status = 8;
+
+ // The MAX supported TX link speed (Mbps).
+ optional int32 max_tx_speed = 9;
+
+ // The MAX supported RX link speed (Mbps).
+ optional int32 max_rx_speed = 10;
+
+ // The connected wifi channel width.
+ optional int32 wifi_channel_width = 11;
+ }
+}
+// LINT.ThenChange()
diff --git a/chromium/third_party/nearby/src/internal/proto/analytics/connections_log_test.cc b/chromium/third_party/nearby/src/internal/proto/analytics/connections_log_test.cc
new file mode 100644
index 00000000000..ca59a1cedf2
--- /dev/null
+++ b/chromium/third_party/nearby/src/internal/proto/analytics/connections_log_test.cc
@@ -0,0 +1,126 @@
+// Copyright 2020 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "google/protobuf/descriptor.h"
+#include "gtest/gtest.h"
+#include "internal/platform/logging.h"
+#include "internal/proto/analytics/connections_log.pb.h"
+#include "proto/connections_enums.pb.h"
+
+namespace location {
+namespace nearby {
+namespace analytics {
+namespace proto {
+
+namespace {
+
+using G3ConnectionsLog = ::location::nearby::analytics::proto::ConnectionsLog;
+using P3ConnectionsLog = ::location::nearby::analytics::proto::ConnectionsLog;
+
+using ::proto2::Descriptor;
+using ::proto2::FieldDescriptor;
+
+// Forward declaration.
+bool Compare(const Descriptor* desc1, const Descriptor* desc2);
+
+// Compares the two field descriptors and return false if name, number, label,
+// or type is different.
+bool Compare(const FieldDescriptor* field1, const FieldDescriptor* field2) {
+ if (field1->name() != field2->name()) {
+ NEARBY_LOGS(WARNING) << "Field name diff: " << field1->name() << " <=> "
+ << field2->name();
+ return false;
+ }
+ if (field1->number() != field2->number()) {
+ NEARBY_LOGS(WARNING) << "Field " << field1->name()
+ << " number diff: " << field1->number() << " <=> "
+ << field2->number();
+ return false;
+ }
+ if (field1->label() != field2->label()) {
+ NEARBY_LOGS(WARNING) << "Field " << field1->name()
+ << " label diff: " << field1->label() << " <=> "
+ << field2->label();
+ return false;
+ }
+ bool bRet = false;
+ if (field1->type() != field2->type()) {
+ NEARBY_LOGS(WARNING) << "Field " << field1->name()
+ << " type diff: " << field1->type() << " <=> "
+ << field2->type();
+ return bRet;
+ } else if (field1->type() == FieldDescriptor::TYPE_MESSAGE) {
+ const Descriptor* msg1 = field1->message_type();
+ const Descriptor* msg2 = field2->message_type();
+
+ bRet = Compare(msg1, msg2);
+ } else {
+ bRet = true;
+ }
+
+ return bRet;
+}
+
+// Compares the two descriptors and return false immediately if different.
+bool Compare(const Descriptor* desc1, const Descriptor* desc2) {
+ NEARBY_LOGS(INFO) << "Descriptor1 full name: " << desc1->full_name()
+ << " <=> " << desc2->full_name();
+ for (int i = 0; i < desc1->field_count(); ++i) {
+ const FieldDescriptor* field1 = desc1->field(i);
+ const FieldDescriptor* field2 = desc2->FindFieldByName(field1->name());
+
+ bool bRet = false;
+ if (field2) {
+ bRet = Compare(field1, field2);
+ } else {
+ NEARBY_LOGS(ERROR) << "Descriptor1 full name: " << desc1->full_name()
+ << "=> Extra field1 name=" << field1->name()
+ << ", number=" << field1->number()
+ << ", label=" << field1->label()
+ << ", type=" << field1->type();
+ }
+ if (!bRet) {
+ return false;
+ }
+ }
+ for (int i = 0; i < desc2->field_count(); ++i) {
+ const FieldDescriptor* field2 = desc2->field(i);
+ const FieldDescriptor* field1 = desc1->FindFieldByName(field2->name());
+ if (!field1) {
+ NEARBY_LOGS(ERROR) << "Descriptor2 full name: " << desc2->full_name()
+ << "=> Extra field2 name=" << field2->name()
+ << ", number=" << field2->number()
+ << ", label=" << field2->label()
+ << ", type=" << field2->type();
+ return false;
+ }
+ }
+
+ return true;
+}
+
+TEST(ConnectionsLogTest, TwoMessagesAreIdentical) {
+ const proto2::Descriptor* descriptor1 = G3ConnectionsLog::descriptor();
+ const proto2::Descriptor* descriptor2 = P3ConnectionsLog::descriptor();
+
+ EXPECT_TRUE(Compare(descriptor1, descriptor2));
+}
+
+} // namespace
+
+} // namespace proto
+} // namespace analytics
+} // namespace nearby
+} // namespace location
diff --git a/chromium/third_party/nearby/src/proto/BUILD b/chromium/third_party/nearby/src/proto/BUILD
index 0117405fc6e..0fc92e84e10 100644
--- a/chromium/third_party/nearby/src/proto/BUILD
+++ b/chromium/third_party/nearby/src/proto/BUILD
@@ -14,7 +14,7 @@
# Proto for Nearby products
-load("//net/proto2/contrib/portable/cc:portable_proto_build_defs.bzl", "portable_proto_library")
+load("//tools/build_defs/proto/cpp:cc_proto_library.bzl", "cc_proto_library")
licenses(["notice"])
@@ -23,11 +23,6 @@ package(default_visibility = ["//visibility:public"])
proto_library(
name = "connections_enums_proto",
srcs = ["connections_enums.proto"],
- cc_api_version = 2,
- compatible_with = ["//buildenv/target:non_prod"],
- deps = [
- "//logs/proto/logs_annotations",
- ],
)
java_lite_proto_library(
@@ -45,43 +40,21 @@ java_proto_library(
deps = [":connections_enums_proto"],
)
-portable_proto_library(
- name = "connections_enums_portable_proto",
- compatible_with = [
- "//buildenv/target:non_prod",
- ],
- config = ":connections_enums_proto_config",
- copts = [
- "-DGOOGLE_PROTOBUF_NO_RTTI=1",
- ],
- header_outs = [
- "connections_enums.pb.h",
- ],
- proto_deps = [
+cc_proto_library(
+ name = "connections_enums_cc_proto",
+ deps = [
":connections_enums_proto",
],
- visibility = [
- "//location/nearby/connections:__subpackages__",
- "//third_party/nearby_connections:__subpackages__",
- ],
)
filegroup(
name = "connections_enums_proto_config",
srcs = ["connections_enums_proto_config.asciipb"],
- compatible_with = [
- "//buildenv/target:non_prod",
- ],
)
proto_library(
name = "sharing_enums_proto",
srcs = ["sharing_enums.proto"],
- cc_api_version = 2,
- compatible_with = ["//buildenv/target:non_prod"],
- deps = [
- "//logs/proto/logs_annotations",
- ],
)
java_lite_proto_library(
diff --git a/chromium/third_party/nearby/src/proto/analytics/BUILD b/chromium/third_party/nearby/src/proto/analytics/BUILD
deleted file mode 100644
index dbd3ee60f40..00000000000
--- a/chromium/third_party/nearby/src/proto/analytics/BUILD
+++ /dev/null
@@ -1,67 +0,0 @@
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# https://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-load("//tools/build_defs/proto/cpp:cc_proto_library.bzl", "cc_proto_library")
-
-licenses(["notice"])
-
-package(default_visibility = ["//visibility:public"])
-
-proto_library(
- name = "connections_log_proto",
- srcs = [
- "connections_log.proto",
- ],
- cc_api_version = 2,
- compatible_with = ["//buildenv/target:non_prod"],
- deps = [
-
- "//proto:connections_enums_proto",
- "//proto/errorcode:error_code_enums_proto",
- ],
-)
-
-cc_proto_library(
- name = "connections_log_cc_proto",
- compatible_with = ["//buildenv/target:non_prod"],
- visibility = [
- "//analytics:__subpackages__",
- "//core:__subpackages__",
- ],
- deps = [":connections_log_proto"],
-)
-
-java_lite_proto_library(
- name = "connections_log_java_proto_lite",
- deps = [":connections_log_proto"],
-)
-
-cc_test(
- name = "proto_analytics_test",
- size = "small",
- srcs = [
- "connections_log_test.cc",
- ],
- shard_count = 16,
- deps = [
- ":connections_log_cc_proto",
-
- "//net/proto2/public",
- "//testing/base/public:gunit_main",
- "//platform/base",
- "//platform/impl/g3", # build_cleaner: keep
- "//platform/public:logging",
- "//proto:connections_enums_portable_proto",
- ],
-)
diff --git a/chromium/third_party/nearby/src/proto/analytics/connections_log.proto b/chromium/third_party/nearby/src/proto/analytics/connections_log.proto
deleted file mode 100644
index 800aa3d0054..00000000000
--- a/chromium/third_party/nearby/src/proto/analytics/connections_log.proto
+++ /dev/null
@@ -1,435 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-syntax = "proto2";
-
-package location.nearby.analytics.proto;
-
-
-import "proto/connections_enums.proto";
-import "proto/errorcode/error_code_enums.proto";
-
-option optimize_for = LITE_RUNTIME;
-option java_package = "com.google.location.nearby.analytics.proto";
-option java_outer_classname = "ConnectionsLogProto";
-option objc_class_prefix = "GNCP";
-
-// Top-level log proto for Nearby Connections.
-// LINT.IfChange(ConnectionsLog)
-message ConnectionsLog {
- // The type of this log.
- optional location.nearby.proto.connections.EventType event_type = 1;
-
- // Non-null for EventType.CLIENT_SESSION.
- // Encapsulates all client activity between connecting to and disconnecting
- // from the Nearby Connections API via Client.
- optional ClientSession client_session = 2;
-
- // The version of Nearby Connections. E.g. "v1.0.4".
- optional string version = 3 ;
-
- // for EventType.ERROR_CODE
- optional ErrorCode error_code = 4;
-
- // Encapsulates one session of a client connected to Nearby Connections API.
- message ClientSession {
- // Elapsed time in milliseconds between Client connect and
- // disconnect.
- optional int64 duration_millis = 1;
-
- // Zero or more StrategySessions.
- repeated StrategySession strategy_session = 2;
- }
-
- // One round of a particular Strategy done by a client.
- message StrategySession {
- // Elapsed time in milliseconds between a call to startAdvertising/Discovery
- // and the end of this particular Strategy. A StrategySession may end due to
- // - the client disconnecting from Client;
- // - a call to stopAllEndpoints, which disconnects all endpoints and
- // stops any advertising/discovery;
- // - a new call to startAdvertising/Discovery.
- optional int64 duration_millis = 1;
-
- // The Strategy used for this session.
- optional location.nearby.proto.connections.ConnectionsStrategy strategy = 2;
-
- // The role(s) played by this device during this StrategySession.
- repeated location.nearby.proto.connections.SessionRole role = 3;
-
- // One or more of the following *Phase is present, depending on the role(s).
-
- // Encapsulates discovery information.
- repeated DiscoveryPhase discovery_phase = 4;
- // Encapsulates advertising information.
- repeated AdvertisingPhase advertising_phase = 5;
-
- // Attempts at establishing a connection to another device.
- repeated ConnectionAttempt connection_attempt = 6;
-
- // Successful and accepted connections to another device.
- repeated EstablishedConnection established_connection = 7;
-
- // Attempts to upgrade a connection from one medium to another.
- repeated BandwidthUpgradeAttempt upgrade_attempt = 9;
-
- // The build version of the user's device (Same value as the Build number in
- // Settings -> about phone).
- optional string build_version = 10
- ;
- }
-
- // Encapsulates activity during a period of discovery.
- message DiscoveryPhase {
- // Elapsed time in milliseconds between startDiscovery and stopDiscovery.
- optional int64 duration_millis = 1;
-
- // The Medium(s) used for discovery.
- repeated location.nearby.proto.connections.Medium medium = 2;
-
- // Discovered endpoints during this round of discovery.
- repeated DiscoveredEndpoint discovered_endpoint = 3;
-
- // Attempted ConnectionRequests (requested by the client). They may or
- // may not reach the other endpoint.
- repeated ConnectionRequest sent_connection_request = 4;
-
- // UWB ranging related data during discovery (May range with multiple
- // endpoints)
- repeated UwbRangingProcess uwb_ranging = 5;
-
- // The SendingEvent flow id.
- optional int64 client_flow_id = 6 ;
-
- // Encapsulates additional discovery information.
- optional DiscoveryMetadata discovery_metadata = 7;
- }
-
- // An endpoint discovered on a particular medium during discovery.
- message DiscoveredEndpoint {
- // The medium on which this endpoint was discovered.
- optional location.nearby.proto.connections.Medium medium = 1;
-
- // Elapsed time between the call to startDiscovery() and the time at which
- // this endpoint was discovered.
- optional int64 latency_millis = 2;
- }
-
- // Encapsulates activity during UWB ranging.
- message UwbRangingProcess {
- // Elapsed time in milliseconds between startRanging and stopRanging.
- optional int64 duration_millis = 1;
-
- // UWB raw ranging data received during discovery. This is optional. Only
- // certain devices (Debug/Testing etc.) will log the raw data.
- repeated RawUwbRangingEvent uwb_ranging_data = 2;
-
- // Number of ranging data received
- optional int32 number_of_ranging_data = 3;
-
- // The minimum distance during a UWB ranging session
- optional int32 distance_min = 4;
-
- // The maximum distance during a UWB ranging session
- optional int32 distance_max = 5;
-
- // The average distance during a UWB ranging session
- optional int32 distance_ave = 6;
-
- // The distance variance during a UWB ranging session
- optional int32 distance_variance = 7;
-
- // The minimum AoA during a UWB ranging session
- optional int32 azimuth_min = 8;
-
- // The maximum AoA during a UWB ranging session
- optional int32 azimuth_max = 9;
-
- // The average AoA during a UWB ranging session
- optional int32 azimuth_ave = 10;
-
- // The AoA variance during a UWB ranging session
- optional int32 azimuth_variance = 11;
- }
-
- // Ranging data received during discovery phase.
- message RawUwbRangingEvent {
- // Distance in cm
- optional int32 distance = 1;
-
- // Azimuth angle in degree
- optional int32 azimuth_angle = 2;
-
- // Polar angle in degree (0 if the device doesn't support it)
- optional int32 polar_angle = 3;
- }
-
- // Encapsulates activity during a period of advertising.
- message AdvertisingPhase {
- // Elapsed time in milliseconds between startAdvertising and
- // stopAdvertising.
- optional int64 duration_millis = 1;
-
- // The Medium(s) used for advertising.
- repeated location.nearby.proto.connections.Medium medium = 2;
-
- // Received ConnectionRequests from remote endpoints.
- repeated ConnectionRequest received_connection_request = 3;
-
- // The ReceivingEvent flow id.
- optional int64 client_flow_id = 4 ;
-
- // Encapsulates additional advertising information.
- optional AdvertisingMetadata advertising_metadata = 5;
- }
-
- // A request to connect, corresponding to the API's concept of
- // request/accept/rejectConnection().
- message ConnectionRequest {
- // Elapsed time in milliseconds between the connection request being
- // initiated and the responses being received.
- optional int64 duration_millis = 1;
-
- // Elapsed time in milliseconds between the start of the containing
- // Advertising/DiscoveryPhase and the start of this ConnectionRequest, i.e.
- // the time at which the request is sent (on the discoverer, at the request
- // of the client) or received (on the advertiser, over the wire from the
- // remote endpoint).
- optional int64 request_delay_millis = 2;
-
- // The local endpoint's response to this connection request.
- optional location.nearby.proto.connections.ConnectionRequestResponse
- local_response = 3;
-
- // The remote endpoint's response to this connection request.
- optional location.nearby.proto.connections.ConnectionRequestResponse
- remote_response = 4;
-
- // The SendingEvent flow id.
- optional int64 client_flow_id = 5 ;
- }
-
- // An attempt to connect to an endpoint over a particular medium.
- message ConnectionAttempt {
- // Elapsed time in milliseconds between starting the connection attempt
- // and succeeding/failing.
- optional int64 duration_millis = 1;
-
- // The type of connection attempt.
- optional location.nearby.proto.connections.ConnectionAttemptType type = 2;
-
- // The direction (incoming vs outgoing) of this attempt.
- optional location.nearby.proto.connections.ConnectionAttemptDirection
- direction = 3;
-
- // The Medium of this connection attempt.
- optional location.nearby.proto.connections.Medium medium = 4;
-
- // The result of the connection attempt.
- optional location.nearby.proto.connections.ConnectionAttemptResult
- attempt_result = 5;
-
- // The ReceivingEvent flow id.
- optional int64 client_flow_id = 6 ;
-
- // The token used to identify this connection pair.
- optional string connection_token = 7
- ;
-
- // Encapsulates additional connection information.
- optional ConnectionAttemptMetadata connection_attempt_metadata = 8;
- }
-
- // A successfully-established connection over a particular medium.
- message EstablishedConnection {
- // Elapsed time in milliseconds that the connection is active.
- optional int64 duration_millis = 1;
-
- // The Medium of this connection.
- optional location.nearby.proto.connections.Medium medium = 2;
-
- // Payloads sent over this connection.
- repeated Payload sent_payload = 3;
-
- // Payloads received over this connection.
- repeated Payload received_payload = 4;
-
- // The reason this connection was disconnected.
- optional location.nearby.proto.connections.DisconnectionReason
- disconnection_reason = 5;
-
- // The SendingEvent flow id.
- optional int64 client_flow_id = 6 ;
-
- // The token use to identify this established connection.
- optional string connection_token = 7
- ;
- }
-
- // A Payload transferred (or attempted to be transferred) between devices.
- message Payload {
- // Elapsed time in milliseconds that num_bytes_transferred took to transfer.
- optional int64 duration_millis = 1;
-
- // The type of this payload.
- optional location.nearby.proto.connections.PayloadType type = 2;
-
- // Total size of the payload in bytes.
- optional int64 total_size_bytes = 3;
-
- // Total number of bytes transferred successfully.
- optional int64 num_bytes_transferred = 4;
-
- // The number of chunks used to transfer num_bytes_transferred.
- optional int32 num_chunks = 5;
-
- // The end status of the payload transfer.
- optional location.nearby.proto.connections.PayloadStatus status = 6;
- }
-
- // An attempt to upgrade an existing connection from one medium to another.
- message BandwidthUpgradeAttempt {
- // The direction (incoming vs outgoing) of the upgrade attempt.
- optional location.nearby.proto.connections.ConnectionAttemptDirection
- direction = 1;
-
- // Elapsed time in milliseconds of the upgrade attempt.
- optional int64 duration_millis = 2;
-
- // The original medium (e.g. bluetooth).
- optional location.nearby.proto.connections.Medium from_medium = 3;
-
- // The new medium that we're hoping to upgrade to (e.g. wifi).
- optional location.nearby.proto.connections.Medium to_medium = 4;
-
- // The result of the upgrade attempt.
- optional location.nearby.proto.connections.BandwidthUpgradeResult
- upgrade_result = 5;
-
- // If upgrade_result is not success, the stage at which the error occurred.
- optional location.nearby.proto.connections.BandwidthUpgradeErrorStage
- error_stage = 6;
-
- // The SendingEvent flow id.
- optional int64 client_flow_id = 7 ;
-
- // The token used to identify this upgrade pair.
- optional string connection_token = 8
- ;
- }
-
- // Next Id: 17
- message ErrorCode {
- // The direction (incoming vs outgoing) of this error.
- optional location.nearby.proto.connections.ConnectionAttemptDirection
- direction = 1;
- optional string service_id = 2;
- // The error medium (e.g. bluetooth).
- optional location.nearby.proto.connections.Medium medium = 3;
- // The event which the error occurs on.
- optional location.nearby.errorcode.proto.Event event = 4;
- // The error description.
- optional location.nearby.errorcode.proto.Description description = 5;
- // The flow id which the error occurs on.
- optional int64 flow_id = 6 ;
-
- // Error code value
- oneof ErrorCodeDetail {
- location.nearby.errorcode.proto.CommonError common_error = 7;
- location.nearby.errorcode.proto.StartAdvertisingError
- start_advertising_error = 8;
- location.nearby.errorcode.proto.StartDiscoveringError
- start_discovering_error = 9;
- location.nearby.errorcode.proto.StopAdvertisingError
- stop_advertising_error = 10;
- location.nearby.errorcode.proto.StopDiscoveringError
- stop_discovering_error = 11;
- location.nearby.errorcode.proto.StartListeningIncomingConnectionError
- start_listening_incoming_connection_error = 12;
- location.nearby.errorcode.proto.StopListeningIncomingConnectionError
- stop_listening_incoming_connection_error = 13;
- location.nearby.errorcode.proto.ConnectError connect_error = 14;
- location.nearby.errorcode.proto.DisconnectError disconnect_error = 15;
- }
-
- // The token use to identify this established connection.
- optional string connection_token = 16
- ;
- }
-
- // Some additional information to keep with the advertising phase.
- message AdvertisingMetadata {
- // The bluetooth low energy extended advertisement support status.
- optional bool supports_extended_ble_advertisements = 1;
-
- // The frequency of the connected WiFi AP.
- optional int32 connected_ap_frequency = 2;
- }
-
- // Some additional information to keep with the discovery phase.
- message DiscoveryMetadata {
- // The bluetooth low energy extended advertisement support status.
- optional bool supports_extended_ble_advertisements = 1;
-
- // The frequency of the connected WiFi AP.
- optional int32 connected_ap_frequency = 2;
- }
-
- // Some additional information to keep with the connection attempt.
- message ConnectionAttemptMetadata {
- // The technology used by the mediums.
- optional location.nearby.proto.connections.ConnectionTechnology technology =
- 1;
-
- // The wifi band used by the wifi mediums.
- optional location.nearby.proto.connections.ConnectionBand band = 2;
-
- // The frequency used by the wifi mediums.
- optional int32 frequency = 3;
-
- // The MCC (Mobile country code) MNC (Mobile network code) of the network
- // operator.
- optional string network_operator = 4
- ;
-
- // The upper-case ISO 3166-1 alpha-2 country code of the current registered
- // operator's MCC (Mobile Country Code), or the country code of the default
- // Locale if not available.
- optional string country_code = 5 ;
-
- // The TDLS status used by the wifi lan medium,
- // TDLS, shortened from Tunneled Direct Link Setup, is "a seamless way to
- // stream media and other data faster between devices already on the same
- // Wi-Fi network." Devices using it communicate directly with one another,
- // without involving the wireless network's router.
- optional bool is_tdls_used = 6;
-
- // The try times for this hosted group or connection operation.
- optional int32 try_counts = 7;
-
- // The enabled status of the wifi hotspot(tethering) when doing this
- // connection attempt.
- optional bool wifi_hotspot_status = 8;
-
- // The MAX supported TX link speed (Mbps).
- optional int32 max_tx_speed = 9;
-
- // The MAX supported RX link speed (Mbps).
- optional int32 max_rx_speed = 10;
-
- // The connected wifi channel width.
- optional int32 wifi_channel_width = 11;
- }
-}
-// LINT.ThenChange()
diff --git a/chromium/third_party/nearby/src/proto/analytics/connections_log_test.cc b/chromium/third_party/nearby/src/proto/analytics/connections_log_test.cc
deleted file mode 100644
index 6e05f9b69fa..00000000000
--- a/chromium/third_party/nearby/src/proto/analytics/connections_log_test.cc
+++ /dev/null
@@ -1,126 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-
-#include "google/protobuf/descriptor.h"
-#include "gtest/gtest.h"
-#include "platform/public/logging.h"
-#include "proto/analytics/connections_log.pb.h"
-#include "proto/connections_enums.pb.h"
-
-namespace location {
-namespace nearby {
-namespace analytics {
-namespace proto {
-
-namespace {
-
-using G3ConnectionsLog = ::location::nearby::analytics::proto::ConnectionsLog;
-using P3ConnectionsLog = ::location::nearby::analytics::proto::ConnectionsLog;
-
-using ::proto2::Descriptor;
-using ::proto2::FieldDescriptor;
-
-// Forward declaration.
-bool Compare(const Descriptor* desc1, const Descriptor* desc2);
-
-// Compares the two field descriptors and return false if name, number, label,
-// or type is different.
-bool Compare(const FieldDescriptor* field1, const FieldDescriptor* field2) {
- if (field1->name() != field2->name()) {
- NEARBY_LOGS(WARNING) << "Field name diff: " << field1->name() << " <=> "
- << field2->name();
- return false;
- }
- if (field1->number() != field2->number()) {
- NEARBY_LOGS(WARNING) << "Field " << field1->name()
- << " number diff: " << field1->number() << " <=> "
- << field2->number();
- return false;
- }
- if (field1->label() != field2->label()) {
- NEARBY_LOGS(WARNING) << "Field " << field1->name()
- << " label diff: " << field1->label() << " <=> "
- << field2->label();
- return false;
- }
- bool bRet = false;
- if (field1->type() != field2->type()) {
- NEARBY_LOGS(WARNING) << "Field " << field1->name()
- << " type diff: " << field1->type() << " <=> "
- << field2->type();
- return bRet;
- } else if (field1->type() == FieldDescriptor::TYPE_MESSAGE) {
- const Descriptor* msg1 = field1->message_type();
- const Descriptor* msg2 = field2->message_type();
-
- bRet = Compare(msg1, msg2);
- } else {
- bRet = true;
- }
-
- return bRet;
-}
-
-// Compares the two descriptors and return false immediately if different.
-bool Compare(const Descriptor* desc1, const Descriptor* desc2) {
- NEARBY_LOGS(INFO) << "Descriptor1 full name: " << desc1->full_name()
- << " <=> " << desc2->full_name();
- for (int i = 0; i < desc1->field_count(); ++i) {
- const FieldDescriptor* field1 = desc1->field(i);
- const FieldDescriptor* field2 = desc2->FindFieldByName(field1->name());
-
- bool bRet = false;
- if (field2) {
- bRet = Compare(field1, field2);
- } else {
- NEARBY_LOGS(ERROR) << "Descriptor1 full name: " << desc1->full_name()
- << "=> Extra field1 name=" << field1->name()
- << ", number=" << field1->number()
- << ", label=" << field1->label()
- << ", type=" << field1->type();
- }
- if (!bRet) {
- return false;
- }
- }
- for (int i = 0; i < desc2->field_count(); ++i) {
- const FieldDescriptor* field2 = desc2->field(i);
- const FieldDescriptor* field1 = desc1->FindFieldByName(field2->name());
- if (!field1) {
- NEARBY_LOGS(ERROR) << "Descriptor2 full name: " << desc2->full_name()
- << "=> Extra field2 name=" << field2->name()
- << ", number=" << field2->number()
- << ", label=" << field2->label()
- << ", type=" << field2->type();
- return false;
- }
- }
-
- return true;
-}
-
-TEST(ConnectionsLogTest, TwoMessagesAreIdentical) {
- const proto2::Descriptor* descriptor1 = G3ConnectionsLog::descriptor();
- const proto2::Descriptor* descriptor2 = P3ConnectionsLog::descriptor();
-
- EXPECT_TRUE(Compare(descriptor1, descriptor2));
-}
-
-} // namespace
-
-} // namespace proto
-} // namespace analytics
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/proto/connections/BUILD b/chromium/third_party/nearby/src/proto/connections/BUILD
deleted file mode 100644
index 78b027199c6..00000000000
--- a/chromium/third_party/nearby/src/proto/connections/BUILD
+++ /dev/null
@@ -1,70 +0,0 @@
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# https://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-load("//net/proto2/contrib/portable/cc:portable_proto_build_defs.bzl", "portable_proto_library")
-
-licenses(["notice"])
-
-proto_library(
- name = "offline_wire_formats_proto",
- srcs = [
- "offline_wire_formats.proto",
- ],
- cc_api_version = 2,
- compatible_with = [
- "//buildenv/target:non_prod",
- ],
- visibility = [
- "//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
- ],
-)
-
-java_lite_proto_library(
- name = "offline_wire_formats_java_proto_lite",
- visibility = [
- "//java/com/google/android/gmscore/integ/modules/nearby:__subpackages__",
- "//javatests/com/google/android/gmscore/integ/modules/nearby:__subpackages__",
- ],
- deps = [":offline_wire_formats_proto"],
-)
-
-portable_proto_library(
- name = "offline_wire_formats_portable_proto",
- compatible_with = [
- "//buildenv/target:non_prod",
- ],
- config = ":offline_wire_formats_proto_config",
- copts = [
- "-DGOOGLE_PROTOBUF_NO_RTTI=1",
- ],
- header_outs = [
- "offline_wire_formats.pb.h",
- ],
- proto_deps = [
- ":offline_wire_formats_proto",
- ],
- visibility = [
- "//location/nearby/connections:__subpackages__",
- "//nearby_connections:__subpackages__",
- "//third_party/nearby_connections:__subpackages__",
- ],
-)
-
-filegroup(
- name = "offline_wire_formats_proto_config",
- srcs = ["offline_wire_formats_proto_config.asciipb"],
- compatible_with = [
- "//buildenv/target:non_prod",
- ],
-)
diff --git a/chromium/third_party/nearby/src/proto/connections/offline_wire_formats.proto b/chromium/third_party/nearby/src/proto/connections/offline_wire_formats.proto
deleted file mode 100644
index ac5888763c2..00000000000
--- a/chromium/third_party/nearby/src/proto/connections/offline_wire_formats.proto
+++ /dev/null
@@ -1,364 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-syntax = "proto2";
-
-package location.nearby.connections;
-
-option optimize_for = LITE_RUNTIME;
-option java_outer_classname = "OfflineWireFormatsProto";
-option java_package = "com.google.location.nearby.connections.proto";
-option objc_class_prefix = "GNCP";
-
-message OfflineFrame {
- enum Version {
- UNKNOWN_VERSION = 0;
- V1 = 1;
- }
- optional Version version = 1;
-
- // Right now there's only 1 version, but if there are more, exactly one of
- // the following fields will be set.
- optional V1Frame v1 = 2;
-}
-
-message V1Frame {
- enum FrameType {
- UNKNOWN_FRAME_TYPE = 0;
- CONNECTION_REQUEST = 1;
- CONNECTION_RESPONSE = 2;
- PAYLOAD_TRANSFER = 3;
- BANDWIDTH_UPGRADE_NEGOTIATION = 4;
- KEEP_ALIVE = 5;
- DISCONNECTION = 6;
- PAIRED_KEY_ENCRYPTION = 7;
- }
- optional FrameType type = 1;
-
- // Exactly one of the following fields will be set.
- optional ConnectionRequestFrame connection_request = 2;
- optional ConnectionResponseFrame connection_response = 3;
- optional PayloadTransferFrame payload_transfer = 4;
- optional BandwidthUpgradeNegotiationFrame bandwidth_upgrade_negotiation = 5;
- optional KeepAliveFrame keep_alive = 6;
- optional DisconnectionFrame disconnection = 7;
- optional PairedKeyEncryptionFrame paired_key_encryption = 8;
-}
-
-message ConnectionRequestFrame {
- // Should always match cs/symbol:location.nearby.proto.connections.Medium
- // LINT.IfChange
- enum Medium {
- UNKNOWN_MEDIUM = 0;
- MDNS = 1 [deprecated = true];
- BLUETOOTH = 2;
- WIFI_HOTSPOT = 3;
- BLE = 4;
- WIFI_LAN = 5;
- WIFI_AWARE = 6;
- NFC = 7;
- WIFI_DIRECT = 8;
- WEB_RTC = 9;
- BLE_L2CAP = 10;
- }
- // LINT.ThenChange(//depot/google3/third_party/nearby_connections/proto/connections_enums.proto)
-
- optional string endpoint_id = 1;
- optional string endpoint_name = 2;
- optional bytes handshake_data = 3;
- // A random number generated for each outgoing connection that is presently
- // used to act as a tiebreaker when 2 devices connect to each other
- // simultaneously; this can also be used for other initialization-scoped
- // things in the future.
- optional int32 nonce = 4;
- // The mediums this device supports upgrading to. This list should be filtered
- // by both the strategy and this device's individual limitations.
- repeated Medium mediums = 5;
- optional bytes endpoint_info = 6;
- optional MediumMetadata medium_metadata = 7;
- optional int32 keep_alive_interval_millis = 8;
- optional int32 keep_alive_timeout_millis = 9;
-}
-
-message ConnectionResponseFrame {
- // This doesn't need to send back endpoint_id and endpoint_name (like
- // the ConnectionRequestFrame does) because those have already been
- // transmitted out-of-band, at the time this endpoint was discovered.
-
- // One of:
- //
- // - ConnectionsStatusCodes.STATUS_OK
- // - ConnectionsStatusCodes.STATUS_CONNECTION_REJECTED.
- optional int32 status = 1 [deprecated = true];
- optional bytes handshake_data = 2;
-
- // Used to replace the status integer parameter with a meaningful enum item.
- // Map ConnectionsStatusCodes.STATUS_OK to ACCEPT and
- // ConnectionsStatusCodes.STATUS_CONNECTION_REJECTED to REJECT.
- // Flag: connection_replace_status_with_response_connectionResponseFrame
- enum ResponseStatus {
- UNKNOWN_RESPONSE_STATUS = 0;
- ACCEPT = 1;
- REJECT = 2;
- }
- optional ResponseStatus response = 3;
-}
-
-message PayloadTransferFrame {
- enum PacketType {
- UNKNOWN_PACKET_TYPE = 0;
- DATA = 1;
- CONTROL = 2;
- }
-
- message PayloadHeader {
- enum PayloadType {
- UNKNOWN_PAYLOAD_TYPE = 0;
- BYTES = 1;
- FILE = 2;
- STREAM = 3;
- }
- optional int64 id = 1;
- optional PayloadType type = 2;
- optional int64 total_size = 3;
- optional bool is_sensitive = 4;
- optional string file_name = 5;
- optional string parent_folder = 6;
- }
-
- // Accompanies DATA packets.
- message PayloadChunk {
- enum Flags { LAST_CHUNK = 0x1; }
- optional int32 flags = 1;
- optional int64 offset = 2;
- optional bytes body = 3;
- }
-
- // Accompanies CONTROL packets.
- message ControlMessage {
- enum EventType {
- UNKNOWN_EVENT_TYPE = 0;
- PAYLOAD_ERROR = 1;
- PAYLOAD_CANCELED = 2;
- }
-
- optional EventType event = 1;
- optional int64 offset = 2;
- }
-
- optional PacketType packet_type = 1;
- optional PayloadHeader payload_header = 2;
-
- // Exactly one of the following fields will be set, depending on the type.
- optional PayloadChunk payload_chunk = 3;
- optional ControlMessage control_message = 4;
-}
-
-message BandwidthUpgradeNegotiationFrame {
- enum EventType {
- UNKNOWN_EVENT_TYPE = 0;
- UPGRADE_PATH_AVAILABLE = 1;
- LAST_WRITE_TO_PRIOR_CHANNEL = 2;
- SAFE_TO_CLOSE_PRIOR_CHANNEL = 3;
- CLIENT_INTRODUCTION = 4;
- UPGRADE_FAILURE = 5;
- CLIENT_INTRODUCTION_ACK = 6;
- }
-
- // Accompanies UPGRADE_PATH_AVAILABLE and UPGRADE_FAILURE events.
- message UpgradePathInfo {
- // Should always match cs/symbol:location.nearby.proto.connections.Medium
- enum Medium {
- UNKNOWN_MEDIUM = 0;
- MDNS = 1 [deprecated = true];
- BLUETOOTH = 2;
- WIFI_HOTSPOT = 3;
- BLE = 4;
- WIFI_LAN = 5;
- WIFI_AWARE = 6;
- NFC = 7;
- WIFI_DIRECT = 8;
- WEB_RTC = 9;
- }
-
- // Accompanies Medium.WIFI_HOTSPOT.
- message WifiHotspotCredentials {
- optional string ssid = 1;
- optional string password = 2;
- optional int32 port = 3;
- optional string gateway = 4 [default = "0.0.0.0"];
- // This field can be a band or frequency
- optional int32 frequency = 5 [default = -1];
- }
-
- // Accompanies Medium.WIFI_LAN.
- message WifiLanSocket {
- optional bytes ip_address = 1;
- optional int32 wifi_port = 2;
- }
-
- // Accompanies Medium.BLUETOOTH.
- message BluetoothCredentials {
- optional string service_name = 1;
- optional string mac_address = 2;
- }
-
- // Accompanies Medium.WIFI_AWARE.
- message WifiAwareCredentials {
- optional string service_id = 1;
- optional bytes service_info = 2;
- optional string password = 3;
- }
-
- // Accompanies Medium.WIFI_DIRECT.
- message WifiDirectCredentials {
- optional string ssid = 1;
- optional string password = 2;
- optional int32 port = 3;
- optional int32 frequency = 4;
- }
-
- // Accompanies Medium.WEB_RTC
- message WebRtcCredentials {
- optional string peer_id = 1;
- optional LocationHint location_hint = 2;
- }
-
- optional Medium medium = 1;
-
- // Exactly one of the following fields will be set.
- optional WifiHotspotCredentials wifi_hotspot_credentials = 2;
- optional WifiLanSocket wifi_lan_socket = 3;
- optional BluetoothCredentials bluetooth_credentials = 4;
- optional WifiAwareCredentials wifi_aware_credentials = 5;
- optional WifiDirectCredentials wifi_direct_credentials = 6;
- optional WebRtcCredentials web_rtc_credentials = 8;
-
- // Disable Encryption for this upgrade medium to improve throughput.
- optional bool supports_disabling_encryption = 7;
-
- // An ack will be sent after the CLIENT_INTRODUCTION frame.
- optional bool supports_client_introduction_ack = 9;
- }
-
- // Accompanies CLIENT_INTRODUCTION events.
- message ClientIntroduction {
- optional string endpoint_id = 1;
- optional bool supports_disabling_encryption = 2;
- }
-
- // Accompanies CLIENT_INTRODUCTION_ACK events.
- message ClientIntroductionAck {}
-
- optional EventType event_type = 1;
-
- // Exactly one of the following fields will be set.
- optional UpgradePathInfo upgrade_path_info = 2;
- optional ClientIntroduction client_introduction = 3;
- optional ClientIntroductionAck client_introduction_ack = 4;
-}
-
-message KeepAliveFrame {
- // And ack will be sent after receiving KEEP_ALIVE frame.
- optional bool ack = 1;
-}
-
-// Informs the remote side to immediately severe the socket connection.
-// Used in bandwidth upgrades to get around a race condition, but may be used
-// in other situations to trigger a faster disconnection event than waiting for
-// socket closed on the remote side.
-message DisconnectionFrame {
- // Empty on purpose.
-}
-
-// A paired key encryption packet sent between devices, contains signed data.
-message PairedKeyEncryptionFrame {
- // The encrypted data (raw authentication token for the established
- // connection) in byte array format.
- optional bytes signed_data = 1;
-}
-
-message MediumMetadata {
- // True if local device supports 5GHz.
- optional bool supports_5_ghz = 1;
- // WiFi LAN BSSID
- optional string bssid = 2;
- // IP address
- optional bytes ip_address = 3;
- // True if local device supports 6GHz.
- optional bool supports_6_ghz = 4;
- // True if local device has mobile radio.
- optional bool mobile_radio = 5;
- // The frequency of the WiFi LAN AP (or -1 is not associated to an AP over
- // WiFi).
- optional int32 ap_frequency = 6 [default = -1];
- // Available channels on the local device.
- optional AvailableChannels available_channels = 7;
- // Usable WiFi Direct client channels on the local device.
- optional WifiDirectCliUsableChannels wifi_direct_cli_usable_channels = 8;
- // Usable WiFi LAN channels on the local device.
- optional WifiLanUsableChannels wifi_lan_usable_channels = 9;
- // Usable WiFi Aware channels on the local device.
- optional WifiAwareUsableChannels wifi_aware_usable_channels = 10;
- // Usable WiFi Hotspot STA channels on the local device.
- optional WifiHotspotStaUsableChannels wifi_hotspot_sta_usable_channels = 11;
-}
-
-// Available channels on the local device.
-message AvailableChannels {
- repeated int32 channels = 1 [packed = true];
-}
-
-// Usable WiFi Direct client channels on the local device.
-message WifiDirectCliUsableChannels {
- repeated int32 channels = 1 [packed = true];
-}
-
-// Usable WiFi LAN channels on the local device.
-message WifiLanUsableChannels {
- repeated int32 channels = 1 [packed = true];
-}
-
-// Usable WiFi Aware channels on the local device.
-message WifiAwareUsableChannels {
- repeated int32 channels = 1 [packed = true];
-}
-
-// Usable WiFi Hotspot STA channels on the local device.
-message WifiHotspotStaUsableChannels {
- repeated int32 channels = 1 [packed = true];
-}
-
-// LocationHint is used to specify a location as well as format.
-message LocationHint {
- // Location is the location, provided in the format specified by format.
- optional string location = 1;
-
- // the format of location.
- optional LocationStandard.Format format = 2;
-}
-
-message LocationStandard {
- enum Format {
- UNKNOWN = 0;
- // E164 country codes:
- // https://en.wikipedia.org/wiki/List_of_country_calling_codes
- // e.g. +1 for USA
- E164_CALLING = 1;
-
- // ISO 3166-1 alpha-2 country codes:
- // https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
- ISO_3166_1_ALPHA_2 = 2;
- }
-}
diff --git a/chromium/third_party/nearby/src/proto/connections_enums.proto b/chromium/third_party/nearby/src/proto/connections_enums.proto
index 2efe8e6a444..9384440f8f4 100644
--- a/chromium/third_party/nearby/src/proto/connections_enums.proto
+++ b/chromium/third_party/nearby/src/proto/connections_enums.proto
@@ -86,7 +86,7 @@ enum Medium {
// LINT.ThenChange(
// //depot/google3/java/com/google/android/gmscore/integ/client/nearby/src/com/google/android/gms/nearby/connection/Medium.java,
// //depot/google3/java/com/google/android/gms/nearby/internal/connection/api.proto,
-// //depot/google3/third_party/nearby_connections/proto/connections/offline_wire_formats.proto
+// //depot/google3/third_party/nearby/connections/implementation/proto/offline_wire_formats.proto
// )
// The medium technologies used during the sharing.
@@ -357,3 +357,22 @@ enum BandwidthUpgradeErrorStage {
// On the incoming side, listening for incoming WebRTC connections.
WEB_RTC_LISTEN_INCOMING = 34;
}
+
+// The device sources of the clearcut log.
+enum LogSource {
+ UNSPECIFIED_SOURCE = 0;
+
+ // Represents the devices in Nearby labs.
+ LAB_DEVICES = 1;
+ // Represents the devices tested by Nearby engs, in the long term can include
+ // any devices with newest feature flags.
+ INTERNAL_DEVICES = 2;
+ // Represents the devices testing our in-development features before they're
+ // released to the greater public.
+ BETA_TESTER_DEVICES = 3;
+ // Represents the OEM partners (like Samsung) that we're working with to
+ // verify functionality on their devices.
+ OEM_DEVICES = 4;
+ // Represents the device for debugging.
+ DEBUG_DEVICES = 5;
+} \ No newline at end of file
diff --git a/chromium/third_party/nearby/src/proto/errorcode/BUILD b/chromium/third_party/nearby/src/proto/errorcode/BUILD
index 9cd74c3914d..512fc108545 100644
--- a/chromium/third_party/nearby/src/proto/errorcode/BUILD
+++ b/chromium/third_party/nearby/src/proto/errorcode/BUILD
@@ -14,7 +14,7 @@
# Proto for Nearby products
-load("//net/proto2/contrib/portable/cc:portable_proto_build_defs.bzl", "portable_proto_library")
+load("//tools/build_defs/proto/cpp:cc_proto_library.bzl", "cc_proto_library")
licenses(["notice"])
@@ -23,11 +23,6 @@ package(default_visibility = ["//visibility:public"])
proto_library(
name = "error_code_enums_proto",
srcs = ["error_code_enums.proto"],
- cc_api_version = 2,
- compatible_with = ["//buildenv/target:non_prod"],
- deps = [
- "//logs/proto/logs_annotations",
- ],
)
java_lite_proto_library(
@@ -35,27 +30,12 @@ java_lite_proto_library(
deps = [":error_code_enums_proto"],
)
-portable_proto_library(
- name = "error_code_enums_portable_proto",
- compatible_with = [
- "//buildenv/target:non_prod",
- ],
- config = ":error_code_enums_proto_config",
- copts = [
- "-DGOOGLE_PROTOBUF_NO_RTTI=1",
- ],
- proto_deps = [
- ":error_code_enums_proto",
- ],
- visibility = [
- "//third_party/nearby_connections:__subpackages__",
- ],
+cc_proto_library(
+ name = "error_code_enums_cc_proto",
+ deps = [":error_code_enums_proto"],
)
filegroup(
name = "error_code_enums_proto_config",
srcs = ["error_code_enums_proto_config.asciipb"],
- compatible_with = [
- "//buildenv/target:non_prod",
- ],
)
diff --git a/chromium/third_party/nearby/src/proto/errorcode/error_code_enums.proto b/chromium/third_party/nearby/src/proto/errorcode/error_code_enums.proto
index 67171642c83..a2e07b1b771 100644
--- a/chromium/third_party/nearby/src/proto/errorcode/error_code_enums.proto
+++ b/chromium/third_party/nearby/src/proto/errorcode/error_code_enums.proto
@@ -502,4 +502,5 @@ enum Description {
UNSUPPORTED_DEVICE_TYPE_AUTO = 168;
UNSUPPORTED_DEVICE_TYPE_TV = 169;
UNSUPPORTED_DEVICE_TYPE_WEAR = 170;
+ NULL_MESSAGE = 171;
}
diff --git a/chromium/third_party/nearby/src/proto/mediums/BUILD b/chromium/third_party/nearby/src/proto/mediums/BUILD
index 0064d55395d..4acc8817e9d 100644
--- a/chromium/third_party/nearby/src/proto/mediums/BUILD
+++ b/chromium/third_party/nearby/src/proto/mediums/BUILD
@@ -12,7 +12,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-load("//net/proto2/contrib/portable/cc:portable_proto_build_defs.bzl", "portable_proto_library")
load("//tools/build_defs/proto/cpp:cc_proto_library.bzl", "cc_proto_library")
licenses(["notice"])
@@ -24,7 +23,6 @@ proto_library(
srcs = [
"nfc_frames.proto",
],
- cc_api_version = 2,
)
java_lite_proto_library(
@@ -38,7 +36,6 @@ proto_library(
srcs = [
"wifi_aware_frames.proto",
],
- cc_api_version = 2,
)
java_lite_proto_library(
@@ -51,41 +48,17 @@ java_lite_proto_library(
)
proto_library(
- name = "ble_frames_proto",
- srcs = [
- "ble_frames.proto",
- ],
- cc_api_version = 2,
-)
-
-java_lite_proto_library(
- name = "ble_frames_java_proto_lite",
- visibility = [
- "//java/com/google/android/gmscore/integ/modules/nearby/src/com/google/android/gms/nearby/mediums:__subpackages__",
- "//javatests/com/google/android/gmscore/integ/modules/nearby/src/com/google/android/gms/nearby/mediums:__subpackages__",
- ],
- deps = [":ble_frames_proto"],
-)
-
-proto_library(
name = "web_rtc_signaling_frames_proto",
srcs = [
"web_rtc_signaling_frames.proto",
],
- cc_api_version = 2,
- compatible_with = [
- "//buildenv/target:non_prod",
- ],
)
cc_proto_library(
name = "web_rtc_signaling_frames_cc_proto",
- compatible_with = [
- "//buildenv/target:non_prod",
- ],
visibility = [
"//location/nearby/connections:__subpackages__",
- "//third_party/nearby_connections:__subpackages__",
+ "//third_party/nearby:__subpackages__",
],
deps = [":web_rtc_signaling_frames_proto"],
)
@@ -99,16 +72,25 @@ java_lite_proto_library(
deps = [":web_rtc_signaling_frames_proto"],
)
-portable_proto_library(
- name = "ble_frames_portable_proto",
- config = ":ble_frames_portable_proto_config",
- copts = [
- "-DGOOGLE_PROTOBUF_NO_RTTI=1",
+proto_library(
+ name = "ble_frames_proto",
+ srcs = [
+ "ble_frames.proto",
],
- header_outs = [
- "ble_frames.pb.h",
+)
+
+java_lite_proto_library(
+ name = "ble_frames_java_proto_lite",
+ visibility = [
+ "//java/com/google/android/gmscore/integ/modules/nearby/src/com/google/android/gms/nearby/mediums:__subpackages__",
+ "//javatests/com/google/android/gmscore/integ/modules/nearby/src/com/google/android/gms/nearby/mediums:__subpackages__",
],
- proto_deps = [
+ deps = [":ble_frames_proto"],
+)
+
+cc_proto_library(
+ name = "ble_frames_cc_proto",
+ deps = [
":ble_frames_proto",
],
)
diff --git a/chromium/third_party/nearby/src/proto/sharing_enums.proto b/chromium/third_party/nearby/src/proto/sharing_enums.proto
index 29777ae9d9c..f57faed6cce 100644
--- a/chromium/third_party/nearby/src/proto/sharing_enums.proto
+++ b/chromium/third_party/nearby/src/proto/sharing_enums.proto
@@ -185,6 +185,9 @@ enum EventType {
// Set up a connection with the remote device.
ESTABLISH_CONNECTION = 48;
+
+ // Track device states in Nearby Share setting.
+ DEVICE_SETTINGS = 49;
}
// Event category to differentiate whether this comes from sender or receiver,
@@ -211,6 +214,7 @@ enum Visibility {
EVERYONE = 2;
SELECTED_CONTACTS_ONLY = 3;
HIDDEN = 4;
+ SELF_SHARE = 5;
}
enum DataUsage {
diff --git a/chromium/third_party/nearby/src/windows/BUILD b/chromium/third_party/nearby/src/windows/BUILD
deleted file mode 100644
index f7906412ce6..00000000000
--- a/chromium/third_party/nearby/src/windows/BUILD
+++ /dev/null
@@ -1,57 +0,0 @@
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# https://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-load("//third_party/msvc:build_windows.bzl", "cc_windows_dll")
-
-licenses(["notice"])
-
-# Build with --config=lexan
-cc_windows_dll(
- name = "core_adapter",
- srcs = ["core_adapter.cc"],
- hdrs = ["core_adapter.h"],
- copts = ["-DCORE_ADAPTER_BUILD_DLL -DCOMPILING_CORE"],
- defines = ["CORE_ADAPTER_DLL"],
- tags = ["windows-dll"],
- deps = [
- "//absl/strings",
- "//third_party/dart_lang/v2:dart_api_dl",
- "//core",
- "//platform/impl/windows",
- "//webrtc/api:create_peerconnection_factory",
- ],
-)
-
-# Build with --config=lexan
-# TODO(b/203019344) Move this configuration under dart folder and create a BUILD there.
-cc_windows_dll(
- name = "core_adapter_dart",
- srcs = [
- "core_adapter.cc",
- "dart/core_adapter_dart.cc",
- ],
- hdrs = [
- "core_adapter.h",
- "dart/core_adapter_dart.h",
- ],
- copts = ["-DCORE_ADAPTER_DART_BUILD_DLL -DCORE_ADAPTER_DLL -DCOMPILING_CORE"],
- defines = ["CORE_ADAPTER_DART_DLL"],
- tags = ["windows-dll"],
- deps = [
- "//absl/strings",
- "//third_party/dart_lang/v2:dart_api_dl",
- "//core",
- "//platform/impl/windows",
- "//webrtc/api:create_peerconnection_factory",
- ],
-)
diff --git a/chromium/third_party/nearby/src/windows/core_adapter.cc b/chromium/third_party/nearby/src/windows/core_adapter.cc
deleted file mode 100644
index 272b97ba0e4..00000000000
--- a/chromium/third_party/nearby/src/windows/core_adapter.cc
+++ /dev/null
@@ -1,158 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-#include "third_party/nearby_connections/windows/core_adapter.h"
-
-#include "absl/strings/str_format.h"
-#include "core/core.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-Core* InitCore(ServiceControllerRouter* router) {
- return new Core(router);
-}
-
-void CloseCore(Core* pCore) {
- if (pCore) {
- pCore->StopAllEndpoints(
- {.result_cb =
- std::function<void(location::nearby::connections::Status)>{
- [](location::nearby::connections::Status) {}}});
- delete pCore;
- }
-}
-
-void StartAdvertising(Core* pCore, const char* service_id,
- ConnectionOptions options,
- ConnectionRequestInfo info,
- ResultCallback callback) {
- if (pCore) {
- pCore->StartAdvertising(service_id, options, info, callback);
- }
-}
-
-void StopAdvertising(Core* pCore, ResultCallback callback) {
- if (pCore) {
- pCore->StopAdvertising(callback);
- }
-}
-
-void StartDiscovery(Core* pCore, const char* service_id,
- ConnectionOptions options,
- DiscoveryListener listener,
- ResultCallback callback) {
- if (pCore) {
- pCore->StartDiscovery(service_id, options, listener, callback);
- }
-}
-
-void StopDiscovery(Core* pCore, ResultCallback callback) {
- if (pCore) {
- pCore->StopDiscovery(callback);
- }
-}
-
-void InjectEndpoint(Core* pCore, char* service_id,
- OutOfBandConnectionMetadata metadata,
- ResultCallback callback) {
- if (pCore) {
- pCore->InjectEndpoint(service_id, metadata, callback);
- }
-}
-
-void RequestConnection(Core* pCore, const char* endpoint_id,
- ConnectionRequestInfo info,
- ConnectionOptions options,
- ResultCallback callback) {
- if (pCore) {
- pCore->RequestConnection(endpoint_id, info, options, callback);
- }
-}
-
-void AcceptConnection(Core* pCore, const char* endpoint_id,
- PayloadListener listener,
- ResultCallback callback) {
- if (pCore) {
- pCore->AcceptConnection(endpoint_id, listener, callback);
- }
-}
-
-void RejectConnection(Core* pCore, const char* endpoint_id,
- ResultCallback callback) {
- if (pCore) {
- pCore->RejectConnection(endpoint_id, callback);
- }
-}
-
-void SendPayload(Core* pCore,
- // todo(jfcarroll) this is being exported, needs to be
- // refactored to return a plain old c type
- absl::Span<const std::string> endpoint_ids,
- Payload payload, ResultCallback callback) {
- if (pCore) {
- pCore->SendPayload(endpoint_ids, std::move(payload), callback);
- }
-}
-
-void CancelPayload(Core* pCore, std::int64_t payload_id,
- ResultCallback callback) {
- if (pCore) {
- pCore->CancelPayload(payload_id, callback);
- }
-}
-
-void DisconnectFromEndpoint(Core* pCore, char* endpoint_id,
- ResultCallback callback) {
- if (pCore) {
- pCore->DisconnectFromEndpoint(endpoint_id, callback);
- }
-}
-
-void StopAllEndpoints(Core* pCore, ResultCallback callback) {
- if (pCore) {
- pCore->StopAllEndpoints(callback);
- }
-}
-
-void InitiateBandwidthUpgrade(Core* pCore, char* endpoint_id,
- ResultCallback callback) {
- if (pCore) {
- pCore->InitiateBandwidthUpgrade(endpoint_id, callback);
- }
-}
-
-const char* GetLocalEndpointId(Core* pCore) {
- if (pCore) {
- std::string endpoint_id = pCore->GetLocalEndpointId();
- char* result = new char[endpoint_id.length() + 1];
- absl::SNPrintF(result, endpoint_id.length() + 1, "%s", endpoint_id);
- return result;
- }
- return "Null-Core";
-}
-
-ServiceControllerRouter* InitServiceControllerRouter() {
- return new ServiceControllerRouter();
-}
-
-void CloseServiceControllerRouter(ServiceControllerRouter* pRouter) {
- if (pRouter) {
- delete pRouter;
- }
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/windows/core_adapter.h b/chromium/third_party/nearby/src/windows/core_adapter.h
deleted file mode 100644
index 7c2c5c9680c..00000000000
--- a/chromium/third_party/nearby/src/windows/core_adapter.h
+++ /dev/null
@@ -1,265 +0,0 @@
-// Copyright 2020 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-#ifndef LOCATION_NEARBY_CONNECTIONS_WINDOWS_CORE_ADAPTER_H_
-#define LOCATION_NEARBY_CONNECTIONS_WINDOWS_CORE_ADAPTER_H_
-
-#include "absl/strings/string_view.h"
-#include "absl/types/span.h"
-
-// todo(jfcarroll) This cannot remain. It exposes stuff the client doesn't need.
-#include \
-"third_party/nearby_connections/cpp/core/internal/offline_service_controller.h"
-
-#define DLL_EXPORT extern "C" __declspec(dllexport)
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-class Core;
-class ServiceControllerRouter;
-
-// Initizlizes a Core instance, providing the ServiceController factory from
-// app side. If no factory is provided, it will initialize a new
-// factory creating OffilineServiceController.
-// Returns the instance handle to c# client.
-DLL_EXPORT Core* __stdcall InitCoreWithServiceControllerFactory(
- std::function<ServiceController*()> factory = []() {
- return new OfflineServiceController;
- });
-
-// Initializes a default Core instance.
-// Returns the instance handle to c# client.
-DLL_EXPORT Core* __stdcall InitCore(ServiceControllerRouter* router);
-
-// Closes the core with stopping all endpoints, then free the memory.
-DLL_EXPORT void __stdcall CloseCore(Core* pCore);
-
-// Starts advertising an endpoint for a local app.
-//
-// service_id - An identifier to advertise your app to other endpoints.
-// This can be an arbitrary string, so long as it uniquely
-// identifies your service. A good default is to use your
-// app's package name.
-// options - The options for advertising.
-// info - Connection parameters:
-// > name - A human readable name for this endpoint, to appear on
-// other devices.
-// > listener - A callback notified when remote endpoints request a
-// connection to this endpoint.
-// callback - to access the status of the operation when available.
-// Possible status codes include:
-// Status::STATUS_OK if advertising started successfully.
-// Status::STATUS_ALREADY_ADVERTISING if the app is already advertising.
-// Status::STATUS_OUT_OF_ORDER_API_CALL if the app is currently
-// connected to remote endpoints; call StopAllEndpoints first.
-DLL_EXPORT void __stdcall StartAdvertising(Core* pCore, const char* service_id,
- ConnectionOptions options,
- ConnectionRequestInfo info,
- ResultCallback callback);
-
-// Stops advertising a local endpoint. Should be called after calling
-// StartAdvertising, as soon as the application no longer needs to advertise
-// itself or goes inactive. Payloads can still be sent to connected
-// endpoints after advertising ends.
-//
-// result_cb - to access the status of the operation when available.
-// Possible status codes include:
-// Status::STATUS_OK if none of the above errors occurred.
-DLL_EXPORT void __stdcall StopAdvertising(Core* pCore, ResultCallback callback);
-
-// Starts discovery for remote endpoints with the specified service ID.
-//
-// service_id - The ID for the service to be discovered, as specified in
-// the corresponding call to StartAdvertising.
-// listener - A callback notified when a remote endpoint is discovered.
-// options - The options for discovery.
-// result_cb - to access the status of the operation when available.
-// Possible status codes include:
-// Status::STATUS_OK if discovery started successfully.
-// Status::STATUS_ALREADY_DISCOVERING if the app is already
-// discovering the specified service.
-// Status::STATUS_OUT_OF_ORDER_API_CALL if the app is currently
-// connected to remote endpoints; call StopAllEndpoints first.
-DLL_EXPORT void __stdcall StartDiscovery(Core* pCore, const char* service_id,
- ConnectionOptions options,
- DiscoveryListener listener,
- ResultCallback callback);
-
-// Stops discovery for remote endpoints, after a previous call to
-// StartDiscovery, when the client no longer needs to discover endpoints or
-// goes inactive. Payloads can still be sent to connected endpoints after
-// discovery ends.
-//
-// result_cb - to access the status of the operation when available.
-// Possible status codes include:
-// Status::STATUS_OK if none of the above errors occurred.
-DLL_EXPORT void __stdcall StopDiscovery(Core* pCore, ResultCallback callback);
-
-// Invokes the discovery callback from a previous call to StartDiscovery()
-// with the given endpoint info. The previous call to StartDiscovery() must
-// have been passed ConnectionOptions with is_out_of_band_connection == true.
-//
-// service_id - The ID for the service to be discovered, as
-// specified in the corresponding call to
-// StartDiscovery().
-// metadata - Metadata used in order to inject the endpoint.
-// result_cb - to access the status of the operation when
-// available.
-// Possible status codes include:
-// Status::kSuccess if endpoint injection was attempted.
-// Status::kError if endpoint_id, endpoint_info, or
-// remote_bluetooth_mac_address are malformed.
-// Status::kOutOfOrderApiCall if the app is not discovering.
-DLL_EXPORT void __stdcall InjectEndpoint(Core* pCore, char* service_id,
- OutOfBandConnectionMetadata metadata,
- ResultCallback callback);
-
-// Sends a request to connect to a remote endpoint.
-//
-// endpoint_id - The identifier for the remote endpoint to which a
-// connection request will be sent. Should match the value
-// provided in a call to
-// DiscoveryListener::endpoint_found_cb()
-// info - Connection parameters:
-// > name - A human readable name for the local endpoint, to appear on
-// the remote endpoint.
-// > listener - A callback notified when the remote endpoint sends a
-// response to the connection request.
-// result_cb - to access the status of the operation when available.
-// Possible status codes include:
-// Status::STATUS_OK if the connection request was sent.
-// Status::STATUS_ALREADY_CONNECTED_TO_ENDPOINT if the app already
-// has a connection to the specified endpoint.
-// Status::STATUS_RADIO_ERROR if we failed to connect because of an
-// issue with Bluetooth/WiFi.
-// Status::STATUS_ERROR if we failed to connect for any other reason.
-DLL_EXPORT void __stdcall RequestConnection(Core* pCore,
- const char* endpoint_id,
- ConnectionRequestInfo info,
- ConnectionOptions options,
- ResultCallback callback);
-
-// Accepts a connection to a remote endpoint. This method must be called
-// before Payloads can be exchanged with the remote endpoint.
-//
-// endpoint_id - The identifier for the remote endpoint. Should match the
-// value provided in a call to
-// ConnectionListener::onConnectionInitiated.
-// listener - A callback for payloads exchanged with the remote endpoint.
-// result_cb - to access the status of the operation when available.
-// Possible status codes include:
-// Status::STATUS_OK if the connection request was accepted.
-// Status::STATUS_ALREADY_CONNECTED_TO_ENDPOINT if the app already.
-// has a connection to the specified endpoint.
-DLL_EXPORT void __stdcall AcceptConnection(Core* pCore,
- const char* endpoint_id,
- PayloadListener listener,
- ResultCallback callback);
-
-// Rejects a connection to a remote endpoint.
-//
-// endpoint_id - The identifier for the remote endpoint. Should match the
-// value provided in a call to
-// ConnectionListener::onConnectionInitiated().
-// result_cb - to access the status of the operation when available.
-// Possible status codes include:
-// Status::STATUS_OK} if the connection request was rejected.
-// Status::STATUS_ALREADY_CONNECTED_TO_ENDPOINT} if the app already
-// has a connection to the specified endpoint.
-DLL_EXPORT void __stdcall RejectConnection(Core* pCore, const char* endpoint_id,
- ResultCallback callback);
-
-// Sends a Payload to a remote endpoint. Payloads can only be sent to remote
-// endpoints once a notice of connection acceptance has been delivered via
-// ConnectionListener::onConnectionResult().
-//
-// endpoint_ids - Array of remote endpoint identifiers for the to which the
-// payload should be sent.
-// payload - The Payload to be sent.
-// result_cb - to access the status of the operation when available.
-// Possible status codes include:
-// Status::STATUS_OUT_OF_ORDER_API_CALL if the device has not first
-// performed advertisement or discovery (to set the Strategy.
-// Status::STATUS_ENDPOINT_UNKNOWN if there's no active (or pending)
-// connection to the remote endpoint.
-// Status::STATUS_OK if none of the above errors occurred. Note that this
-// indicates that Nearby Connections will attempt to send the Payload,
-// but not that the send has successfully completed yet. Errors might
-// still occur during transmission (and at different times for
-// different endpoints), and will be delivered via
-// PayloadCallback#onPayloadTransferUpdate.
-DLL_EXPORT void __stdcall SendPayload(Core* pCore,
- absl::Span<const std::string> endpoint_ids,
- Payload payload, ResultCallback callback);
-
-// Cancels a Payload currently in-flight to or from remote endpoint(s).
-//
-// payload_id - The identifier for the Payload to be canceled.
-// result_cb - to access the status of the operation when available.
-// Possible status codes include:
-// Status::STATUS_OK if none of the above errors occurred.
-DLL_EXPORT void __stdcall CancelPayload(Core* pCore, int64_t payload_id,
- ResultCallback callback);
-
-// Disconnects from a remote endpoint. {@link Payload}s can no longer be sent
-// to or received from the endpoint after this method is called.
-//
-// endpoint_id - The identifier for the remote endpoint to disconnect from.
-// result_cb - to access the status of the operation when available.
-// Possible status codes include:
-// Status::STATUS_OK - finished successfully.
-DLL_EXPORT void __stdcall DisconnectFromEndpoint(Core* pCore, char* endpoint_id,
- ResultCallback callback);
-
-// Disconnects from, and removes all traces of, all connected and/or
-// discovered endpoints. This call is expected to be preceded by a call to
-// StopAdvertising or StartDiscovery as needed. After calling
-// StopAllEndpoints, no further operations with remote endpoints will be
-// possible until a new call to one of StartAdvertising() or StartDiscovery().
-//
-// result_cb - to access the status of the operation when available.
-// Possible status codes include:
-// Status::STATUS_OK - finished successfully.
-DLL_EXPORT void __stdcall StopAllEndpoints(Core* pCore,
- ResultCallback callback);
-
-// Sends a request to initiate connection bandwidth upgrade.
-//
-// endpoint_id - The identifier for the remote endpoint which will be
-// switching to a higher connection data rate and possibly
-// different wireless protocol. On success, calls
-// ConnectionListener::bandwidth_changed_cb().
-// result_cb - to access the status of the operation when available.
-// Possible status codes include:
-// Status::STATUS_OK - finished successfully.
-DLL_EXPORT void __stdcall InitiateBandwidthUpgrade(Core* pCore,
- char* endpoint_id,
- ResultCallback callback);
-
-// Gets the local endpoint generated by Nearby Connections.
-DLL_EXPORT const char* __stdcall GetLocalEndpointId(Core* pCore);
-
-// Initializes a default ServiceControllerRouter instance.
-// Returns the instance handle to c# client.
-DLL_EXPORT ServiceControllerRouter* __stdcall InitServiceControllerRouter();
-
-// Close a ServiceControllerRouter instance.
-DLL_EXPORT void __stdcall CloseServiceControllerRouter(
- ServiceControllerRouter* pRouter);
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-#endif // LOCATION_NEARBY_CONNECTIONS_WINDOWS_CORE_ADAPTER_H_
diff --git a/chromium/third_party/nearby/src/windows/dart/core_adapter_dart.cc b/chromium/third_party/nearby/src/windows/dart/core_adapter_dart.cc
deleted file mode 100644
index 9d087202944..00000000000
--- a/chromium/third_party/nearby/src/windows/dart/core_adapter_dart.cc
+++ /dev/null
@@ -1,456 +0,0 @@
-// Copyright 2021 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "third_party/dart_lang/v2/runtime/include/dart_api_dl.h"
-#include "third_party/dart_lang/v2/runtime/include/dart_native_api.h"
-#include "third_party/nearby_connections/windows/dart/core_adapter_dart.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-Strategy GetStrategy(StrategyDart strategy) {
- switch (strategy) {
- case StrategyDart::P2P_CLUSTER:
- return Strategy::kP2pCluster;
- case StrategyDart::P2P_POINT_TO_POINT:
- return Strategy::kP2pPointToPoint;
- case StrategyDart::P2P_STAR:
- return Strategy::kP2pStar;
- }
- return Strategy::kNone;
-}
-
-ByteArray ConvertBluetoothMacAddress(absl::string_view address) {
- return ByteArray(address.data());
-}
-
-void SetResultCallback(ResultCallback& callback, Dart_Port& port) {
- callback.result_cb = [port](Status status) {
- Dart_CObject dart_object_result_callback;
- dart_object_result_callback.type = Dart_CObject_kInt64;
- dart_object_result_callback.value.as_int64 = status.value;
- const bool result = Dart_PostCObject_DL(port,
- &dart_object_result_callback);
- if (!result) {
- NEARBY_LOG(INFO, "Posting message to port failed.");
- }
- };
-}
-
-void PostResult(Dart_Port& result_cb, Status::Value value) {
- Dart_CObject dart_object_result_callback;
- dart_object_result_callback.type = Dart_CObject_kInt64;
- dart_object_result_callback.value.as_int64 = value;
- const bool result = Dart_PostCObject_DL(result_cb,
- &dart_object_result_callback);
- if (!result) {
- NEARBY_LOG(INFO, "Returning error to port failed.");
- }
-}
-
-void StartAdvertisingDart(Core* pCore,
- const char* service_id,
- ConnectionOptionsDart options_dart,
- ConnectionRequestInfoDart info_dart,
- Dart_Port result_cb)
-{
- if (!pCore) {
- PostResult(result_cb, Status::Value::kError);
- return;
- }
-
- ConnectionOptions options;
- options.strategy = GetStrategy(options_dart.strategy);
- options.auto_upgrade_bandwidth =
- options_dart.auto_upgrade_bandwidth;
- options.enforce_topology_constraints =
- options_dart.enforce_topology_constraints;
- options.allowed.bluetooth = options_dart.enable_bluetooth;
- options.allowed.ble = options_dart.enable_ble;
- options.low_power = options_dart.use_low_power_mode;
- options.fast_advertisement_service_uuid =
- options_dart.discover_fast_advertisements ?
- "0000FE2C-0000-1000-8000-00805F9B34FB" : "";
- options.allowed.wifi_lan = options_dart.enable_wifi_lan;
- options.allowed.web_rtc = options_dart.enable_web_rtc;
-
- ConnectionRequestInfo info;
- info.endpoint_info = ByteArray(info_dart.endpoint_info);
- info.listener.initiated_cb = [info_dart](const std::string& endpoint_id,
- const ConnectionResponseInfo& connection_info) {
- NEARBY_LOG(INFO, "Advertising initiated: id=%s",
- endpoint_id.c_str());
- Dart_CObject dart_object_initiated;
- dart_object_initiated.type = Dart_CObject_kString;
- dart_object_initiated.value.as_string =
- (char *)connection_info.remote_endpoint_info.data();
- const bool result =
- Dart_PostCObject_DL(info_dart.initiated_cb,
- &dart_object_initiated);
- if (!result) {
- NEARBY_LOG(INFO,
- "Posting message to port failed.");
- }
- };
- info.listener.accepted_cb = [info_dart](const std::string& endpoint_id) {
- NEARBY_LOG(INFO, "Advertising accepted: id=%s",
- endpoint_id.c_str());
- Dart_CObject dart_object_accepted;
- dart_object_accepted.type = Dart_CObject_kString;
- dart_object_accepted.value.as_string =
- (char *)endpoint_id.c_str();
- const bool result =
- Dart_PostCObject_DL(info_dart.accepted_cb,
- &dart_object_accepted);
- if (!result) {
- NEARBY_LOG(INFO,
- "Posting message to port failed.");
- }
- };
- info.listener.rejected_cb = [info_dart](const std::string& endpoint_id,
- Status status) {
- NEARBY_LOG(INFO, "Advertising rejected: id=%s",
- endpoint_id.c_str());
- Dart_CObject dart_object_rejected;
- dart_object_rejected.type = Dart_CObject_kString;
- dart_object_rejected.value.as_string =
- (char *)endpoint_id.c_str();
- const bool result =
- Dart_PostCObject_DL(info_dart.rejected_cb,
- &dart_object_rejected);
- if (!result) {
- NEARBY_LOG(INFO,
- "Posting message to port failed.");
- }
- };
- info.listener.disconnected_cb = [info_dart](
- const std::string& endpoint_id) {
- NEARBY_LOG(INFO, "Advertising disconnected: id=%s",
- endpoint_id.c_str());
- Dart_CObject dart_object_disconnected;
- dart_object_disconnected.type = Dart_CObject_kString;
- dart_object_disconnected.value.as_string =
- (char *)endpoint_id.c_str();
- const bool result =
- Dart_PostCObject_DL(info_dart.disconnected_cb,
- &dart_object_disconnected);
- if (!result) {
- NEARBY_LOG(INFO,
- "Posting message to port failed.");
- }
- };
- info.listener.bandwidth_changed_cb = [info_dart](
- const std::string& endpoint_id, Medium medium) {
- NEARBY_LOG(INFO, "Advertising bandwidth changed: id=%s",
- endpoint_id.c_str());
- Dart_CObject dart_object_bandwidth_changed;
-
- dart_object_bandwidth_changed.type = Dart_CObject_kString;
- dart_object_bandwidth_changed.value.as_string =
- (char *)endpoint_id.c_str();
- const bool result =
- Dart_PostCObject_DL(info_dart.bandwidth_changed_cb,
- &dart_object_bandwidth_changed);
- if (!result) {
- NEARBY_LOG(INFO,
- "Posting message to port failed.");
- }
- };
-
- ResultCallback callback;
- SetResultCallback(callback, result_cb);
- StartAdvertising(pCore, service_id, options, info, callback);
-}
-
-void StopAdvertisingDart(Core* pCore, Dart_Port result_cb) {
- if (!pCore) {
- PostResult(result_cb, Status::Value::kError);
- return;
- }
-
- ResultCallback callback;
- SetResultCallback(callback, result_cb);
- StopAdvertising(pCore, callback);
-}
-
-void StartDiscoveryDart(Core* pCore,
- const char* service_id,
- ConnectionOptionsDart options_dart,
- DiscoveryListenerDart listener_dart,
- Dart_Port result_cb) {
- if (!pCore) {
- PostResult(result_cb, Status::Value::kError);
- return;
- }
-
- ConnectionOptions options;
- options.strategy = GetStrategy(options_dart.strategy);
- options.allowed.bluetooth = options_dart.enable_bluetooth;
- options.allowed.ble = options_dart.enable_ble;
- options.allowed.wifi_lan = options_dart.enable_wifi_lan;
- options.allowed.web_rtc = false;
- options.low_power = options_dart.use_low_power_mode;
- options.enable_bluetooth_listening =
- options_dart.enable_bluetooth;
- options.enforce_topology_constraints = true;
- options.fast_advertisement_service_uuid =
- options_dart.discover_fast_advertisements ?
- "0000FE2C-0000-1000-8000-00805F9B34FB" : "";
-
- DiscoveryListener listener;
- listener.endpoint_found_cb =
- [listener_dart](const std::string& endpoint_id,
- const ByteArray& endpoint_info,
- const std::string& str_service_id) {
- NEARBY_LOG(INFO, "Device discovered: id=%s",
- endpoint_id.c_str());
- NEARBY_LOG(INFO, "Device discovered: service_id=%s",
- str_service_id.c_str());
- NEARBY_LOG(INFO, "Device discovered: info=%s",
- ((string)endpoint_info).c_str());
-
- Dart_CObject dart_object_endpoint_id;
- dart_object_endpoint_id.type = Dart_CObject_kString;
- dart_object_endpoint_id.value.as_string =
- (char *)endpoint_id.data();
-
- Dart_CObject dart_object_endpoint_info;
- dart_object_endpoint_info.type = Dart_CObject_kString;
- dart_object_endpoint_info.value.as_string =
- (char *)endpoint_info.data();
-
- Dart_CObject* elements[2];
- elements[0] = &dart_object_endpoint_id;
- elements[1] = &dart_object_endpoint_info;
-
- Dart_CObject dart_object_found;
- dart_object_found.type = Dart_CObject_kArray;
- dart_object_found.value.as_array.length = 2;
- dart_object_found.value.as_array.values = elements;
- const bool result =
- Dart_PostCObject_DL(listener_dart.found_cb,
- &dart_object_found);
- if (!result) {
- NEARBY_LOG(INFO,
- "Posting message to port failed.");
- }
- };
- listener.endpoint_lost_cb =
- [listener_dart](const std::string& endpoint_id) {
- NEARBY_LOG(INFO, "Device lost: id=%s",
- endpoint_id.c_str());
- Dart_CObject dart_object_lost;
- dart_object_lost.type = Dart_CObject_kString;
- dart_object_lost.value.as_string =
- (char *)endpoint_id.c_str();
- const bool result =
- Dart_PostCObject_DL(listener_dart.lost_cb,
- &dart_object_lost);
- if (!result) {
- NEARBY_LOG(INFO,
- "Posting message to port failed.");
- }
- };
- listener.endpoint_distance_changed_cb =
- [listener_dart](const std::string& endpoint_id,
- DistanceInfo info) {
- NEARBY_LOG(INFO, "Device distance changed: id=%s",
- endpoint_id.c_str());
- Dart_CObject dart_object_distance_changed;
- dart_object_distance_changed.type =
- Dart_CObject_kString;
- dart_object_distance_changed.value.as_string =
- (char *)(endpoint_id.c_str());
- const bool result =
- Dart_PostCObject_DL(
- listener_dart.distance_changed_cb,
- &dart_object_distance_changed);
- if (!result) {
- NEARBY_LOG(INFO,
- "Posting message to port failed.");
- }
- };
-
- ResultCallback callback;
- SetResultCallback(callback, result_cb);
- StartDiscovery(pCore, service_id, options, listener, callback);
-}
-
-void StopDiscoveryDart(Core* pCore, Dart_Port result_cb) {
- if (!pCore) {
- PostResult(result_cb, Status::Value::kError);
- return;
- }
-
- ResultCallback callback;
- SetResultCallback(callback, result_cb);
- StopDiscovery(pCore, callback);
-}
-
-void RequestConnectionDart(Core* pCore,
- const char* endpoint_id,
- ConnectionOptionsDart options_dart,
- ConnectionRequestInfoDart info_dart,
- Dart_Port result_cb) {
- if (!pCore) {
- PostResult(result_cb, Status::Value::kError);
- return;
- }
-
- ConnectionOptions options;
- options.enforce_topology_constraints = false;
- options.allowed.bluetooth = options_dart.enable_bluetooth;
- options.allowed.ble = options_dart.enable_ble;
- options.allowed.wifi_lan = options_dart.enable_wifi_lan;
- options.allowed.web_rtc = options_dart.enable_web_rtc;
-
- ConnectionRequestInfo info;
- info.endpoint_info = ByteArray(info_dart.endpoint_info);
- info.listener.initiated_cb = [info_dart](const std::string& endpoint_id,
- const ConnectionResponseInfo& connection_info) {
- NEARBY_LOG(INFO, "Advertising initiated: id=%s",
- endpoint_id.c_str());
- Dart_CObject dart_object_initiated;
- dart_object_initiated.type = Dart_CObject_kString;
- dart_object_initiated.value.as_string =
- (char *)connection_info.remote_endpoint_info.data();
- const bool result =
- Dart_PostCObject_DL(info_dart.initiated_cb,
- &dart_object_initiated);
- if (!result) {
- NEARBY_LOG(INFO,
- "Posting message to port failed.");
- }
- };
- info.listener.accepted_cb = [info_dart](const std::string& endpoint_id) {
- NEARBY_LOG(INFO, "Advertising accepted: id=%s",
- endpoint_id.c_str());
- Dart_CObject dart_object_accepted;
- dart_object_accepted.type = Dart_CObject_kString;
- dart_object_accepted.value.as_string =
- (char *)endpoint_id.c_str();
- const bool result =
- Dart_PostCObject_DL(info_dart.accepted_cb,
- &dart_object_accepted);
- if (!result) {
- NEARBY_LOG(INFO,
- "Posting message to port failed.");
- }
- };
- info.listener.rejected_cb = [info_dart](const std::string& endpoint_id,
- Status status) {
- NEARBY_LOG(INFO, "Advertising rejected: id=%s",
- endpoint_id.c_str());
- Dart_CObject dart_object_rejected;
- dart_object_rejected.type = Dart_CObject_kString;
- dart_object_rejected.value.as_string =
- (char *)endpoint_id.c_str();
- const bool result =
- Dart_PostCObject_DL(info_dart.rejected_cb,
- &dart_object_rejected);
- if (!result) {
- NEARBY_LOG(INFO,
- "Posting message to port failed.");
- }
- };
- info.listener.disconnected_cb = [info_dart](
- const std::string& endpoint_id) {
- NEARBY_LOG(INFO, "Advertising disconnected: id=%s",
- endpoint_id.c_str());
- Dart_CObject dart_object_disconnected;
- dart_object_disconnected.type = Dart_CObject_kString;
- dart_object_disconnected.value.as_string =
- (char *)endpoint_id.c_str();
- const bool result =
- Dart_PostCObject_DL(info_dart.disconnected_cb,
- &dart_object_disconnected);
- if (!result) {
- NEARBY_LOG(INFO,
- "Posting message to port failed.");
- }
- };
- info.listener.bandwidth_changed_cb = [info_dart](
- const std::string& endpoint_id, Medium medium) {
- NEARBY_LOG(INFO, "Advertising bandwidth changed: id=%s",
- endpoint_id.c_str());
- Dart_CObject dart_object_bandwidth_changed;
-
- dart_object_bandwidth_changed.type = Dart_CObject_kString;
- dart_object_bandwidth_changed.value.as_string =
- (char *)endpoint_id.c_str();
- const bool result =
- Dart_PostCObject_DL(info_dart.bandwidth_changed_cb,
- &dart_object_bandwidth_changed);
- if (!result) {
- NEARBY_LOG(INFO,
- "Posting message to port failed.");
- }
- };
-
- ResultCallback callback;
- SetResultCallback(callback, result_cb);
- RequestConnection(pCore, endpoint_id, info, options, callback);
-}
-
-void AcceptConnectionDart(Core* pCore,
- const char* endpoint_id,
- PayloadListenerDart listener_dart,
- Dart_Port result_cb) {
- if (!pCore) {
- PostResult(result_cb, Status::Value::kError);
- return;
- }
-
- PayloadListener listener;
- listener.payload_cb = [listener_dart](const std::string& endpoint_id,
- Payload payload) {
- // TODO: pass payload in callback
- Dart_CObject dart_object_payload;
- dart_object_payload.type = Dart_CObject_kString;
- dart_object_payload.value.as_string =
- (char *)endpoint_id.data();
- const bool result =
- Dart_PostCObject_DL(listener_dart.payload_cb,
- &dart_object_payload);
- if (!result) {
- NEARBY_LOG(INFO,
- "Posting message to port failed.");
- }
- };
- listener.payload_progress_cb = [listener_dart](
- const std::string& endpoint_id,
- const PayloadProgressInfo& info) {
- // TODO: pass payload progress info in callback
- Dart_CObject dart_object_payload;
- dart_object_payload.type = Dart_CObject_kString;
- dart_object_payload.value.as_string =
- (char *)endpoint_id.data();
- const bool result =
- Dart_PostCObject_DL(listener_dart.payload_cb,
- &dart_object_payload);
- if (!result) {
- NEARBY_LOG(INFO,
- "Posting message to port failed.");
- }
- };
-
- ResultCallback callback;
- SetResultCallback(callback, result_cb);
- AcceptConnection(pCore, endpoint_id, listener, callback);
-}
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
diff --git a/chromium/third_party/nearby/src/windows/dart/core_adapter_dart.h b/chromium/third_party/nearby/src/windows/dart/core_adapter_dart.h
deleted file mode 100644
index 25a6072fc54..00000000000
--- a/chromium/third_party/nearby/src/windows/dart/core_adapter_dart.h
+++ /dev/null
@@ -1,174 +0,0 @@
-// Copyright 2021 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef LOCATION_NEARBY_CONNECTIONS_WINDOWS_DART_CORE_ADAPTER_DART_H_
-#define LOCATION_NEARBY_CONNECTIONS_WINDOWS_DART_CORE_ADAPTER_DART_H_
-
-#include "third_party/nearby_connections/windows/core_adapter.h"
-
-namespace location {
-namespace nearby {
-namespace connections {
-
-enum StrategyDart {
- P2P_CLUSTER = 0,
- P2P_STAR,
- P2P_POINT_TO_POINT,
-};
-
-struct ConnectionOptionsDart {
- StrategyDart strategy;
- int64_t auto_upgrade_bandwidth;
- int64_t enforce_topology_constraints;
- int64_t enable_bluetooth;
- int64_t enable_ble;
- int64_t advertise_nearby_notifications_beacon;
- int64_t use_low_power_mode;
- int64_t discover_fast_advertisements;
- int64_t enable_wifi_lan;
- int64_t enable_nfc;
- int64_t enable_wifi_aware;
- int64_t enable_web_rtc;
-};
-
-struct ConnectionRequestInfoDart {
- char* endpoint_info;
- int64_t initiated_cb;
- int64_t accepted_cb;
- int64_t rejected_cb;
- int64_t disconnected_cb;
- int64_t bandwidth_changed_cb;
-};
-
-struct DiscoveryListenerDart {
- int64_t found_cb;
- int64_t lost_cb;
- int64_t distance_changed_cb;
-};
-
-struct PayloadListenerDart {
- int64_t payload_cb;
- int64_t payload_progress_cb;
-};
-
-// Starts advertising an endpoint for a local app.
-//
-// service_id - An identifier to advertise your app to other endpoints.
-// This can be an arbitrary string, so long as it uniquely
-// identifies your service. A good default is to use your
-// app's package name.
-// options_dart - options for advertising
-// info_dart - Including callbacks notified when remote
-// endpoints request a connection to this endpoint.
-// result_cb - to access the status of the operation when available.
-// Possible status codes include:
-// Status::STATUS_OK if advertising started successfully.
-// Status::STATUS_ALREADY_ADVERTISING if the app is already advertising.
-// Status::STATUS_OUT_OF_ORDER_API_CALL if the app is currently
-// connected to remote endpoints; call StopAllEndpoints first.
-DLL_EXPORT void __stdcall StartAdvertisingDart(Core* pCore,
- const char* service_id,
- ConnectionOptionsDart options_dart,
- ConnectionRequestInfoDart info_dart,
- Dart_Port result_cb);
-
-// Stops advertising a local endpoint. Should be called after calling
-// StartAdvertising, as soon as the application no longer needs to advertise
-// itself or goes inactive. Payloads can still be sent to connected
-// endpoints after advertising ends.
-//
-// result_cb - to access the status of the operation when available.
-// Possible status codes include:
-// Status::STATUS_OK if none of the above errors occurred.
-DLL_EXPORT void __stdcall StopAdvertisingDart(Core* pCore,
- Dart_Port result_cb);
-
-// Starts discovery for remote endpoints with the specified service ID.
-//
-// service_id - The ID for the service to be discovered, as specified in
-// the corresponding call to StartAdvertising.
-// options - The options for discovery.
-// listener - Callbacks notified when a remote endpoint is discovered.
-// result_cb - to access the status of the operation when available.
-// Possible status codes include:
-// Status::STATUS_OK if discovery started successfully.
-// Status::STATUS_ALREADY_DISCOVERING if the app is already
-// discovering the specified service.
-// Status::STATUS_OUT_OF_ORDER_API_CALL if the app is currently
-// connected to remote endpoints; call StopAllEndpoints first.
-DLL_EXPORT void __stdcall StartDiscoveryDart(Core* pCore,
- const char* service_id,
- ConnectionOptionsDart options_dart,
- DiscoveryListenerDart listener_dart,
- Dart_Port result_cb);
-
-// Stops discovery for remote endpoints, after a previous call to
-// StartDiscovery, when the client no longer needs to discover endpoints or
-// goes inactive. Payloads can still be sent to connected endpoints after
-// discovery ends.
-//
-// result_cb - to access the status of the operation when available.
-// Possible status codes include:
-// Status::STATUS_OK if none of the above errors occurred.
-DLL_EXPORT void __stdcall StopDiscoveryDart(Core* pCore,
- Dart_Port result_cb);
-
-// Sends a request to connect to a remote endpoint.
-//
-// endpoint_id - The identifier for the remote endpoint to which a
-// connection request will be sent. Should match the value
-// provided in a call to
-// DiscoveryListener::endpoint_found_cb()
-// options_dart - The options for connection.
-// info_dart - Connection parameters:
-// > name - A human readable name for the local endpoint, to appear on
-// the remote endpoint.
-// > listener - Callbacks notified when the remote endpoint sends a
-// response to the connection request.
-// result_cb - to access the status of the operation when available.
-// Possible status codes include:
-// Status::STATUS_OK if the connection request was sent.
-// Status::STATUS_ALREADY_CONNECTED_TO_ENDPOINT if the app already
-// has a connection to the specified endpoint.
-// Status::STATUS_RADIO_ERROR if we failed to connect because of an
-// issue with Bluetooth/WiFi.
-// Status::STATUS_ERROR if we failed to connect for any other reason.
-DLL_EXPORT void __stdcall RequestConnectionDart(Core* pCore,
- const char* endpoint_id,
- ConnectionOptionsDart options_dart,
- ConnectionRequestInfoDart info_dart,
- Dart_Port result_cb);
-
-// Accepts a connection to a remote endpoint. This method must be called
-// before Payloads can be exchanged with the remote endpoint.
-//
-// endpoint_id - The identifier for the remote endpoint. Should match the
-// value provided in a call to
-// ConnectionListener::onConnectionInitiated.
-// listener_dart - A callback for payloads exchanged with the remote endpoint.
-// result_cb - to access the status of the operation when available.
-// Possible status codes include:
-// Status::STATUS_OK if the connection request was accepted.
-// Status::STATUS_ALREADY_CONNECTED_TO_ENDPOINT if the app already.
-// has a connection to the specified endpoint.
-DLL_EXPORT void __stdcall AcceptConnectionDart(Core* pCore,
- const char* endpoint_id,
- PayloadListenerDart listener_dart,
- Dart_Port result_cb);
-
-} // namespace connections
-} // namespace nearby
-} // namespace location
-
-#endif // LOCATION_NEARBY_CONNECTIONS_WINDOWS_CORE_ADAPTER_DART_H_