clang-format

This commit is contained in:
Vibhav Pant
2023-08-30 13:21:30 +05:30
parent b34611b77e
commit 808ed3992d
83 changed files with 983 additions and 986 deletions
@@ -15,13 +15,13 @@
#ifndef PLATFORM_IMPL_LINUX_ATOMIC_BOOLEAN_H_
#define PLATFORM_IMPL_LINUX_ATOMIC_BOOLEAN_H_
#include "internal/platform/implementation/atomic_boolean.h"
#include <atomic>
#include "internal/platform/implementation/atomic_boolean.h"
namespace nearby {
namespace linux {
// A boolean value that may be updated atomically.
class AtomicBoolean : public api::AtomicBoolean {
public:
public:
AtomicBoolean(bool initial_value) : atomic_boolean_(initial_value) {}
~AtomicBoolean() override = default;
@@ -31,11 +31,11 @@ public:
// Atomically exchange original value with a new one. Return previous value.
bool Set(bool value) override { return atomic_boolean_.exchange(value); };
private:
private:
std::atomic_bool atomic_boolean_ = false;
};
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif // PLATFORM_IMPL_LINUX_ATOMIC_BOOLEAN_H_
#endif // PLATFORM_IMPL_LINUX_ATOMIC_BOOLEAN_H_
@@ -15,15 +15,15 @@
#ifndef PLATFORM_IMPL_LINUX_ATOMIC_UINT32_H_
#define PLATFORM_IMPL_LINUX_ATOMIC_UINT32_H_
#include "internal/platform/implementation/atomic_reference.h"
#include <atomic>
#include <cstdint>
#include "internal/platform/implementation/atomic_reference.h"
namespace nearby {
namespace linux {
// A boolean value that may be updated atomically.
class AtomicUint32 : public api::AtomicUint32 {
public:
public:
AtomicUint32(std::uint32_t initial_value) : atomic_uint_(initial_value) {}
~AtomicUint32() override = default;
@@ -33,10 +33,10 @@ public:
// Atomically exchange original value with a new one. Return previous value.
void Set(std::uint32_t value) override { atomic_uint_ = value; };
private:
private:
std::atomic_bool atomic_uint_ = false;
};
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif
@@ -41,7 +41,7 @@ void ServiceBrowser::onItemNew(const int32_t &interface,
auto [r_iface, r_protocol, r_name, r_type, r_domain, r_host, r_aprotocol,
r_address, r_port, r_txt, r_flags] =
server_->ResolveService(interface, protocol, name, type, domain,
0, // AVAHI_PROTO_INET
0, // AVAHI_PROTO_INET
0);
info.SetServiceName(r_name);
info.SetIPAddress(r_address);
@@ -83,7 +83,7 @@ void ServiceBrowser::onItemRemove(
auto [r_iface, r_protocol, r_name, r_type, r_domain, r_host, r_aprotocol,
r_address, r_port, r_txt, r_flags] =
server_->ResolveService(interface, protocol, name, type, domain,
0, // AVAHI_PROTO_INET
0, // AVAHI_PROTO_INET
flags);
info.SetServiceName(r_name);
info.SetIPAddress(r_address);
@@ -121,6 +121,6 @@ void ServiceBrowser::onCacheExhausted() {
<< ": notified via ServiceBrowser of cache exhaustion";
}
} // namespace avahi
} // namespace linux
} // namespace nearby
} // namespace avahi
} // namespace linux
} // namespace nearby
+14 -13
View File
@@ -15,14 +15,14 @@
#ifndef PLATFORM_IMPL_LINUX_AVAHI_H_
#define PLATFORM_IMPL_LINUX_AVAHI_H_
#include <memory>
#include <sdbus-c++/IConnection.h>
#include <sdbus-c++/ProxyInterfaces.h>
#include <memory>
#include "internal/platform/implementation/linux/dbus.h"
#include "internal/platform/implementation/linux/generated/dbus/avahi/entrygroup_client.h"
#include "internal/platform/implementation/linux/generated/dbus/avahi/server2_client.h"
#include "internal/platform/implementation/linux/generated/dbus/avahi/servicebrowser_client.h"
#include "internal/platform/implementation/linux/dbus.h"
#include "internal/platform/implementation/wifi_lan.h"
namespace nearby {
@@ -30,21 +30,21 @@ namespace linux {
namespace avahi {
class Server
: public sdbus::ProxyInterfaces<org::freedesktop::Avahi::Server2_proxy> {
public:
public:
Server(sdbus::IConnection &system_bus)
: ProxyInterfaces(system_bus, "org.freedesktop.Avahi", "/") {
registerProxy();
}
~Server() { unregisterProxy(); }
protected:
protected:
void onStateChanged(const int32_t &state, const std::string &error) override {
}
};
class EntryGroup
: public sdbus::ProxyInterfaces<org::freedesktop::Avahi::EntryGroup_proxy> {
public:
public:
EntryGroup(sdbus::IConnection &system_bus,
const sdbus::ObjectPath &entry_group_object_path)
: ProxyInterfaces(system_bus, "org.freedesktop.Avahi",
@@ -64,21 +64,22 @@ public:
unregisterProxy();
}
protected:
protected:
void onStateChanged(const int32_t &state, const std::string &error) override {
}
};
class ServiceBrowser : public sdbus::ProxyInterfaces<
org::freedesktop::Avahi::ServiceBrowser_proxy> {
public:
public:
ServiceBrowser(sdbus::IConnection &system_bus,
const sdbus::ObjectPath &service_browser_object_path,
api::WifiLanMedium::DiscoveredServiceCallback callback,
std::shared_ptr<Server> avahi_server)
: ProxyInterfaces(system_bus, "org.freedesktop.Avahi",
service_browser_object_path),
discovery_cb_(std::move(callback)), server_(avahi_server) {
discovery_cb_(std::move(callback)),
server_(avahi_server) {
registerProxy();
}
~ServiceBrowser() {
@@ -93,7 +94,7 @@ public:
unregisterProxy();
}
protected:
protected:
void onItemNew(const int32_t &interface, const int32_t &protocol,
const std::string &name, const std::string &type,
const std::string &domain, const uint32_t &flags) override;
@@ -104,7 +105,7 @@ protected:
void onAllForNow() override;
void onCacheExhausted() override;
private:
private:
enum LookupResultFlags {
kAvahiLookupResultFlagCached = 1,
kAvahiLookupResultFlagWideArea = 2,
@@ -117,8 +118,8 @@ private:
api::WifiLanMedium::DiscoveredServiceCallback discovery_cb_;
std::shared_ptr<Server> server_;
};
} // namespace avahi
} // namespace linux
} // namespace nearby
} // namespace avahi
} // namespace linux
} // namespace nearby
#endif
@@ -21,7 +21,7 @@ namespace nearby {
namespace linux {
// Container of operations that can be performed over the BLE medium.
class BleMedium : public api::BleMedium {
public:
public:
BleMedium() {}
~BleMedium() = default;
@@ -61,13 +61,13 @@ public:
// Connects to a BLE peripheral.
// On success, returns a new BleSocket.
// On error, returns nullptr.
std::unique_ptr<api::BleSocket>
Connect(api::BlePeripheral &peripheral, const std::string &service_id,
CancellationFlag *cancellation_flag) override {
std::unique_ptr<api::BleSocket> Connect(
api::BlePeripheral &peripheral, const std::string &service_id,
CancellationFlag *cancellation_flag) override {
return nullptr;
}
};
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif
@@ -25,13 +25,13 @@ class BleV2Medium : public api::ble_v2::BleMedium {
api::ble_v2::AdvertiseParameters advertise_set_parameters) override {
return false;
}
std::unique_ptr<AdvertisingSession>
StartAdvertising(const api::ble_v2::BleAdvertisementData &advertising_data,
api::ble_v2::AdvertiseParameters advertise_set_parameters,
AdvertisingCallback callback) override {
std::unique_ptr<AdvertisingSession> StartAdvertising(
const api::ble_v2::BleAdvertisementData &advertising_data,
api::ble_v2::AdvertiseParameters advertise_set_parameters,
AdvertisingCallback callback) override {
return nullptr;
}
bool StopAdvertising() override {return false;}
bool StopAdvertising() override { return false; }
bool StartScanning(const Uuid &service_uuid,
api::ble_v2::TxPowerLevel tx_power_level,
@@ -40,15 +40,14 @@ class BleV2Medium : public api::ble_v2::BleMedium {
}
bool StopScanning() override { return false; }
std::unique_ptr<ScanningSession>
StartScanning(const Uuid &service_uuid,
api::ble_v2::TxPowerLevel tx_power_level,
ScanningCallback callback) override {
std::unique_ptr<ScanningSession> StartScanning(
const Uuid &service_uuid, api::ble_v2::TxPowerLevel tx_power_level,
ScanningCallback callback) override {
return nullptr;
};
std::unique_ptr<api::ble_v2::GattServer>
StartGattServer(api::ble_v2::ServerGattConnectionCallback callback) override {
std::unique_ptr<api::ble_v2::GattServer> StartGattServer(
api::ble_v2::ServerGattConnectionCallback callback) override {
return nullptr;
}
@@ -59,21 +58,18 @@ class BleV2Medium : public api::ble_v2::BleMedium {
return nullptr;
}
std::unique_ptr<api::ble_v2::BleServerSocket>
OpenServerSocket(const std::string &service_id) override {
std::unique_ptr<api::ble_v2::BleServerSocket> OpenServerSocket(
const std::string &service_id) override {
return nullptr;
}
std::unique_ptr<api::ble_v2::BleSocket>
Connect(const std::string &service_id,
api::ble_v2::TxPowerLevel tx_power_level,
api::ble_v2::BlePeripheral &peripheral,
CancellationFlag *cancellation_flag) override {
std::unique_ptr<api::ble_v2::BleSocket> Connect(
const std::string &service_id, api::ble_v2::TxPowerLevel tx_power_level,
api::ble_v2::BlePeripheral &peripheral,
CancellationFlag *cancellation_flag) override {
return nullptr;
}
bool IsExtendedAdvertisementsAvailable() override {
return false;
}
bool IsExtendedAdvertisementsAvailable() override { return false; }
bool GetRemotePeripheral(const std::string &mac_address,
GetRemotePeripheralCallback callback) override {
return false;
@@ -83,7 +79,7 @@ class BleV2Medium : public api::ble_v2::BleMedium {
return false;
}
};
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif
@@ -18,8 +18,8 @@
#include "internal/platform/implementation/bluetooth_adapter.h"
#include "internal/platform/implementation/linux/bluetooth_adapter.h"
#include "internal/platform/implementation/linux/bluez.h"
#include "internal/platform/implementation/linux/generated/dbus/bluez/adapter_client.h"
#include "internal/platform/implementation/linux/dbus.h"
#include "internal/platform/implementation/linux/generated/dbus/bluez/adapter_client.h"
#include "internal/platform/logging.h"
namespace nearby {
@@ -63,26 +63,26 @@ BluetoothAdapter::ScanMode BluetoothAdapter::GetScanMode() const {
bool BluetoothAdapter::SetScanMode(ScanMode scan_mode) {
switch (scan_mode) {
case ScanMode::kConnectable:
return SetStatus(Status::kEnabled);
case ScanMode::kConnectableDiscoverable: {
if (!SetStatus(Status::kEnabled)) {
return false;
}
case ScanMode::kConnectable:
return SetStatus(Status::kEnabled);
case ScanMode::kConnectableDiscoverable: {
if (!SetStatus(Status::kEnabled)) {
return false;
}
try {
bluez_adapter_->Discoverable(true);
} catch (const sdbus::Error &e) {
DBUS_LOG_PROPERTY_SET_ERROR(bluez_adapter_, "Discoverable", e);
return false;
}
try {
bluez_adapter_->Discoverable(true);
} catch (const sdbus::Error &e) {
DBUS_LOG_PROPERTY_SET_ERROR(bluez_adapter_, "Discoverable", e);
return false;
}
return true;
}
case ScanMode::kNone:
return SetStatus(Status::kDisabled);
default:
return false;
return true;
}
case ScanMode::kNone:
return SetStatus(Status::kDisabled);
default:
return false;
}
}
@@ -119,5 +119,5 @@ std::string BluetoothAdapter::GetMacAddress() const {
}
}
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
@@ -20,13 +20,13 @@
#include "absl/strings/string_view.h"
#include "internal/platform/implementation/bluetooth_adapter.h"
#include "internal/platform/implementation/linux/bluez.h"
#include "internal/platform/implementation/linux/generated/dbus/bluez/adapter_client.h"
#include "internal/platform/implementation/linux/dbus.h"
#include "internal/platform/implementation/linux/generated/dbus/bluez/adapter_client.h"
namespace nearby {
namespace linux {
class BluezAdapter : public sdbus::ProxyInterfaces<org::bluez::Adapter1_proxy> {
public:
public:
BluezAdapter(sdbus::IConnection &system_bus,
const sdbus::ObjectPath &adapter_object_path)
: ProxyInterfaces(system_bus, bluez::SERVICE_DEST, adapter_object_path) {
@@ -36,7 +36,7 @@ public:
};
class BluetoothAdapter : public api::BluetoothAdapter {
public:
public:
BluetoothAdapter(sdbus::IConnection &system_bus,
const sdbus::ObjectPath &adapter_object_path)
: bluez_adapter_(
@@ -81,11 +81,11 @@ public:
BluezAdapter &GetBluezAdapterObject() { return *bluez_adapter_; }
private:
private:
std::unique_ptr<BluezAdapter> bluez_adapter_;
bool persist_name_;
};
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif // PLATFORM_IMPL_LINUX_BLUETOOTH_ADAPTER_H_
#endif // PLATFORM_IMPL_LINUX_BLUETOOTH_ADAPTER_H_
@@ -16,11 +16,11 @@
#include <map>
#include <memory>
#include <optional>
#include <sdbus-c++/Error.h>
#include <string>
#include <tuple>
#include <sdbus-c++/AdaptorInterfaces.h>
#include <sdbus-c++/Error.h>
#include <sdbus-c++/IConnection.h>
#include <sdbus-c++/IObject.h>
#include <sdbus-c++/IProxy.h>
@@ -172,10 +172,9 @@ void ProfileManager::Unregister(absl::string_view service_uuid) {
// Get a service record FD for a connected profile (identified by service_uuid)
// to the given device.
std::optional<sdbus::UnixFd>
ProfileManager::GetServiceRecordFD(api::BluetoothDevice &remote_device,
absl::string_view service_uuid,
CancellationFlag *cancellation_flag) {
std::optional<sdbus::UnixFd> ProfileManager::GetServiceRecordFD(
api::BluetoothDevice &remote_device, absl::string_view service_uuid,
CancellationFlag *cancellation_flag) {
if (!ProfileRegistered(service_uuid)) {
NEARBY_LOGS(ERROR) << __func__ << ": Service " << service_uuid
<< " is not registered";
@@ -245,8 +244,7 @@ ProfileManager::GetServiceRecordFD(absl::string_view service_uuid) {
auto mac_addr = it->first;
auto [fd, properties] = it->second.back();
it->second.pop_back();
if (it->second.empty())
profile->connections_.erase(it);
if (it->second.empty()) profile->connections_.erase(it);
profile->connections_lock_.Unlock();
auto maybe_device = devices_.get_device_by_address(mac_addr);
@@ -259,5 +257,5 @@ ProfileManager::GetServiceRecordFD(absl::string_view service_uuid) {
return std::pair(*maybe_device, fd);
}
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
@@ -165,5 +165,5 @@ void MonitoredBluetoothDevice::onPropertiesChanged(
}
}
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
@@ -33,28 +33,27 @@ namespace linux {
class BluetoothDevice
: public api::BluetoothDevice,
public sdbus::ProxyInterfaces<org::bluez::Device1_proxy> {
public:
BluetoothDevice(const BluetoothDevice &) = delete;
BluetoothDevice(BluetoothDevice &&) = delete;
BluetoothDevice &operator=(const BluetoothDevice &) = delete;
BluetoothDevice &operator=(BluetoothDevice &&) = delete;
BluetoothDevice(sdbus::IConnection &system_bus, sdbus::ObjectPath device_object_path);
~BluetoothDevice() override {
unregisterProxy();
}
public:
BluetoothDevice(const BluetoothDevice &) = delete;
BluetoothDevice(BluetoothDevice &&) = delete;
BluetoothDevice &operator=(const BluetoothDevice &) = delete;
BluetoothDevice &operator=(BluetoothDevice &&) = delete;
BluetoothDevice(sdbus::IConnection &system_bus,
sdbus::ObjectPath device_object_path);
~BluetoothDevice() override { unregisterProxy(); }
// https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#getName()
std::string GetName() const override;
// 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;
// Returns BT MAC address assigned to this device.
std::string GetMacAddress() const override;
bool ConnectToProfile(absl::string_view service_uuid);
bool ConnectToProfile(absl::string_view service_uuid);
void set_pair_reply_callback(
absl::AnyInvocable<void(const sdbus::Error *)> cb) {
absl::MutexLock l(&pair_callback_lock_);
on_pair_reply_cb_ = std::move(cb);
void set_pair_reply_callback(
absl::AnyInvocable<void(const sdbus::Error *)> cb) {
absl::MutexLock l(&pair_callback_lock_);
on_pair_reply_cb_ = std::move(cb);
}
void reset_pair_reply_callback() {
@@ -62,14 +61,14 @@ public:
on_pair_reply_cb_ = DefaultCallback<const sdbus::Error *>();
}
protected:
protected:
void onConnectProfileReply(const sdbus::Error *error) override;
void onPairReply(const sdbus::Error *error) override {
absl::ReaderMutexLock l(&pair_callback_lock_);
on_pair_reply_cb_(error);
};
private:
private:
absl::Mutex pair_callback_lock_;
absl::AnyInvocable<void(const sdbus::Error *)> on_pair_reply_cb_ =
DefaultCallback<const sdbus::Error *>();
@@ -82,7 +81,7 @@ private:
class MonitoredBluetoothDevice final
: public BluetoothDevice,
public sdbus::ProxyInterfaces<sdbus::Properties_proxy> {
public:
public:
using sdbus::ProxyInterfaces<sdbus::Properties_proxy>::registerProxy;
using sdbus::ProxyInterfaces<sdbus::Properties_proxy>::unregisterProxy;
using sdbus::ProxyInterfaces<sdbus::Properties_proxy>::getObjectPath;
@@ -97,17 +96,17 @@ public:
ObserverList<api::BluetoothClassicMedium::Observer> &observers);
~MonitoredBluetoothDevice() override { unregisterProxy(); }
protected:
protected:
void onPropertiesChanged(
const std::string &interfaceName,
const std::map<std::string, sdbus::Variant> &changedProperties,
const std::vector<std::string> &invalidatedProperties) override;
private:
private:
ObserverList<api::BluetoothClassicMedium::Observer> &observers_;
};
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif
@@ -116,7 +116,6 @@ void BluetoothClassicMedium::onInterfacesRemoved(
bool BluetoothClassicMedium::StartDiscovery(
DiscoveryCallback discovery_callback) {
discovery_cb_ = std::move(discovery_callback);
try {
@@ -150,10 +149,9 @@ bool BluetoothClassicMedium::StopDiscovery() {
return true;
}
std::unique_ptr<api::BluetoothSocket>
BluetoothClassicMedium::ConnectToService(api::BluetoothDevice &remote_device,
const std::string &service_uuid,
CancellationFlag *cancellation_flag) {
std::unique_ptr<api::BluetoothSocket> BluetoothClassicMedium::ConnectToService(
api::BluetoothDevice &remote_device, const std::string &service_uuid,
CancellationFlag *cancellation_flag) {
auto device_object_path = bluez::device_object_path(
adapter_->GetObjectPath(), remote_device.GetMacAddress());
if (!profile_manager_->ProfileRegistered(service_uuid)) {
@@ -200,17 +198,16 @@ BluetoothClassicMedium::ListenForService(const std::string &service_name,
new BluetoothServerSocket(*profile_manager_, service_uuid));
}
api::BluetoothDevice *
BluetoothClassicMedium::GetRemoteDevice(const std::string &mac_address) {
api::BluetoothDevice *BluetoothClassicMedium::GetRemoteDevice(
const std::string &mac_address) {
auto device = devices_->get_device_by_address(mac_address);
if (!device.has_value())
return nullptr;
if (!device.has_value()) return nullptr;
return &(device->get());
}
std::unique_ptr<api::BluetoothPairing>
BluetoothClassicMedium::CreatePairing(api::BluetoothDevice &remote_device) {
std::unique_ptr<api::BluetoothPairing> BluetoothClassicMedium::CreatePairing(
api::BluetoothDevice &remote_device) {
auto device = devices_->get_device_by_address(remote_device.GetMacAddress());
if (!device.has_value()) return nullptr;
@@ -218,5 +215,5 @@ BluetoothClassicMedium::CreatePairing(api::BluetoothDevice &remote_device) {
new BluetoothPairing(*adapter_, *device));
}
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
@@ -42,73 +42,75 @@ namespace linux {
class BluetoothClassicMedium final
: public api::BluetoothClassicMedium,
sdbus::ProxyInterfaces<sdbus::ObjectManager_proxy> {
public:
BluetoothClassicMedium(const BluetoothClassicMedium &) = delete;
BluetoothClassicMedium(BluetoothClassicMedium &&) = delete;
BluetoothClassicMedium &operator=(const BluetoothClassicMedium &) = delete;
BluetoothClassicMedium &operator=(BluetoothClassicMedium &&) = delete;
BluetoothClassicMedium(sdbus::IConnection &system_bus,
const sdbus::ObjectPath &adapter_object_path);
~BluetoothClassicMedium() override { unregisterProxy(); };
public:
BluetoothClassicMedium(const BluetoothClassicMedium &) = delete;
BluetoothClassicMedium(BluetoothClassicMedium &&) = delete;
BluetoothClassicMedium &operator=(const BluetoothClassicMedium &) = delete;
BluetoothClassicMedium &operator=(BluetoothClassicMedium &&) = delete;
BluetoothClassicMedium(sdbus::IConnection &system_bus,
const sdbus::ObjectPath &adapter_object_path);
~BluetoothClassicMedium() override { unregisterProxy(); };
// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#startDiscovery()
//
// Returns true once the process of discovery has been initiated.
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;
// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#startDiscovery()
//
// Returns true once the process of discovery has been initiated.
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, returns nullptr.
std::unique_ptr<api::BluetoothSocket> ConnectToService(
api::BluetoothDevice &remote_device, const std::string &service_uuid,
CancellationFlag *cancellation_flag) 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, returns nullptr.
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;
// 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;
// https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#createBond()
//
// Start the bonding (pairing) process with the remote device.
// Return a Bluetooth pairing instance to handle the pairing process with the
// remote device.
std::unique_ptr<api::BluetoothPairing> CreatePairing(
api::BluetoothDevice &remote_device) override;
// https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#createBond()
//
// Start the bonding (pairing) process with the remote device.
// Return a Bluetooth pairing instance to handle the pairing process with the
// remote device.
std::unique_ptr<api::BluetoothPairing> CreatePairing(
api::BluetoothDevice &remote_device) override;
api::BluetoothDevice *GetRemoteDevice(const std::string &mac_address) override;
api::BluetoothDevice *GetRemoteDevice(
const std::string &mac_address) override;
void AddObserver(Observer *observer) override {
observers_.AddObserver(observer);
void AddObserver(Observer *observer) override {
observers_.AddObserver(observer);
};
void RemoveObserver(Observer *observer) override {
observers_.RemoveObserver(observer);
};
protected:
protected:
void onInterfacesAdded(
const sdbus::ObjectPath &objectPath,
const std::map<std::string, std::map<std::string, sdbus::Variant>>
@@ -116,7 +118,7 @@ protected:
void onInterfacesRemoved(const sdbus::ObjectPath &objectPath,
const std::vector<std::string> &interfaces) override;
private:
private:
std::unique_ptr<BluetoothAdapter> adapter_;
std::unique_ptr<BluetoothDevices> devices_;
@@ -126,7 +128,7 @@ private:
ObserverList<Observer> observers_;
};
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif
@@ -12,16 +12,15 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal/platform/implementation/linux/bluetooth_classic_server_socket.h"
#include "absl/strings/str_replace.h"
#include "absl/strings/substitute.h"
#include "internal/platform/exception.h"
#include "internal/platform/implementation/bluetooth_classic.h"
#include "internal/platform/implementation/linux/bluetooth_classic_device.h"
#include "internal/platform/implementation/linux/bluetooth_classic_server_socket.h"
#include "internal/platform/implementation/linux/bluetooth_classic_socket.h"
#include "internal/platform/implementation/linux/bluez.h"
#include "internal/platform/logging.h"
#include <systemd/sd-bus.h>
namespace nearby {
namespace linux {
@@ -46,5 +45,5 @@ Exception BluetoothServerSocket::Close() {
return {Exception::kSuccess};
}
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
@@ -15,40 +15,40 @@
#ifndef PLATFORM_IMPL_LINUX_BLUETOOTH_SERVER_SOCKET_H_
#define PLATFORM_IMPL_LINUX_BLUETOOTH_SERVER_SOCKET_H_
#include "absl/strings/string_view.h"
#include "internal/platform/exception.h"
#include "internal/platform/implementation/bluetooth_classic.h"
#include "internal/platform/implementation/linux/bluetooth_bluez_profile.h"
#include "absl/strings/string_view.h"
namespace nearby {
namespace linux {
class BluetoothServerSocket final : public api::BluetoothServerSocket {
public:
BluetoothServerSocket(ProfileManager &profile_manager,
absl::string_view service_uuid)
: profile_manager_(profile_manager), service_uuid_(service_uuid) {}
public:
BluetoothServerSocket(ProfileManager &profile_manager,
absl::string_view service_uuid)
: profile_manager_(profile_manager), service_uuid_(service_uuid) {}
// 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#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;
// https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html#close()
//
// Returns Exception::kIo on error, Exception::kSuccess otherwise.
Exception Close() override;
private:
private:
ProfileManager &profile_manager_;
std::string service_uuid_;
};
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif
@@ -12,10 +12,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include <unistd.h>
#include <array>
#include <cerrno>
#include <cstdint>
#include <unistd.h>
#include "internal/platform/byte_array.h"
#include "internal/platform/exception.h"
@@ -25,8 +25,7 @@ namespace nearby {
namespace linux {
ExceptionOr<ByteArray> InputStream::Read(std::int64_t size) {
if (!fd_.has_value())
return Exception::kIo;
if (!fd_.has_value()) return Exception::kIo;
char *data = new char[size];
ssize_t ret = read(fd_->get(), data, size);
@@ -42,8 +41,7 @@ ExceptionOr<ByteArray> InputStream::Read(std::int64_t size) {
}
Exception InputStream::Close() {
if (!fd_.has_value())
return Exception{Exception::kIo};
if (!fd_.has_value()) return Exception{Exception::kIo};
auto ret = close(fd_->get()) < 0 ? Exception{Exception::kIo}
: Exception{Exception::kSuccess};
@@ -52,8 +50,7 @@ Exception InputStream::Close() {
}
Exception OutputStream::Write(const ByteArray &data) {
if (!fd_.has_value())
return Exception{Exception::kIo};
if (!fd_.has_value()) return Exception{Exception::kIo};
size_t written = 0;
while (written < data.size()) {
@@ -69,8 +66,7 @@ Exception OutputStream::Write(const ByteArray &data) {
Exception OutputStream::Flush() { return Exception{Exception::kSuccess}; }
Exception OutputStream::Close() {
if (!fd_.has_value())
return Exception{Exception::kIo};
if (!fd_.has_value()) return Exception{Exception::kIo};
auto ret = close(fd_->get()) < 0 ? Exception{Exception::kIo}
: Exception{Exception::kSuccess};
@@ -85,5 +81,5 @@ Exception BluetoothSocket::Close() {
return Exception{Exception::kSuccess};
}
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
@@ -28,20 +28,20 @@
namespace nearby {
namespace linux {
class BluetoothSocket final : public api::BluetoothSocket {
public:
BluetoothSocket(api::BluetoothDevice &device, sdbus::UnixFd fd)
: device_(device), output_stream_(fd), input_stream_(fd) {}
public:
BluetoothSocket(api::BluetoothDevice &device, sdbus::UnixFd fd)
: device_(device), output_stream_(fd), input_stream_(fd) {}
nearby::InputStream &GetInputStream() override { return input_stream_; }
nearby::OutputStream &GetOutputStream() override { return output_stream_; }
Exception Close() override;
api::BluetoothDevice *GetRemoteDevice() override { return &device_; };
nearby::InputStream &GetInputStream() override { return input_stream_; }
nearby::OutputStream &GetOutputStream() override { return output_stream_; }
Exception Close() override;
api::BluetoothDevice *GetRemoteDevice() override { return &device_; };
private:
private:
api::BluetoothDevice &device_;
OutputStream output_stream_;
InputStream input_stream_;
};
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif
@@ -51,8 +51,8 @@ void BluetoothDevices::remove_device_by_path(
devices_by_path_.erase(device_object_path);
}
BluetoothDevice &
BluetoothDevices::add_new_device(sdbus::ObjectPath device_object_path) {
BluetoothDevice &BluetoothDevices::add_new_device(
sdbus::ObjectPath device_object_path) {
absl::MutexLock l(&devices_by_path_lock_);
auto pair = devices_by_path_.emplace(
std::string(device_object_path),
@@ -60,5 +60,5 @@ BluetoothDevices::add_new_device(sdbus::ObjectPath device_object_path) {
system_bus_, std::move(device_object_path), observers_));
return *pair.first->second;
}
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
@@ -29,22 +29,22 @@
namespace nearby {
namespace linux {
class BluetoothDevices final {
public:
public:
BluetoothDevices(
sdbus::IConnection &system_bus,
sdbus::ObjectPath adapter_object_path,
sdbus::IConnection &system_bus, sdbus::ObjectPath adapter_object_path,
ObserverList<api::BluetoothClassicMedium::Observer> &observers)
: system_bus_(system_bus), observers_(observers),
: system_bus_(system_bus),
observers_(observers),
adapter_object_path_(std::move(adapter_object_path)) {}
std::optional<std::reference_wrapper<BluetoothDevice>>
get_device_by_path(const sdbus::ObjectPath &);
std::optional<std::reference_wrapper<BluetoothDevice>>
get_device_by_address(const std::string &);
std::optional<std::reference_wrapper<BluetoothDevice>> get_device_by_path(
const sdbus::ObjectPath &);
std::optional<std::reference_wrapper<BluetoothDevice>> get_device_by_address(
const std::string &);
void remove_device_by_path(const sdbus::ObjectPath &);
BluetoothDevice &add_new_device(sdbus::ObjectPath);
private:
private:
absl::Mutex devices_by_path_lock_;
std::map<std::string, std::unique_ptr<MonitoredBluetoothDevice>>
devices_by_path_;
@@ -53,7 +53,7 @@ private:
ObserverList<api::BluetoothClassicMedium::Observer> &observers_;
sdbus::ObjectPath adapter_object_path_;
};
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif
@@ -61,7 +61,7 @@ void BluetoothPairing::pairing_reply_handler(const sdbus::Error *error) {
}
BluetoothPairing::BluetoothPairing(BluetoothAdapter &adapter,
BluetoothDevice &remote_device)
BluetoothDevice &remote_device)
: device_(remote_device), adapter_(adapter) {}
bool BluetoothPairing::InitiatePairing(
@@ -112,7 +112,7 @@ bool BluetoothPairing::CancelPairing() {
}
bool BluetoothPairing::Unpair() {
try {
try {
adapter_.RemoveDeviceByObjectPath(device_.getObjectPath());
return true;
} catch (const sdbus::Error &e) {
@@ -137,5 +137,5 @@ bool BluetoothPairing::IsPaired() {
return false;
}
}
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
@@ -30,7 +30,7 @@
namespace nearby {
namespace linux {
class BluetoothPairing final : public api::BluetoothPairing {
public:
public:
BluetoothPairing(BluetoothAdapter &adapter, BluetoothDevice &remote_device);
bool InitiatePairing(api::BluetoothPairingCallback pairing_cb) override;
@@ -39,7 +39,7 @@ public:
bool Unpair() override;
bool IsPaired() override;
private:
private:
void pairing_reply_handler(const sdbus::Error *e);
sdbus::PendingAsyncCall pair_async_call_;
@@ -49,7 +49,7 @@ private:
api::BluetoothPairingCallback pairing_cb_;
};
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif
@@ -12,11 +12,11 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include "absl/strings/substitute.h"
#include "absl/strings/string_view.h"
#include "absl/strings/str_replace.h"
#include "internal/platform/implementation/linux/bluez.h"
#include <sdbus-c++/Types.h>
#include "absl/strings/str_replace.h"
#include "absl/strings/string_view.h"
#include "absl/strings/substitute.h"
namespace nearby {
namespace linux {
@@ -36,6 +36,6 @@ sdbus::ObjectPath adapter_object_path(absl::string_view name) {
return absl::Substitute("/org/bluez/$0", name);
}
} // namespace bluez
} // namespace linux
} // namespace nearby
} // namespace bluez
} // namespace linux
} // namespace nearby
+18 -19
View File
@@ -23,12 +23,12 @@
#include <string>
#define BLUEZ_LOG_METHOD_CALL_ERROR(proxy, method, err) \
do { \
NEARBY_LOGS(ERROR) << __func__ << ": Got error '" << (err).getName() \
<< "' with message '" << (err).getMessage() \
<< "' while calling " << method << " on object " \
<< (proxy)->getObjectPath(); \
#define BLUEZ_LOG_METHOD_CALL_ERROR(proxy, method, err) \
do { \
NEARBY_LOGS(ERROR) << __func__ << ": Got error '" << (err).getName() \
<< "' with message '" << (err).getMessage() \
<< "' while calling " << method << " on object " \
<< (proxy)->getObjectPath(); \
} while (false)
namespace nearby {
@@ -44,35 +44,34 @@ static constexpr const char *DEVICE_PROP_ALIAS = "Alias";
static constexpr const char *DEVICE_PROP_PAIRED = "Paired";
static constexpr const char *DEVICE_PROP_CONNECTED = "Connected";
std::string
device_object_path(const sdbus::ObjectPath &adapter_object_path,
absl::string_view mac_address);
std::string device_object_path(const sdbus::ObjectPath &adapter_object_path,
absl::string_view mac_address);
sdbus::ObjectPath profile_object_path(absl::string_view service_uuid);
sdbus::ObjectPath profile_object_path(absl::string_view service_uuid);
sdbus::ObjectPath adapter_object_path(absl::string_view name);
sdbus::ObjectPath adapter_object_path(absl::string_view name);
class BluezObjectManager
: public sdbus::ProxyInterfaces<sdbus::ObjectManager_proxy> {
public:
public:
BluezObjectManager(sdbus::IConnection &system_bus)
: ProxyInterfaces(system_bus, "org.bluez", "/") {
registerProxy();
}
~BluezObjectManager() { unregisterProxy(); }
protected:
protected:
void onInterfacesAdded(
const sdbus::ObjectPath &objectPath,
const std::map<std::string, std::map<std::string, sdbus::Variant>>
&interfacesAndProperties) override {}
void
onInterfacesRemoved(const sdbus::ObjectPath &objectPath,
const std::vector<std::string> &interfaces) override {}
void onInterfacesRemoved(
const sdbus::ObjectPath &objectPath,
const std::vector<std::string> &interfaces) override {}
};
} // namespace bluez
} // namespace linux
} // namespace nearby
} // namespace bluez
} // namespace linux
} // namespace nearby
#endif
@@ -23,7 +23,7 @@
namespace nearby {
namespace linux {
class ConditionVariable : public api::ConditionVariable {
public:
public:
explicit ConditionVariable(api::Mutex *mutex)
: mutex_(static_cast<Mutex *>(mutex)->GetRegularMutex()) {}
~ConditionVariable() = default;
@@ -40,11 +40,11 @@ public:
void Notify() override { cond_var_.SignalAll(); }
private:
private:
absl::Mutex *mutex_;
absl::CondVar cond_var_;
};
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif // PLATFORM_IMPL_LINUX_CONDITION_VARIABLE_H_
#endif // PLATFORM_IMPL_LINUX_CONDITION_VARIABLE_H_
@@ -14,7 +14,7 @@
#include "internal/platform/implementation/linux/condition_variable.h"
#include <future> // NOLINT
#include <future> // NOLINT
#include "absl/time/clock.h"
#include "internal/platform/exception.h"
@@ -28,12 +28,10 @@ class ConditionVariableTests : public testing::Test {
public:
ConditionVariableTest() {}
std::future<bool> WaitForEvent(bool timedWait, // NOLINT
std::future<bool> WaitForEvent(bool timedWait, // NOLINT
const absl::Duration* timeout) {
return std::async(
std::launch::async,
[this, timedWait, timeout]() mutable -> bool {
std::launch::async, [this, timedWait, timeout]() mutable -> bool {
if (timedWait == true) {
auto result = this->condition_variable_actual_.Wait(*timeout);
if (result.value == nearby::Exception::kSuccess) {
@@ -31,7 +31,7 @@ class CountDownLatchTests : public testing::Test {
class CountDownLatchTest {
public:
static unsigned int ThreadProcCountDown(void *lpParam) {
static unsigned int ThreadProcCountDown(void* lpParam) {
TestData* testData = static_cast<TestData*>(lpParam);
sleep(1);
@@ -42,7 +42,7 @@ class CountDownLatchTests : public testing::Test {
return 0;
}
static unsigned int ThreadProcAwait(void *lpParam) {
static unsigned int ThreadProcAwait(void* lpParam) {
TestData* testData = static_cast<TestData*>(lpParam);
sleep(1);
@@ -125,7 +125,7 @@ TEST_F(CountDownLatchTests, CountDownLatchAwaitNoTimeoutSucceeds) {
threads.emplace_back(CountDownLatchTest::ThreadProcAwait, &testData);
}
for (auto &thread : threads) {
for (auto& thread : threads) {
thread.join();
}
// Act
@@ -139,8 +139,8 @@ TEST_F(CountDownLatchTests, CountDownLatchAwaitNoTimeoutSucceeds) {
}
void test(std::string str) {
std::cout << str << std::endl;
return;
std::cout << str << std::endl;
return;
}
TEST_F(CountDownLatchTests, CountDownLatchCountDownBeforeAwaitSucceeds) {
@@ -158,4 +158,3 @@ TEST_F(CountDownLatchTests, CountDownLatchCountDownBeforeAwaitSucceeds) {
// Assert
EXPECT_EQ(count, 1);
}
@@ -50,15 +50,15 @@ class CredentialStorage : public api::CredentialStorage {
absl::string_view account_name,
nearby::internal::LocalCredential credential,
SaveCredentialsResultCallback callback) override;
void
GetPublicCredentials(const CredentialSelector &credential_selector,
PublicCredentialType public_credential_type,
GetPublicCredentialsResultCallback callback) override;
void GetPublicCredentials(
const CredentialSelector &credential_selector,
PublicCredentialType public_credential_type,
GetPublicCredentialsResultCallback callback) override;
private:
private:
std::unique_ptr<sdbus::IProxy> proxy;
};
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif
@@ -12,13 +12,13 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include <memory>
#include <cassert>
#include <memory>
#include <sdbus-c++/IConnection.h>
#include "internal/platform/implementation/linux/dbus.h"
#include "absl/base/call_once.h"
#include "internal/platform/implementation/linux/dbus.h"
namespace nearby {
namespace linux {
@@ -29,8 +29,7 @@ static std::unique_ptr<sdbus::IConnection> global_default_bus_connection =
static absl::once_flag bus_connection_init_;
static void initBusConnections() {
global_system_bus_connection =
sdbus::createSystemBusConnection();
global_system_bus_connection = sdbus::createSystemBusConnection();
global_system_bus_connection->enterEventLoopAsync();
global_default_bus_connection =
sdbus::createDefaultBusConnection("com.google.nearby");
@@ -47,5 +46,5 @@ sdbus::IConnection &getDefaultBusConnection() {
assert(global_default_bus_connection != nullptr);
return *global_default_bus_connection;
}
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
+21 -21
View File
@@ -15,37 +15,37 @@
#ifndef PLATFORM_IMPL_LINUX_DBUS_H_
#define PLATFORM_IMPL_LINUX_DBUS_H_
#include "internal/platform/logging.h"
#include <sdbus-c++/IConnection.h>
#include "internal/platform/logging.h"
#define DBUS_LOG_METHOD_CALL_ERROR(p, m, e) \
do { \
NEARBY_LOGS(ERROR) << __func__ << ": Got error '" << (e).getName() \
<< "' with message '" << (e).getMessage() \
<< "' while calling " << (m) << " on object " \
<< (p)->getObjectPath(); \
#define DBUS_LOG_METHOD_CALL_ERROR(p, m, e) \
do { \
NEARBY_LOGS(ERROR) << __func__ << ": Got error '" << (e).getName() \
<< "' with message '" << (e).getMessage() \
<< "' while calling " << (m) << " on object " \
<< (p)->getObjectPath(); \
} while (false)
#define DBUS_LOG_PROPERTY_GET_ERROR(p, prop, e) \
do { \
NEARBY_LOGS(ERROR) << __func__ << ": Got error '" << (e).getName() \
<< "' with message '" << (e).getMessage() \
<< "' while getting property " << (prop) \
<< " on object " << (p)->getObjectPath(); \
#define DBUS_LOG_PROPERTY_GET_ERROR(p, prop, e) \
do { \
NEARBY_LOGS(ERROR) << __func__ << ": Got error '" << (e).getName() \
<< "' with message '" << (e).getMessage() \
<< "' while getting property " << (prop) \
<< " on object " << (p)->getObjectPath(); \
} while (false)
#define DBUS_LOG_PROPERTY_SET_ERROR(p, prop, e) \
do { \
NEARBY_LOGS(ERROR) << __func__ << ": Got error '" << (e).getName() \
<< "' with message '" << (e).getMessage() \
<< "' while setting property " << (prop) \
<< " on object " << (p)->getObjectPath(); \
#define DBUS_LOG_PROPERTY_SET_ERROR(p, prop, e) \
do { \
NEARBY_LOGS(ERROR) << __func__ << ": Got error '" << (e).getName() \
<< "' with message '" << (e).getMessage() \
<< "' while setting property " << (prop) \
<< " on object " << (p)->getObjectPath(); \
} while (false)
namespace nearby {
namespace linux {
extern sdbus::IConnection &getSystemBusConnection();
extern sdbus::IConnection &getDefaultBusConnection();
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif
@@ -12,12 +12,12 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include <pwd.h>
#include <sys/types.h>
#include <cstdlib>
#include <cstring>
#include <optional>
#include <pwd.h>
#include <string>
#include <sys/types.h>
#include <sdbus-c++/IConnection.h>
#include <sdbus-c++/IProxy.h>
@@ -166,7 +166,7 @@ bool DeviceInfo::PreventSleep() {
inhibit_fd_ = login_manager_->Inhibit("sleep", "Google Nearby",
"Google Nearby", "block");
return true;
} catch (const sdbus::Error& e) {
} catch (const sdbus::Error &e) {
DBUS_LOG_METHOD_CALL_ERROR(login_manager_, "Inhibit", e);
return false;
}
@@ -183,5 +183,5 @@ bool DeviceInfo::AllowSleep() {
return true;
}
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
@@ -83,7 +83,7 @@ class Hostnamed
"/org/freedesktop/hostname1") {
registerProxy();
}
~Hostnamed() { unregisterProxy(); }
~Hostnamed() { unregisterProxy(); }
};
class LoginManager final
@@ -94,7 +94,8 @@ class LoginManager final
LoginManager &operator=(const LoginManager &) = delete;
LoginManager &operator=(LoginManager &&) = delete;
explicit LoginManager(sdbus::IConnection &system_bus)
: ProxyInterfaces(system_bus, "org.freedesktop.login1", "/org/freedesktop/login1") {
: ProxyInterfaces(system_bus, "org.freedesktop.login1",
"/org/freedesktop/login1") {
registerProxy();
}
~LoginManager() { unregisterProxy(); }
@@ -17,8 +17,8 @@
#include <functional>
#include <string>
#include "gtest/gtest.h"
#include "absl/synchronization/notification.h"
#include "gtest/gtest.h"
#include "internal/platform/implementation/device_info.h"
namespace nearby {
@@ -48,5 +48,5 @@ void Executor::Shutdown() {
thread_pool_ = nullptr;
}
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
@@ -15,14 +15,14 @@
#include "internal/platform/implementation/linux/executor.h"
#include <algorithm>
#include <utility>
#include <thread>
#include <utility>
#include "gtest/gtest.h"
#include "absl/synchronization/blocking_counter.h"
#include "absl/synchronization/mutex.h"
#include "absl/synchronization/notification.h"
#include "absl/time/time.h"
#include "gtest/gtest.h"
#include "internal/platform/implementation/linux/test_data.h"
namespace nearby {
@@ -17,11 +17,11 @@
#include <algorithm>
#include <codecvt>
#include <cstddef>
#include <filesystem>
#include <ios>
#include <locale>
#include <memory>
#include <string>
#include <filesystem>
#include "absl/memory/memory.h"
#include "absl/strings/string_view.h"
@@ -40,7 +40,8 @@ std::unique_ptr<IOFile> IOFile::CreateInputFile(
IOFile::IOFile(const absl::string_view file_path, size_t size)
: path_(file_path) {
// Always open input file path as wide string on Linux platform.
file_.open(std::filesystem::path(linux::string_to_wstring(path_)), std::ios::binary | std::ios::in | std::ios::ate);
file_.open(std::filesystem::path(linux::string_to_wstring(path_)),
std::ios::binary | std::ios::in | std::ios::ate);
total_size_ = file_.tellg();
file_.seekg(0);
@@ -54,7 +55,8 @@ IOFile::IOFile(const absl::string_view file_path)
: file_(), path_(file_path), total_size_(0) {
// Always open input file path as wide string on Windows platform.
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
file_.open(std::filesystem::path(converter.from_bytes(path_)), std::ios::binary | std::ios::out);
file_.open(std::filesystem::path(converter.from_bytes(path_)),
std::ios::binary | std::ios::out);
}
ExceptionOr<ByteArray> IOFile::Read(std::int64_t size) {
@@ -23,8 +23,8 @@
#include "absl/strings/str_cat.h"
#include "internal/platform/implementation/linux/dbus.h"
#include "internal/platform/implementation/linux/utils.h"
#include "internal/platform/implementation/linux/device_info.h"
#include "internal/platform/implementation/linux/utils.h"
#include "internal/platform/logging.h"
namespace nearby {
@@ -63,9 +63,8 @@ std::wstring FilePath::GetDownloadPathInternal(std::wstring parent_folder,
// If grabbing the download path fails then we make a custom one
base_path = getenv("HOME");
base_path.append("/Downloads");
}
else {
base_path = download_path.value();
} else {
base_path = download_path.value();
}
// If parent_folder starts with a \\ or /, then strip it
@@ -152,7 +151,8 @@ std::wstring FilePath::CreateOutputFileWithRename(std::wstring path) {
file_name2);
file.clear();
file.open(wstring_to_string(target), std::fstream::binary | std::fstream::in);
file.open(wstring_to_string(target),
std::fstream::binary | std::fstream::in);
}
if (count > 0) {
@@ -186,13 +186,12 @@ void FilePath::SanitizePath(std::wstring& path) {
char kIllegalFileCharacters[] = {'/'};
void FilePath::ReplaceInvalidCharacters(std::wstring& path) {
for (auto &character : path) {
for (auto& character : path) {
// If 0 < character < 32, it's illegal, replace it
if (character > 0 && character < 32) {
NEARBY_LOGS(INFO) << "In path " << wstring_to_string(path)
<< " replaced \'" << std::string(1, character) << "\' with \'"
<< std::string(1, kReplacementChar);
<< " replaced \'" << std::string(1, character)
<< "\' with \'" << std::string(1, kReplacementChar);
character = kReplacementChar;
}
for (auto illegal_character : kIllegalFileCharacters) {
@@ -20,9 +20,9 @@
#include <string>
#include <vector>
#include "gtest/gtest.h"
#include <internal/platform/implementation/linux/device_info.h>
#include <internal/platform/implementation/linux/utils.h>
#include "gtest/gtest.h"
namespace nearby {
namespace linux {
@@ -54,7 +54,9 @@ class FilePathTests : public testing::Test {
protected:
// You can define per-test set-up logic as usual.
FilePathTests() {
default_download_path_ = string_to_wstring(DeviceInfo().GetDownloadPath().value_or(std::string(getenv("HOME")).append("/Downloads")));
default_download_path_ =
string_to_wstring(DeviceInfo().GetDownloadPath().value_or(
std::string(getenv("HOME")).append("/Downloads")));
}
std::wstring default_download_path_;
};
@@ -563,7 +565,8 @@ FileWithIncrementedName) {
// File 1
std::filesystem::remove(output_file_path.c_str());
input_file.open(wstring_to_string(output_file_path), std::ifstream::binary | std::ifstream::in);
input_file.open(wstring_to_string(output_file_path),
std::ifstream::binary | std::ifstream::in);
ASSERT_FALSE(input_file.rdstate() == std::ifstream::goodbit);
}
@@ -615,7 +618,8 @@ ReturnsNextIncrementedFileName) {
std::filesystem::remove(wstring_to_string(output_file2_path).c_str());
input_file.clear();
input_file.open(wstring_to_string(output_file2_path), std::ifstream::binary | std::ifstream::in);
input_file.open(wstring_to_string(output_file2_path),
std::ifstream::binary | std::ifstream::in);
ASSERT_FALSE(input_file.rdstate() == std::ifstream::goodbit);
}
@@ -649,7 +653,8 @@ MultipleDotsReturnsIncrementBeforeFirstDot) {
EXPECT_EQ(expected, actual);
std::filesystem::remove(wstring_to_string(output_file1_path).c_str());
input_file.open(wstring_to_string(output_file1_path), std::ifstream::binary | std::ifstream::in);
input_file.open(wstring_to_string(output_file1_path),
std::ifstream::binary | std::ifstream::in);
ASSERT_FALSE(input_file.rdstate() == std::ifstream::goodbit);
}
@@ -683,7 +688,8 @@ DotsReturnsWithIncrementAtEnd) {
EXPECT_EQ(expected, actual);
std::filesystem::remove(wstring_to_string(output_file1_path).c_str());
input_file.open(wstring_to_string(output_file1_path), std::ifstream::binary | std::ifstream::in);
input_file.open(wstring_to_string(output_file1_path),
std::ifstream::binary | std::ifstream::in);
ASSERT_FALSE(input_file.rdstate() == std::ifstream::goodbit);
}
@@ -751,19 +757,22 @@ AHoleBetweenRenamedFiles) {
// Delete the original file
std::filesystem::remove(wstring_to_string(output_file_path).c_str());
input_file.open(wstring_to_string(output_file_path), std::ifstream::binary | std::ifstream::in);
input_file.open(wstring_to_string(output_file_path),
std::ifstream::binary | std::ifstream::in);
ASSERT_FALSE(input_file.rdstate() == std::ifstream::goodbit);
// Delete the first iteration of the original file
input_file.clear(); // Reset the input_file state
std::filesystem::remove(wstring_to_string(output_file1_path).c_str());
input_file.open(wstring_to_string(output_file1_path), std::ifstream::binary | std::ifstream::in);
input_file.open(wstring_to_string(output_file1_path),
std::ifstream::binary | std::ifstream::in);
ASSERT_FALSE(input_file.rdstate() == std::ifstream::goodbit);
// Delete the third iteration of the original file
input_file.clear(); // Reset the input_file state
std::filesystem::remove(wstring_to_string(output_file3_path).c_str());
input_file.open(wstring_to_string(output_file3_path), std::ifstream::binary | std::ifstream::in);
input_file.open(wstring_to_string(output_file3_path),
std::ifstream::binary | std::ifstream::in);
ASSERT_FALSE(input_file.rdstate() == std::ifstream::goodbit);
}
} // namespace linux
@@ -35,16 +35,14 @@ using ::nearby::api::WebResponse;
} // namespace
HttpLoader::HttpLoader(const nearby::api::WebRequest &request) :
request_(request),
header_data_(open_memstream(&header_strings_, &header_sizeloc_)),
our_header_data_(nullptr),
response_data_(open_memstream(&response_strings_, &response_sizeloc_)),
curl_(curl_easy_init()) {}
HttpLoader::HttpLoader(const nearby::api::WebRequest &request)
: request_(request),
header_data_(open_memstream(&header_strings_, &header_sizeloc_)),
our_header_data_(nullptr),
response_data_(open_memstream(&response_strings_, &response_sizeloc_)),
curl_(curl_easy_init()) {}
HttpLoader::~HttpLoader() {
DisconnectWebServer();
}
HttpLoader::~HttpLoader() { DisconnectWebServer(); }
absl::StatusOr<WebResponse> HttpLoader::GetResponse() {
absl::Status status;
@@ -90,8 +88,7 @@ absl::StatusOr<int> HttpLoader::QueryStatusCode(CURL *file_handle) {
return status_code;
}
absl::StatusOr<std::string> HttpLoader::QueryStatusText(
CURL *request_handle) {
absl::StatusOr<std::string> HttpLoader::QueryStatusText(CURL *request_handle) {
absl::StatusOr<int> status;
std::string status_text;
@@ -102,129 +99,129 @@ absl::StatusOr<std::string> HttpLoader::QueryStatusText(
switch (status.value()) {
case 100:
return "Continue";
return "Continue";
case 101:
return "Switching Protocols";
return "Switching Protocols";
case 102:
return "Processing";
return "Processing";
case 103:
return "Early Hints";
return "Early Hints";
case 200:
return "OK";
return "OK";
case 201:
return "Created";
return "Created";
case 202:
return "Accepted";
return "Accepted";
case 203:
return "Non-Authoritative Information";
return "Non-Authoritative Information";
case 204:
return "No Content";
return "No Content";
case 205:
return "Reset Content";
return "Reset Content";
case 206:
return "Partial Content";
return "Partial Content";
case 207:
return "Multi-Status";
return "Multi-Status";
case 208:
return "Already Reported";
return "Already Reported";
case 226:
return "IM Used";
return "IM Used";
case 300:
return "Multiple Choices";
return "Multiple Choices";
case 301:
return "Moved Permanently";
return "Moved Permanently";
case 302:
return "Found";
return "Found";
case 303:
return "See Other";
return "See Other";
case 304:
return "Not Modified";
return "Not Modified";
case 305:
return "Use Proxy";
return "Use Proxy";
case 307:
return "Temporary Redirect";
return "Temporary Redirect";
case 308:
return "Permanent Redirect";
return "Permanent Redirect";
case 400:
return "Bad Request";
return "Bad Request";
case 401:
return "Unauthorized";
return "Unauthorized";
case 402:
return "Payment Required";
return "Payment Required";
case 403:
return "Forbidden";
return "Forbidden";
case 404:
return "Not Found";
return "Not Found";
case 405:
return "Method Not Allowed";
return "Method Not Allowed";
case 406:
return "Not Acceptable";
return "Not Acceptable";
case 407:
return "Proxy Authentication Required";
return "Proxy Authentication Required";
case 408:
return "Request Timeout";
return "Request Timeout";
case 409:
return "Conflict";
return "Conflict";
case 410:
return "Gone";
return "Gone";
case 411:
return "Lenth Required";
return "Lenth Required";
case 412:
return "Precondition Failed";
return "Precondition Failed";
case 413:
return "Payload Too Large";
return "Payload Too Large";
case 414:
return "URI Too Long";
return "URI Too Long";
case 415:
return "Unsupported Media Type";
return "Unsupported Media Type";
case 416:
return "Range Not Satisfiable";
return "Range Not Satisfiable";
case 417:
return "Expectation Failed";
return "Expectation Failed";
case 418:
return "I'm a teapot!";
return "I'm a teapot!";
case 421:
return "Misdirected Request";
return "Misdirected Request";
case 422:
return "Unprocessable Content";
return "Unprocessable Content";
case 423:
return "Locked";
return "Locked";
case 424:
return "Failed Dependency";
return "Failed Dependency";
case 425:
return "Too Early";
return "Too Early";
case 426:
return "Upgrade Required";
return "Upgrade Required";
case 428:
return "Precondition Required";
return "Precondition Required";
case 429:
return "Too Many Requests";
return "Too Many Requests";
case 431:
return "Request Header Fields Too Large";
return "Request Header Fields Too Large";
case 451:
return "Unavailable For Legal Reasons";
return "Unavailable For Legal Reasons";
case 500:
return "Internal Server Error";
return "Internal Server Error";
case 501:
return "Not Implemented";
return "Not Implemented";
case 502:
return "Bad Gateway";
return "Bad Gateway";
case 503:
return "Service Unavailable";
return "Service Unavailable";
case 504:
return "Gateway Timeout";
return "Gateway Timeout";
case 505:
return "HTTP Version Not Supported";
return "HTTP Version Not Supported";
case 506:
return "Variant Also Negotiates";
return "Variant Also Negotiates";
case 507:
return "Insufficient Storage";
return "Insufficient Storage";
case 508:
return "Loop Detected";
return "Loop Detected";
case 509:
return "Network Authentication Required";
return "Network Authentication Required";
default:
return absl::InternalError("Invalid status code.");
return absl::InternalError("Invalid status code.");
}
}
@@ -234,7 +231,7 @@ HttpLoader::QueryResponseHeaders(CURL *request_handle) {
long header_size;
status = QueryResponseInfo(curl_, CURLINFO_HEADER_SIZE, &header_size);
if (!status.ok()) {
return status;
}
@@ -261,16 +258,16 @@ HttpLoader::QueryResponseHeaders(CURL *request_handle) {
return headers;
}
const nearby::api::WebRequest& HttpLoader::GetRequest() {
return request_;
}
const nearby::api::WebRequest &HttpLoader::GetRequest() { return request_; }
size_t HttpLoader::CurlReadCallback(char *buffer, size_t size, size_t nitems, void *userdata) {
size_t HttpLoader::CurlReadCallback(char *buffer, size_t size, size_t nitems,
void *userdata) {
size_t write_size_max = size * nitems;
size_t write_amount = 0;
for (const auto &str : reinterpret_cast<HttpLoader*>(userdata)->GetRequest().body) {
for (const auto &str :
reinterpret_cast<HttpLoader *>(userdata)->GetRequest().body) {
if (write_amount == write_size_max) {
break;
break;
}
*(buffer + write_amount) = str;
write_amount++;
@@ -279,19 +276,21 @@ size_t HttpLoader::CurlReadCallback(char *buffer, size_t size, size_t nitems, vo
return write_amount;
}
// This function uses the CURL getinfo function to grab info. Each info_level has a different
// type it can return. It would not be feasable to determine the type and return it.
// IT IS UP TO THE CALLER OF THE FUNCTION TO USE THE void* CORRECTLY.
// This function uses the CURL getinfo function to grab info. Each info_level
// has a different type it can return. It would not be feasable to determine the
// type and return it. IT IS UP TO THE CALLER OF THE FUNCTION TO USE THE void*
// CORRECTLY.
absl::Status HttpLoader::QueryResponseInfo(CURL *request_handle,
CURLINFO info_level,
void *info) {
CURLINFO info_level, void *info) {
CURLcode query_result = curl_easy_getinfo(request_handle, info_level, &info);
if (query_result == CURLE_OK) {
return absl::OkStatus();
}
return absl::InvalidArgumentError("Failed to query HTTP information: " + std::string(curl_easy_strerror(query_result)));
return absl::InvalidArgumentError(
"Failed to query HTTP information: " +
std::string(curl_easy_strerror(query_result)));
}
absl::Status HttpLoader::ParseUrl() {
@@ -300,7 +299,8 @@ absl::Status HttpLoader::ParseUrl() {
char *host_name;
char *path;
CURLUcode ret = curl_url_set(url_components, CURLUPART_URL, request_.url.c_str(), CURLU_NON_SUPPORT_SCHEME);
CURLUcode ret = curl_url_set(url_components, CURLUPART_URL,
request_.url.c_str(), CURLU_NON_SUPPORT_SCHEME);
if (ret) {
curl_url_cleanup(url_components);
curl_free(schema);
@@ -310,10 +310,13 @@ absl::Status HttpLoader::ParseUrl() {
schema = nullptr;
host_name = nullptr;
path = nullptr;
return absl::InvalidArgumentError("Invalid URL format: " + std::string(curl_url_strerror(ret)));
return absl::InvalidArgumentError("Invalid URL format: " +
std::string(curl_url_strerror(ret)));
}
ret = curl_url_get(url_components, CURLUPART_SCHEME, &schema, CURLU_URLDECODE | CURLU_URLENCODE | CURLU_DEFAULT_PORT | CURLU_DEFAULT_SCHEME);
ret = curl_url_get(url_components, CURLUPART_SCHEME, &schema,
CURLU_URLDECODE | CURLU_URLENCODE | CURLU_DEFAULT_PORT |
CURLU_DEFAULT_SCHEME);
if (ret) {
curl_url_cleanup(url_components);
curl_free(schema);
@@ -323,10 +326,13 @@ absl::Status HttpLoader::ParseUrl() {
schema = nullptr;
host_name = nullptr;
path = nullptr;
return absl::InvalidArgumentError("Could not parse URL schema: " + std::string(curl_url_strerror(ret)));
return absl::InvalidArgumentError("Could not parse URL schema: " +
std::string(curl_url_strerror(ret)));
}
ret = curl_url_get(url_components, CURLUPART_PATH, &path, CURLU_URLDECODE | CURLU_URLENCODE | CURLU_DEFAULT_PORT | CURLU_DEFAULT_SCHEME);
ret = curl_url_get(url_components, CURLUPART_PATH, &path,
CURLU_URLDECODE | CURLU_URLENCODE | CURLU_DEFAULT_PORT |
CURLU_DEFAULT_SCHEME);
if (ret) {
curl_url_cleanup(url_components);
curl_free(schema);
@@ -336,7 +342,8 @@ absl::Status HttpLoader::ParseUrl() {
schema = nullptr;
host_name = nullptr;
path = nullptr;
return absl::InvalidArgumentError("Could not parse URL path: " + std::string(curl_url_strerror(ret)));
return absl::InvalidArgumentError("Could not parse URL path: " +
std::string(curl_url_strerror(ret)));
}
if (!(schema_ == "http" || schema_ == "https")) {
@@ -378,53 +385,71 @@ absl::Status HttpLoader::ConnectWebServer() {
response_data_ = open_memstream(&response_strings_, &response_sizeloc_);
}
option_return_codes.push_back(curl_easy_setopt(curl_, CURLOPT_NOPROGRESS, 1L));
option_return_codes.push_back(curl_easy_setopt(curl_, CURLOPT_URL, request_.url.c_str()));
option_return_codes.push_back(
curl_easy_setopt(curl_, CURLOPT_NOPROGRESS, 1L));
option_return_codes.push_back(
curl_easy_setopt(curl_, CURLOPT_URL, request_.url.c_str()));
option_return_codes.push_back(curl_easy_setopt(curl_, CURLOPT_PORT, port_));
option_return_codes.push_back(curl_easy_setopt(curl_, CURLOPT_AUTOREFERER, 1L));
option_return_codes.push_back(curl_easy_setopt(curl_, CURLOPT_FOLLOWLOCATION, 1L));
option_return_codes.push_back(curl_easy_setopt(curl_, CURLOPT_USERAGENT, "Mozilla/5.0"));
option_return_codes.push_back(curl_easy_setopt(curl_, CURLOPT_HEADERDATA, header_data_));
option_return_codes.push_back(curl_easy_setopt(curl_, CURLOPT_WRITEDATA, response_data_));
option_return_codes.push_back(
curl_easy_setopt(curl_, CURLOPT_AUTOREFERER, 1L));
option_return_codes.push_back(
curl_easy_setopt(curl_, CURLOPT_FOLLOWLOCATION, 1L));
option_return_codes.push_back(
curl_easy_setopt(curl_, CURLOPT_USERAGENT, "Mozilla/5.0"));
option_return_codes.push_back(
curl_easy_setopt(curl_, CURLOPT_HEADERDATA, header_data_));
option_return_codes.push_back(
curl_easy_setopt(curl_, CURLOPT_WRITEDATA, response_data_));
// Prepare headers
std::string request_headers;
for (const auto& header : request_.headers) {
struct curl_slist *list = curl_slist_append(our_header_data_, std::string(header.first + ": " + header.second).c_str());
for (const auto &header : request_.headers) {
struct curl_slist *list = curl_slist_append(
our_header_data_,
std::string(header.first + ": " + header.second).c_str());
if (list) {
our_header_data_ = list;
}
}
if (!request_headers.empty()) {
option_return_codes.push_back(curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, our_header_data_));
option_return_codes.push_back(
curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, our_header_data_));
}
if (request_.method == "GET") {
option_return_codes.push_back(curl_easy_setopt(curl_, CURLOPT_HTTPGET, 1L));
}
else if (request_.method == "POST") {
option_return_codes.push_back(curl_easy_setopt(curl_, CURLOPT_POSTFIELDSIZE, static_cast<long>(request_.body.size())));
option_return_codes.push_back(curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, request_.body.c_str()));
}
else if (request_.method == "PUT") {
} else if (request_.method == "POST") {
option_return_codes.push_back(curl_easy_setopt(
curl_, CURLOPT_POSTFIELDSIZE, static_cast<long>(request_.body.size())));
option_return_codes.push_back(
curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, request_.body.c_str()));
} else if (request_.method == "PUT") {
option_return_codes.push_back(curl_easy_setopt(curl_, CURLOPT_UPLOAD, 1L));
option_return_codes.push_back(curl_easy_setopt(curl_, CURLOPT_READFUNCTION, CurlReadCallback));
option_return_codes.push_back(curl_easy_setopt(curl_, CURLOPT_READDATA, this));
option_return_codes.push_back(curl_easy_setopt(curl_, (request_.body.size() < std::numeric_limits<long>::max() ? CURLOPT_INFILESIZE : CURLOPT_INFILESIZE_LARGE), request_.body.size()));
option_return_codes.push_back(
curl_easy_setopt(curl_, CURLOPT_READFUNCTION, CurlReadCallback));
option_return_codes.push_back(
curl_easy_setopt(curl_, CURLOPT_READDATA, this));
option_return_codes.push_back(curl_easy_setopt(
curl_,
(request_.body.size() < std::numeric_limits<long>::max()
? CURLOPT_INFILESIZE
: CURLOPT_INFILESIZE_LARGE),
request_.body.size()));
}
else {
NEARBY_LOGS(ERROR) << "Failed to open internet with error "
<< "Invalid request method: " << request_.method << ".";
return absl::FailedPreconditionError("Failed to open internet: Invalid request method.");
} else {
NEARBY_LOGS(ERROR) << "Failed to open internet with error "
<< "Invalid request method: " << request_.method << ".";
return absl::FailedPreconditionError(
"Failed to open internet: Invalid request method.");
}
for (const auto &ret : option_return_codes) {
if (ret) {
NEARBY_LOGS(ERROR) << "Failed to open internet with error "
<< curl_easy_strerror(ret) << ".";
return absl::FailedPreconditionError(absl::StrCat(curl_easy_strerror(ret)));
return absl::FailedPreconditionError(
absl::StrCat(curl_easy_strerror(ret)));
}
}
@@ -432,7 +457,6 @@ absl::Status HttpLoader::ConnectWebServer() {
}
absl::Status HttpLoader::SendRequest() {
CURLcode ret = curl_easy_perform(curl_);
if (ret != CURLE_OK) {
@@ -468,18 +492,20 @@ absl::StatusOr<WebResponse> HttpLoader::ProcessResponse() {
curl_off_t download_size;
CURLcode ret = curl_easy_getinfo(curl_, CURLINFO_SIZE_DOWNLOAD_T, &download_size);
CURLcode ret =
curl_easy_getinfo(curl_, CURLINFO_SIZE_DOWNLOAD_T, &download_size);
if (ret) {
if (download_size != 0) {
// Append data to response
web_response.body.assign(response_strings_, download_size);
} else {
NEARBY_LOGS(ERROR)
<< "Failed to read response from remote web server with error "
<< curl_easy_strerror(ret) << ".";
return absl::FailedPreconditionError(absl::StrCat(curl_easy_strerror(ret)));
}
if (ret) {
if (download_size != 0) {
// Append data to response
web_response.body.assign(response_strings_, download_size);
} else {
NEARBY_LOGS(ERROR)
<< "Failed to read response from remote web server with error "
<< curl_easy_strerror(ret) << ".";
return absl::FailedPreconditionError(
absl::StrCat(curl_easy_strerror(ret)));
}
}
status = HTTPCodeToStatus(web_response.status_code, web_response.status_text);
@@ -15,8 +15,8 @@
#ifndef THIRD_PARTY_NEARBY_INTERNAL_PLATFORM_IMPLEMENTATION_LINUX_HTTP_LOADER_H_
#define THIRD_PARTY_NEARBY_INTERNAL_PLATFORM_IMPLEMENTATION_LINUX_HTTP_LOADER_H_
#include <string>
#include <curl/curl.h>
#include <string>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
@@ -32,18 +32,19 @@ namespace linux {
// WinInet APIs to get HTTP response. The platform handles HTTP/HTTPS sessions.
class HttpLoader {
public:
explicit HttpLoader(const nearby::api::WebRequest& request);
explicit HttpLoader(const nearby::api::WebRequest &request);
~HttpLoader();
absl::StatusOr<nearby::api::WebResponse> GetResponse();
const nearby::api::WebRequest& GetRequest();
const nearby::api::WebRequest &GetRequest();
private:
// Defines the buffer size. It is used to init a buffer for receiving HTTP
// response. The unit is byte.
static constexpr int kReceiveBufferSize = 8 * 1024;
static size_t CurlReadCallback(char *buffer, size_t size, size_t nitems, void *userdata);
static size_t CurlReadCallback(char *buffer, size_t size, size_t nitems,
void *userdata);
absl::Status ConnectWebServer();
absl::Status SendRequest();
@@ -15,9 +15,9 @@
#ifndef PLATFORM_IMPL_LINUX_INPUT_FILE_H_
#define PLATFORM_IMPL_LINUX_INPUT_FILE_H_
#include "internal/platform/implementation/input_file.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/exception.h"
#include "internal/platform/implementation/input_file.h"
namespace nearby {
namespace linux {
@@ -18,9 +18,9 @@
#include "gtest/gtest.h"
#include "internal/platform/exception.h"
#include "internal/platform/payload_id.h"
#include "internal/platform/implementation/linux/test_utils.h"
#include "internal/platform/logging.h"
#include "internal/platform/payload_id.h"
class InputFileTests : public testing::Test {
protected:
@@ -32,9 +32,9 @@ class InputFileTests : public testing::Test {
file_.open(path, std::ios::out);
if (!file_) {
NEARBY_LOG(ERROR,
"Failed to create OutputFile with payloadId: %s and error: %d",
test_utils::GetPayloadPath(payloadId).c_str(), std::strerror(errno));
NEARBY_LOG(
ERROR, "Failed to create OutputFile with payloadId: %s and error: %d",
test_utils::GetPayloadPath(payloadId).c_str(), std::strerror(errno));
}
const char* buffer = TEST_STRING;
@@ -12,6 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include <sys/syslog.h>
#include <cassert>
#include <cstdarg>
#include <cstddef>
@@ -19,7 +20,6 @@
#include <cstdlib>
#include <ctime>
#include <memory>
#include <sys/syslog.h>
#define SD_JOURNAL_SUPPRESS_LOCATION true
#include <systemd/sd-journal.h>
@@ -51,34 +51,34 @@ bool LogMessage::ShouldCreateLogMessage(Severity severity) {
return severity >= global_log_control_->GetLogLevel();
}
} // namespace api
} // namespace api
namespace linux {
static inline google::LogSeverity
ConvertSeverity(api::LogMessage::Severity severity) {
static inline google::LogSeverity ConvertSeverity(
api::LogMessage::Severity severity) {
switch (severity) {
case api::LogMessage::Severity::kWarning:
return google::GLOG_WARNING;
case api::LogMessage::Severity::kError:
return google::GLOG_ERROR;
case api::LogMessage::Severity::kFatal:
return google::GLOG_FATAL;
case api::LogMessage::Severity::kVerbose:
case api::LogMessage::Severity::kInfo:
default:
return google::GLOG_INFO;
case api::LogMessage::Severity::kWarning:
return google::GLOG_WARNING;
case api::LogMessage::Severity::kError:
return google::GLOG_ERROR;
case api::LogMessage::Severity::kFatal:
return google::GLOG_FATAL;
case api::LogMessage::Severity::kVerbose:
case api::LogMessage::Severity::kInfo:
default:
return google::GLOG_INFO;
}
}
static inline int ConvertSeverityToSyslog(google::LogSeverity severity) {
switch (severity) {
case google::GLOG_WARNING:
return LOG_WARNING;
case google::GLOG_ERROR:
return LOG_ERR;
case google::GLOG_FATAL:
return LOG_EMERG;
case google::GLOG_INFO:
default:
return LOG_INFO;
case google::GLOG_WARNING:
return LOG_WARNING;
case google::GLOG_ERROR:
return LOG_ERR;
case google::GLOG_FATAL:
return LOG_EMERG;
case google::GLOG_INFO:
default:
return LOG_INFO;
}
}
@@ -94,24 +94,24 @@ void LogControl::send(google::LogSeverity severity, const char *full_filename,
const struct ::tm *tm_time, const char *message,
size_t message_len) {
switch (log_target_) {
case kJournal:
sd_journal_send("MESSAGE=%s", message, "PRIORITY=%d",
ConvertSeverityToSyslog(severity), "CODE_FILE=%s",
base_filename, "CODE_LINE=%d", line, NULL);
break;
case kSyslog: {
auto str = LogSink::ToString(severity, base_filename, line, tm_time,
message, message_len);
syslog(ConvertSeverityToSyslog(severity), "%s", str.c_str());
break;
}
case kConsole:
default:
absl::MutexLock l(&cout_mutex);
std::cout << LogSink::ToString(severity, base_filename, line, tm_time,
message, message_len)
<< "\n";
break;
case kJournal:
sd_journal_send("MESSAGE=%s", message, "PRIORITY=%d",
ConvertSeverityToSyslog(severity), "CODE_FILE=%s",
base_filename, "CODE_LINE=%d", line, NULL);
break;
case kSyslog: {
auto str = LogSink::ToString(severity, base_filename, line, tm_time,
message, message_len);
syslog(ConvertSeverityToSyslog(severity), "%s", str.c_str());
break;
}
case kConsole:
default:
absl::MutexLock l(&cout_mutex);
std::cout << LogSink::ToString(severity, base_filename, line, tm_time,
message, message_len)
<< "\n";
break;
}
}
@@ -131,5 +131,5 @@ void LogMessage::Print(const char *format, ...) {
std::ostream &LogMessage::Stream() { return log_streamer_.stream(); }
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
@@ -28,7 +28,7 @@ namespace linux {
// See documentation in
// cpp/platform/api/log_message.h
class LogMessage : public api::LogMessage {
public:
public:
LogMessage(const char *file, int line, Severity severity);
~LogMessage() override{};
@@ -36,7 +36,7 @@ public:
std::ostream &Stream() override;
private:
private:
google::LogMessage log_streamer_;
static api::LogMessage::Severity min_log_severity_;
};
@@ -44,7 +44,7 @@ private:
class LogControl
: public sdbus::AdaptorInterfaces<org::freedesktop::LogControl1_adaptor>,
public google::LogSink {
public:
public:
LogControl(sdbus::IConnection &system_bus)
: AdaptorInterfaces(system_bus, "/org/freedesktop/LogControl1"),
severity_(api::LogMessage::LogMessage::Severity::kVerbose),
@@ -57,20 +57,20 @@ public:
LogMessage::Severity GetLogLevel() { return severity_; }
protected:
protected:
std::string LogLevel() override {
switch (severity_) {
case api::LogMessage::Severity::kInfo:
return "info";
case api::LogMessage::Severity::kWarning:
return "warning";
case api::LogMessage::Severity::kError:
return "err";
case api::LogMessage::Severity::kFatal:
return "emerg";
case api::LogMessage::Severity::kVerbose:
default:
return "debug";
case api::LogMessage::Severity::kInfo:
return "info";
case api::LogMessage::Severity::kWarning:
return "warning";
case api::LogMessage::Severity::kError:
return "err";
case api::LogMessage::Severity::kFatal:
return "emerg";
case api::LogMessage::Severity::kVerbose:
default:
return "debug";
}
}
@@ -91,15 +91,15 @@ protected:
std::string LogTarget() override {
switch (log_target_) {
case kKernel:
return "kmsg";
case kJournal:
return "journal";
case kSyslog:
return "syslog";
case kConsole:
default:
return "console";
case kKernel:
return "kmsg";
case kJournal:
return "journal";
case kSyslog:
return "syslog";
case kConsole:
default:
return "console";
}
}
@@ -120,11 +120,11 @@ protected:
const char *base_filename, int line, const struct ::tm *tm_time,
const char *message, size_t message_len) override;
private:
private:
std::atomic<api::LogMessage::Severity> severity_;
std::atomic<enum LogTarget> log_target_;
};
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif // PLATFORM_IMPL_LINUX_LOG_MESSAGE_H_
#endif // PLATFORM_IMPL_LINUX_LOG_MESSAGE_H_
@@ -24,7 +24,7 @@
namespace nearby {
namespace linux {
class ABSL_LOCKABLE Mutex : public api::Mutex {
public:
public:
explicit Mutex(Mode mode) : mode_(mode) {
if (mode == Mode::kRecursive)
mutex_.emplace<std::recursive_mutex>();
@@ -57,14 +57,12 @@ public:
}
}
absl::Mutex *GetRegularMutex() {
return std::get_if<absl::Mutex>(&mutex_);
}
absl::Mutex *GetRegularMutex() { return std::get_if<absl::Mutex>(&mutex_); }
private:
private:
std::variant<absl::Mutex, std::recursive_mutex> mutex_;
Mode mode_;
};
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif
@@ -15,9 +15,9 @@
#ifndef PLATFORM_IMPL_LINUX_OUTPUT_FILE_H_
#define PLATFORM_IMPL_LINUX_OUTPUT_FILE_H_
#include "internal/platform/implementation/output_file.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/exception.h"
#include "internal/platform/implementation/output_file.h"
namespace nearby {
namespace linux {
@@ -13,12 +13,11 @@
// limitations under the License.
#include "internal/platform/implementation/linux/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/platform.h"
#include "internal/platform/implementation/windows/test_utils.h"
#include "internal/platform/payload_id.h"
class OutputFileTests : public testing::Test {
protected:
@@ -33,7 +32,8 @@ class OutputFileTests : public testing::Test {
// You can define per-test tear-down logic as usual.
void TearDown() override {
nearby::PayloadId payloadId(TEST_PAYLOAD_ID);
if (std::filesystem::exists(test_utils::GetPayloadPath(payloadId).c_str())) {
if (std::filesystem::exists(
test_utils::GetPayloadPath(payloadId).c_str())) {
std::filesystem::remove(test_utils::GetPayloadPath(payloadId).c_str());
}
}
@@ -34,9 +34,9 @@
#include "internal/platform/implementation/linux/bluetooth_adapter.h"
#include "internal/platform/implementation/linux/bluetooth_classic_medium.h"
#include "internal/platform/implementation/linux/bluez.h"
#include "internal/platform/implementation/linux/generated/dbus/bluez/adapter_client.h"
#include "internal/platform/implementation/linux/condition_variable.h"
#include "internal/platform/implementation/linux/dbus.h"
#include "internal/platform/implementation/linux/generated/dbus/bluez/adapter_client.h"
#include "internal/platform/implementation/linux/mutex.h"
#include "internal/platform/implementation/linux/preferences_manager.h"
#include "internal/platform/implementation/linux/submittable_executor.h"
@@ -57,41 +57,41 @@
namespace nearby {
namespace api {
std::string
ImplementationPlatform::GetCustomSavePath(const std::string &parent_folder,
const std::string &file_name) {
std::string ImplementationPlatform::GetCustomSavePath(
const std::string &parent_folder, const std::string &file_name) {
auto fs = std::filesystem::path(parent_folder);
return fs / file_name;
}
std::string
ImplementationPlatform::GetDownloadPath(const std::string &parent_folder,
const std::string &file_name) {
std::string ImplementationPlatform::GetDownloadPath(
const std::string &parent_folder, const std::string &file_name) {
auto downloads = std::filesystem::path(getenv("XDG_DOWNLOAD_DIR"));
return downloads / std::filesystem::path(parent_folder).filename() /
std::filesystem::path(file_name).filename();
}
std::string
ImplementationPlatform::GetDownloadPath(const std::string &file_name) {
std::string ImplementationPlatform::GetDownloadPath(
const std::string &file_name) {
auto downloads = std::filesystem::path(getenv("XDG_DOWNLOAD_DIR"));
return downloads / std::filesystem::path(file_name).filename();
}
std::string
ImplementationPlatform::GetAppDataPath(const std::string &file_name) {
std::string ImplementationPlatform::GetAppDataPath(
const std::string &file_name) {
auto state = std::filesystem::path(getenv("XDG_STATE_HOME"));
return state / std::filesystem::path(file_name).filename();
}
OSName ImplementationPlatform::GetCurrentOS() { return OSName::kWindows; }
std::unique_ptr<api::AtomicBoolean> ImplementationPlatform::CreateAtomicBoolean(bool initial_value) {
std::unique_ptr<api::AtomicBoolean> ImplementationPlatform::CreateAtomicBoolean(
bool initial_value) {
return std::make_unique<linux::AtomicBoolean>(initial_value);
}
std::unique_ptr<api::AtomicUint32> ImplementationPlatform::CreateAtomicUint32(std::uint32_t value) {
std::unique_ptr<api::AtomicUint32> ImplementationPlatform::CreateAtomicUint32(
std::uint32_t value) {
return std::make_unique<linux::AtomicUint32>(value);
}
@@ -102,8 +102,8 @@ ImplementationPlatform::CreateCountDownLatch(std::int32_t count) {
#pragma push_macro("CreateMutex")
#undef CreateMutex
std::unique_ptr<api::Mutex>
ImplementationPlatform::CreateMutex(Mutex::Mode mode) {
std::unique_ptr<api::Mutex> ImplementationPlatform::CreateMutex(
Mutex::Mode mode) {
return std::make_unique<linux::Mutex>(mode);
}
#pragma pop_macro("CreateMutex")
@@ -113,26 +113,25 @@ ImplementationPlatform::CreateConditionVariable(api::Mutex *mutex) {
return std::make_unique<linux::ConditionVariable>(mutex);
}
std::unique_ptr<api::InputFile>
ImplementationPlatform::CreateInputFile(PayloadId id, std::int64_t total_size) {
std::unique_ptr<api::InputFile> ImplementationPlatform::CreateInputFile(
PayloadId id, std::int64_t total_size) {
auto path = GetDownloadPath(std::to_string(id));
return nearby::shared::IOFile::CreateInputFile(path, total_size);
}
std::unique_ptr<InputFile>
ImplementationPlatform::CreateInputFile(const std::string &file_path,
size_t size) {
std::unique_ptr<InputFile> ImplementationPlatform::CreateInputFile(
const std::string &file_path, size_t size) {
return nearby::shared::IOFile::CreateInputFile(file_path, size);
}
std::unique_ptr<OutputFile>
ImplementationPlatform::CreateOutputFile(PayloadId payload_id) {
std::unique_ptr<OutputFile> ImplementationPlatform::CreateOutputFile(
PayloadId payload_id) {
return nearby::shared::IOFile::CreateOutputFile(
GetDownloadPath("", std::to_string(payload_id)));
}
std::unique_ptr<OutputFile>
ImplementationPlatform::CreateOutputFile(const std::string &file_path) {
std::unique_ptr<OutputFile> ImplementationPlatform::CreateOutputFile(
const std::string &file_path) {
std::filesystem::path path(file_path);
try {
std::filesystem::create_directories(path.parent_path());
@@ -144,9 +143,8 @@ ImplementationPlatform::CreateOutputFile(const std::string &file_path) {
return nearby::shared::IOFile::CreateOutputFile(path.string());
}
std::unique_ptr<api::LogMessage>
ImplementationPlatform::CreateLogMessage(const char *file, int line,
LogMessage::Severity severity) {
std::unique_ptr<api::LogMessage> ImplementationPlatform::CreateLogMessage(
const char *file, int line, LogMessage::Severity severity) {
return std::make_unique<linux::LogMessage>(file, line, severity);
}
@@ -197,8 +195,8 @@ ImplementationPlatform::CreateBluetoothClassicMedium(
linux::getSystemBusConnection(), path);
}
std::unique_ptr<BleMedium>
ImplementationPlatform::CreateBleMedium(BluetoothAdapter &) {
std::unique_ptr<BleMedium> ImplementationPlatform::CreateBleMedium(
BluetoothAdapter &) {
return std::make_unique<linux::BleMedium>();
}
@@ -207,8 +205,8 @@ ImplementationPlatform::CreateBleV2Medium(api::BluetoothAdapter &adapter) {
return std::make_unique<linux::BleV2Medium>();
}
static std::unique_ptr<linux::NetworkManagerWifiMedium>
createWifiMedium(std::shared_ptr<linux::NetworkManager> nm) {
static std::unique_ptr<linux::NetworkManagerWifiMedium> createWifiMedium(
std::shared_ptr<linux::NetworkManager> nm) {
std::vector<sdbus::ObjectPath> device_paths;
try {
@@ -299,8 +297,8 @@ std::unique_ptr<api::DeviceInfo> ImplementationPlatform::CreateDeviceInfo() {
return std::make_unique<linux::DeviceInfo>(linux::getSystemBusConnection());
}
absl::StatusOr<api::WebResponse>
ImplementationPlatform::SendRequest(const WebRequest &request) {
absl::StatusOr<api::WebResponse> ImplementationPlatform::SendRequest(
const WebRequest &request) {
if (request.body.size() >= (8 * 1024 * 1024)) {
return absl::Status(absl::StatusCode::kResourceExhausted,
"request body too large");
@@ -375,5 +373,5 @@ ImplementationPlatform::CreatePreferencesManager(absl::string_view path) {
}
#endif
} // namespace api
} // namespace nearby
} // namespace api
} // namespace nearby
@@ -12,8 +12,6 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal/platform/implementation/linux/preferences_manager.h"
#include <filesystem> // NOLINT(build/c++17)
#include <memory>
#include <optional>
@@ -22,10 +20,11 @@
#include <vector>
#include "absl/strings/string_view.h"
#include "nlohmann/json.hpp"
#include "nlohmann/json_fwd.hpp"
#include "internal/platform/implementation/linux/preferences_manager.h"
#include "internal/platform/implementation/linux/preferences_repository.h"
#include "internal/platform/logging.h"
#include "nlohmann/json.hpp"
#include "nlohmann/json_fwd.hpp"
namespace nearby {
namespace linux {
@@ -26,10 +26,10 @@
#include "absl/synchronization/mutex.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "internal/platform/implementation/linux/preferences_repository.h"
#include "internal/platform/implementation/preferences_manager.h"
#include "nlohmann/json.hpp"
#include "nlohmann/json_fwd.hpp"
#include "internal/platform/implementation/preferences_manager.h"
#include "internal/platform/implementation/linux/preferences_repository.h"
namespace nearby {
namespace linux {
@@ -12,8 +12,6 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal/platform/implementation/linux/preferences_manager.h"
#include <stdint.h>
#include <codecvt>
@@ -24,14 +22,15 @@
#include <string>
#include <vector>
#include "gtest/gtest.h"
#include "absl/strings/string_view.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "gtest/gtest.h"
#include "internal/platform/implementation/linux/preferences_manager.h"
#include "internal/platform/logging.h"
#include "nlohmann/json.hpp"
#include "nlohmann/json_fwd.hpp"
#include "internal/platform/logging.h"
namespace nearby {
namespace linux {
@@ -41,10 +40,8 @@ constexpr absl::Duration kTimeOut = absl::Milliseconds(200);
constexpr char kPreferencesFilePath[] = "Google/Nearby/Sharing";
} // namespace
TEST(PreferencesManager, CorruptedConfigFile) {
std::filesystem::path settingsPath =
std::filesystem::temp_directory_path();
std::filesystem::path settingsPath = std::filesystem::temp_directory_path();
std::ofstream output_stream{settingsPath / "preferences.json"};
output_stream << "CORRUPTED" << std::endl;
@@ -54,8 +51,7 @@ TEST(PreferencesManager, CorruptedConfigFile) {
}
TEST(PreferencesManager, ValidConfigFile) {
std::filesystem::path settingsPath =
std::filesystem::temp_directory_path();
std::filesystem::path settingsPath = std::filesystem::temp_directory_path();
std::ofstream output_stream{settingsPath / "preferences.json"};
output_stream << "{\"data\":8, \"name\": \"Valid\"}" << std::endl;
output_stream.close();
@@ -11,16 +11,15 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal/platform/implementation/linux/preferences_repository.h"
#include <exception>
#include <filesystem> // NOLINT(build/c++17)
#include <fstream>
#include <optional>
#include "internal/platform/implementation/linux/preferences_repository.h"
#include "internal/platform/logging.h"
#include "nlohmann/json.hpp"
#include "nlohmann/json_fwd.hpp"
#include "internal/platform/logging.h"
namespace nearby {
namespace linux {
@@ -12,17 +12,16 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal/platform/implementation/linux/preferences_repository.h"
#include <filesystem> // NOLINT(build/c++17)
#include <fstream>
#include <optional>
#include "gtest/gtest.h"
#include "nlohmann/json.hpp"
#include "nlohmann/json_fwd.hpp"
#include "internal/platform/implementation/device_info.h"
#include "internal/platform/implementation/platform.h"
#include "nlohmann/json.hpp"
#include "nlohmann/json_fwd.hpp"
#include "internal/platform/implementation/linux/preferences_repository.h"
namespace nearby {
namespace linux {
@@ -32,8 +32,8 @@ ScheduledExecutor::ScheduledExecutor()
// 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) {
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.";
@@ -80,5 +80,5 @@ void ScheduledExecutor::Shutdown() {
NEARBY_LOGS(ERROR) << __func__
<< ": Attempt to Shutdown on a shut down executor.";
}
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
@@ -22,8 +22,8 @@
#include "absl/synchronization/notification.h"
#include "absl/time/time.h"
#include "internal/platform/implementation/cancelable.h"
#include "internal/platform/implementation/scheduled_executor.h"
#include "internal/platform/implementation/linux/executor.h"
#include "internal/platform/implementation/scheduled_executor.h"
namespace nearby {
namespace linux {
@@ -12,16 +12,15 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal/platform/implementation/linux/scheduled_executor.h"
#include <memory>
#include <utility>
#include "gtest/gtest.h"
#include "absl/synchronization/notification.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "gtest/gtest.h"
#include "internal/platform/implementation/linux/test_data.h"
#include "internal/platform/implementation/linux/scheduled_executor.h"
namespace nearby {
namespace linux {
@@ -25,30 +25,30 @@
namespace nearby {
namespace linux {
class InputStream : public nearby::InputStream {
public:
public:
InputStream(sdbus::UnixFd &fd) : fd_(fd){};
ExceptionOr<ByteArray> Read(std::int64_t size) override;
Exception Close() override;
private:
private:
std::optional<sdbus::UnixFd> fd_;
};
class OutputStream : public nearby::OutputStream {
public:
public:
OutputStream(sdbus::UnixFd &fd) : fd_(fd){};
Exception Write(const ByteArray &data) override;
Exception Flush() override;
Exception Close() override;
private:
private:
std::optional<sdbus::UnixFd> fd_;
};
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif
@@ -15,8 +15,8 @@
#ifndef PLATFORM_IMPL_LINUX_SUBMITTABLE_EXECUTOR_H_
#define PLATFORM_IMPL_LINUX_SUBMITTABLE_EXECUTOR_H_
#include "internal/platform/implementation/submittable_executor.h"
#include "internal/platform/implementation/linux/executor.h"
#include "internal/platform/implementation/submittable_executor.h"
namespace nearby {
namespace linux {
@@ -14,13 +14,13 @@
#include "internal/platform/implementation/linux/submittable_executor.h"
#include <utility>
#include <thread>
#include <utility>
#include "gtest/gtest.h"
#include "absl/synchronization/blocking_counter.h"
#include "absl/synchronization/notification.h"
#include "absl/time/time.h"
#include "gtest/gtest.h"
#include "internal/platform/implementation/linux/test_data.h"
namespace nearby {
@@ -20,14 +20,14 @@
namespace nearby {
// Initialize global system state.
void SystemClock::Init() { }
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());
std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch())
.count());
}
// Pauses current thread for the specified duration.
@@ -31,4 +31,3 @@
RUNNABLE_SEPARATOR_TEXT)
#endif // PLATFORM_IMPL_LINUX_TEST_DATA_H_
@@ -12,15 +12,14 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal/platform/implementation/linux/test_utils.h"
#include "internal/platform/implementation/linux/device_info.h"
#include <algorithm>
#include <sstream>
#include <codecvt>
#include <sstream>
#include "absl/strings/str_format.h"
#include "absl/strings/str_replace.h"
#include "internal/platform/implementation/linux/device_info.h"
#include "internal/platform/implementation/linux/test_utils.h"
namespace test_utils {
std::wstring StringToWideString(const std::string& s) {
@@ -29,7 +28,9 @@ std::wstring StringToWideString(const std::string& s) {
}
std::string GetPayloadPath(nearby::PayloadId payload_id) {
std::filesystem::path path = nearby::linux::DeviceInfo().GetDownloadPath().value_or(std::string(getenv("HOME")).append("Downloads"));
std::filesystem::path path =
nearby::linux::DeviceInfo().GetDownloadPath().value_or(
std::string(getenv("HOME")).append("Downloads"));
return path.string();
}
@@ -117,5 +117,5 @@ Runnable ThreadPool::NextTask() {
return task;
}
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
@@ -30,23 +30,23 @@ namespace nearby {
namespace linux {
class ThreadPool {
public:
ThreadPool(const ThreadPool &) = delete;
ThreadPool(ThreadPool &&) = delete;
ThreadPool &operator=(const ThreadPool &) = delete;
ThreadPool &operator=(ThreadPool &&) = delete;
explicit ThreadPool(size_t max_pool_size);
~ThreadPool();
public:
ThreadPool(const ThreadPool &) = delete;
ThreadPool(ThreadPool &&) = delete;
ThreadPool &operator=(const ThreadPool &) = delete;
ThreadPool &operator=(ThreadPool &&) = delete;
explicit ThreadPool(size_t max_pool_size);
~ThreadPool();
bool Start() ABSL_LOCKS_EXCLUDED(mutex_);
bool Start() ABSL_LOCKS_EXCLUDED(mutex_);
// Runs a task on thread pool. The result indicates whether the task is put
// into the thread pool.
bool Run(Runnable &&task) ABSL_LOCKS_EXCLUDED(mutex_);
// Runs a task on thread pool. The result indicates whether the task is put
// into the thread pool.
bool Run(Runnable &&task) ABSL_LOCKS_EXCLUDED(mutex_);
void ShutDown() ABSL_LOCKS_EXCLUDED(mutex_);
void ShutDown() ABSL_LOCKS_EXCLUDED(mutex_);
private:
private:
Runnable NextTask() ABSL_LOCKS_EXCLUDED(mutex_);
size_t max_pool_size_;
@@ -56,7 +56,7 @@ private:
std::vector<std::thread> threads_ ABSL_GUARDED_BY(mutex_);
std::queue<Runnable> tasks_ ABSL_GUARDED_BY(mutex_);
};
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif // PLATFORM_IMPL_LINUX_THREAD_POOL_H_
#endif // PLATFORM_IMPL_LINUX_THREAD_POOL_H_
@@ -12,15 +12,14 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal/platform/implementation/linux/thread_pool.h"
#include <vector>
#include "gtest/gtest.h"
#include "absl/synchronization/blocking_counter.h"
#include "absl/synchronization/notification.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "gtest/gtest.h"
#include "internal/platform/implementation/linux/thread_pool.h"
namespace nearby {
namespace linux {
+12 -14
View File
@@ -13,16 +13,15 @@
// limitations under the License.
#include <bits/types/struct_itimerspec.h>
#include <signal.h>
#include <time.h>
#include <cerrno>
#include <cstring>
#include <ctime>
#include <signal.h>
#include <time.h>
#include "internal/platform/implementation/linux/submittable_executor.h"
#include "internal/platform/implementation/linux/timer.h"
#include "absl/synchronization/mutex.h"
#include "internal/platform/implementation/linux/submittable_executor.h"
#include "internal/platform/implementation/linux/timer.h"
#include "internal/platform/logging.h"
namespace nearby {
@@ -31,8 +30,7 @@ namespace linux {
static void timer_callback(union sigval val) {
absl::AnyInvocable<void()> *callback =
reinterpret_cast<absl::AnyInvocable<void()> *>(val.sival_ptr);
if (*callback != nullptr)
(*callback)();
if (*callback != nullptr) (*callback)();
}
Timer::~Timer() {
@@ -60,11 +58,11 @@ bool Timer::Create(int delay, int interval,
}
callback_ = std::move(callback);
struct sigevent ev;
ev.sigev_value.sival_ptr = &callback_;
ev.sigev_notify_function = timer_callback;
timer_t timerid;
struct itimerspec spec;
@@ -86,7 +84,7 @@ bool Timer::Create(int delay, int interval,
<< std::strerror(errno);
if (!timer_delete(&timerid)) {
NEARBY_LOGS(ERROR) << __func__ << ": error deleting POSIX timer: "
<< std::strerror(errno);
<< std::strerror(errno);
}
return false;
}
@@ -108,7 +106,7 @@ bool Timer::Stop() {
return false;
}
timerid_.reset();
timerid_.reset();
return true;
}
@@ -127,10 +125,10 @@ bool Timer::FireNow() {
task_executor_ = std::make_unique<SubmittableExecutor>();
}
task_executor_->Execute([&]() {callback_();});
task_executor_->Execute([&]() { callback_(); });
return true;
}
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
@@ -15,22 +15,22 @@
#ifndef PLATFORM_IMPL_LINUX_TIMER_H_
#define PLATFORM_IMPL_LINUX_TIMER_H_
#include <signal.h>
#include <time.h>
#include <memory>
#include <optional>
#include <time.h>
#include <signal.h>
#include "absl/base/thread_annotations.h"
#include "absl/synchronization/mutex.h"
#include "internal/platform/implementation/timer.h"
#include "internal/platform/implementation/linux/submittable_executor.h"
#include "internal/platform/implementation/timer.h"
namespace nearby {
namespace linux {
class Timer : public api::Timer {
public:
Timer() : timerid_(nullptr) {} ;
Timer() : timerid_(nullptr){};
~Timer() override;
bool Create(int delay, int interval,
@@ -39,7 +39,7 @@ class Timer : public api::Timer {
bool Stop() override ABSL_LOCKS_EXCLUDED(mutex_);
bool FireNow() override ABSL_LOCKS_EXCLUDED(mutex_);
private:
private:
absl::Mutex mutex_;
std::optional<timer_t> timerid_ ABSL_GUARDED_BY(mutex_);
absl::AnyInvocable<void()> callback_;
+54 -64
View File
@@ -37,10 +37,10 @@
#include "internal/platform/uuid.h"
// Linux headers
#include <netinet/in.h>
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <netdb.h>
#include <netinet/in.h>
namespace nearby {
namespace linux {
@@ -69,10 +69,9 @@ uint64_t mac_address_string_to_uint64(absl::string_view mac_address) {
std::string ipaddr_4bytes_to_dotdecimal_string(
absl::string_view ipaddr_4bytes) {
union addrs {
in_addr_t addr;
uint8_t bits[4];
in_addr_t addr;
uint8_t bits[4];
} address;
address.bits[0] = ipaddr_4bytes[0];
@@ -99,7 +98,7 @@ std::string ipaddr_dotdecimal_to_4bytes_string(std::string ipv4_s) {
struct in_addr addr;
if (inet_aton(ipv4_s.c_str(), &addr) != 0) {
return {};
return {};
}
std::string ipv4_b = std::to_string(addr.s_addr);
@@ -120,75 +119,66 @@ std::string wstring_to_string(std::wstring wstr) {
std::vector<std::string> GetIpv4Addresses() {
std::vector<std::string> result;
struct ifaddrs *interface = nullptr;
struct ifaddrs* interface = nullptr;
char host[NI_MAXHOST];
if (getifaddrs(&interface) != 0) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to get interfaces. Error: "
NEARBY_LOGS(ERROR) << __func__ << ": Failed to get interfaces. Error: "
<< strerror(errno);
freeifaddrs(interface);
return {};
}
int status = 0;
for (struct ifaddrs *ifa = interface; ifa != nullptr; ifa = ifa->ifa_next) {
for (struct ifaddrs* ifa = interface; ifa != nullptr; ifa = ifa->ifa_next) {
if (ifa->ifa_addr->sa_family == AF_INET) {
status = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), host, NI_MAXHOST, nullptr, 0, NI_NUMERICHOST);
status = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), host,
NI_MAXHOST, nullptr, 0, NI_NUMERICHOST);
}
switch (status) {
case EAI_AGAIN:
NEARBY_LOGS(ERROR) << __func__
<< "Failed to get IP for interface: "
<< ifa->ifa_name
<< " : The name could not be resolved at this time. "
<< "Try again later.";
break;
case EAI_BADFLAGS:
NEARBY_LOGS(ERROR) << __func__
<< "Failed to get IP for interface: "
<< ifa->ifa_name
<< " : The flags argument has an invalid value.";
break;
case EAI_FAIL:
NEARBY_LOGS(ERROR) << __func__
<< "Failed to get IP for interface: "
<< ifa->ifa_name
<< " : A nonrecoverable error occured.";
break;
case EAI_FAMILY:
NEARBY_LOGS(ERROR) << __func__
<< "Failed to get IP for interface: "
<< ifa->ifa_name
<< " : The address family was not recognized, "
<< "or the address length was invalid for the "
<< "specified family.";
break;
case EAI_MEMORY:
NEARBY_LOGS(ERROR) << __func__
<< "Failed to get IP for interface: "
<< ifa->ifa_name
<< " : Out of memory.";
break;
case EAI_NONAME:
NEARBY_LOGS(ERROR) << __func__
<< "Failed to get IP for interface: "
<< ifa->ifa_name
<< " : The name does not resolve for the suplied arguments."
<< " NI_NAMEREQD is set and the host's name cannot be located, "
<< "or neither hostname nor service name were requsted.";
break;
case EAI_OVERFLOW:
NEARBY_LOGS(ERROR) << __func__
<< "Failed to get IP for interface: "
<< ifa->ifa_name
<< " : The bugger pointed to by `host` or `serv` was too small.";
break;
case EAI_SYSTEM:
NEARBY_LOGS(ERROR) << __func__
<< "A system error occured. Error code: "
<< errno
<< ": " << strerror(errno);
break;
case EAI_AGAIN:
NEARBY_LOGS(ERROR) << __func__ << "Failed to get IP for interface: "
<< ifa->ifa_name
<< " : The name could not be resolved at this time. "
<< "Try again later.";
break;
case EAI_BADFLAGS:
NEARBY_LOGS(ERROR) << __func__ << "Failed to get IP for interface: "
<< ifa->ifa_name
<< " : The flags argument has an invalid value.";
break;
case EAI_FAIL:
NEARBY_LOGS(ERROR) << __func__ << "Failed to get IP for interface: "
<< ifa->ifa_name
<< " : A nonrecoverable error occured.";
break;
case EAI_FAMILY:
NEARBY_LOGS(ERROR) << __func__ << "Failed to get IP for interface: "
<< ifa->ifa_name
<< " : The address family was not recognized, "
<< "or the address length was invalid for the "
<< "specified family.";
break;
case EAI_MEMORY:
NEARBY_LOGS(ERROR) << __func__ << "Failed to get IP for interface: "
<< ifa->ifa_name << " : Out of memory.";
break;
case EAI_NONAME:
NEARBY_LOGS(ERROR)
<< __func__ << "Failed to get IP for interface: " << ifa->ifa_name
<< " : The name does not resolve for the suplied arguments."
<< " NI_NAMEREQD is set and the host's name cannot be located, "
<< "or neither hostname nor service name were requsted.";
break;
case EAI_OVERFLOW:
NEARBY_LOGS(ERROR)
<< __func__ << "Failed to get IP for interface: " << ifa->ifa_name
<< " : The bugger pointed to by `host` or `serv` was too small.";
break;
case EAI_SYSTEM:
NEARBY_LOGS(ERROR) << __func__
<< "A system error occured. Error code: " << errno
<< ": " << strerror(errno);
break;
}
}
freeifaddrs(interface);
@@ -358,6 +348,6 @@ std::vector<std::string> InspectableReader::ReadStringArray(
return result;
}
*/
}
} // namespace
} // namespace linux
} // namespace nearby
@@ -13,9 +13,9 @@
// limitations under the License.
#include <arpa/inet.h>
#include <memory>
#include <netinet/in.h>
#include <sys/socket.h>
#include <memory>
#include "internal/platform/implementation/linux/wifi_direct.h"
#include "internal/platform/implementation/linux/wifi_direct_server_socket.h"
@@ -146,7 +146,7 @@ bool NetworkManagerWifiDirectMedium::DisconnectWifiDirect() {
bool NetworkManagerWifiDirectMedium::ConnectedToWifi() {
try {
auto mode = wireless_device_->Mode();
return mode == 2; // NM_802_11_MODE_INFRA
return mode == 2; // NM_802_11_MODE_INFRA
} catch (const sdbus::Error &e) {
DBUS_LOG_PROPERTY_GET_ERROR(wireless_device_, "Mode", e);
return false;
@@ -156,15 +156,14 @@ bool NetworkManagerWifiDirectMedium::ConnectedToWifi() {
bool NetworkManagerWifiDirectMedium::StartWifiDirect(
WifiDirectCredentials *wifi_direct_credentials) {
// According to the comments in the windows implementation, the wifi direct
// medium is currently just a regular wifi hotspot.
// medium is currently just a regular wifi hotspot.
auto wireless_device = std::make_unique<NetworkManagerWifiMedium>(
network_manager_, system_bus_, wireless_device_->getObjectPath());
auto hotspot = NetworkManagerWifiHotspotMedium(system_bus_, network_manager_,
std::move(wireless_device));
HotspotCredentials hotspot_creds;
if (!hotspot.StartWifiHotspot(&hotspot_creds))
return false;
if (!hotspot.StartWifiHotspot(&hotspot_creds)) return false;
wifi_direct_credentials->SetSSID(hotspot_creds.GetSSID());
wifi_direct_credentials->SetPassword(hotspot_creds.GetPassword());
@@ -180,5 +179,5 @@ bool NetworkManagerWifiDirectMedium::StopWifiDirect() {
return hotspot.DisconnectWifiHotspot();
}
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
@@ -17,6 +17,7 @@
#include <memory>
#include <optional>
#include <sdbus-c++/IConnection.h>
#include "internal/platform/implementation/linux/wifi_medium.h"
@@ -25,40 +26,41 @@
namespace nearby {
namespace linux {
class NetworkManagerWifiDirectMedium : public api::WifiDirectMedium {
public:
public:
NetworkManagerWifiDirectMedium(
sdbus::IConnection &system_bus,
std::shared_ptr<NetworkManager> network_manager,
std::unique_ptr<NetworkManagerWifiMedium> wireless_device)
: system_bus_(system_bus), network_manager_(std::move(network_manager)),
: system_bus_(system_bus),
network_manager_(std::move(network_manager)),
wireless_device_(std::move(wireless_device)) {}
bool IsInterfaceValid() const override { return true; }
std::unique_ptr<api::WifiDirectSocket>
ConnectToService(absl::string_view ip_address, int port,
CancellationFlag *cancellation_flag) override;
std::unique_ptr<api::WifiDirectServerSocket>
ListenForService(int port) override;
bool
ConnectWifiDirect(WifiDirectCredentials *wifi_direct_credentials) override;
std::unique_ptr<api::WifiDirectSocket> ConnectToService(
absl::string_view ip_address, int port,
CancellationFlag *cancellation_flag) override;
std::unique_ptr<api::WifiDirectServerSocket> ListenForService(
int port) override;
bool ConnectWifiDirect(
WifiDirectCredentials *wifi_direct_credentials) override;
bool DisconnectWifiDirect() override;
bool StartWifiDirect(WifiDirectCredentials *wifi_direct_credentials) override;
bool StopWifiDirect() override;
absl::optional<std::pair<std::int32_t, std::int32_t>>
GetDynamicPortRange() override {
absl::optional<std::pair<std::int32_t, std::int32_t>> GetDynamicPortRange()
override {
return std::nullopt;
}
private:
private:
bool ConnectedToWifi();
sdbus::IConnection &system_bus_;
std::shared_ptr<NetworkManager> network_manager_;
std::unique_ptr<NetworkManagerWifiMedium> wireless_device_;
};
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif
@@ -12,12 +12,13 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal/platform/implementation/linux/wifi_direct_server_socket.h"
#include "internal/platform/exception.h"
#include "internal/platform/implementation/linux/wifi_direct_socket.h"
#include <netinet/in.h>
#include <sys/socket.h>
#include "internal/platform/exception.h"
#include "internal/platform/implementation/linux/wifi_direct_server_socket.h"
#include "internal/platform/implementation/linux/wifi_direct_socket.h"
namespace nearby {
namespace linux {
std::string NetworkManagerWifiDirectServerSocket::GetIPAddress() const {
@@ -76,5 +77,5 @@ Exception NetworkManagerWifiDirectServerSocket::Close() {
return {Exception::kSuccess};
}
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
@@ -22,9 +22,9 @@
namespace nearby {
namespace linux {
class WifiDirectSocket : public api::WifiDirectSocket {
public:
public:
explicit WifiDirectSocket(int socket)
: fd_(sdbus::UnixFd(socket)), output_stream_(fd_), input_stream_(fd_) {}
: fd_(sdbus::UnixFd(socket)), output_stream_(fd_), input_stream_(fd_) {}
InputStream &GetInputStream() override { return input_stream_; };
OutputStream &GetOutputStream() override { return output_stream_; };
@@ -36,12 +36,12 @@ public:
return Exception{Exception::kSuccess};
};
private:
private:
sdbus::UnixFd fd_;
OutputStream output_stream_;
InputStream input_stream_;
};
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif
@@ -13,12 +13,12 @@
// limitations under the License.
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <cstring>
#include <memory>
#include <netinet/in.h>
#include <random>
#include <sys/socket.h>
#include <systemd/sd-id128.h>
#include "internal/platform/implementation/linux/dbus.h"
@@ -313,7 +313,7 @@ bool NetworkManagerWifiHotspotMedium::DisconnectWifiHotspot() {
bool NetworkManagerWifiHotspotMedium::WifiHotspotActive() {
try {
auto mode = wireless_device_->Mode();
return mode == 3; // NM_802_11_MODE_AP
return mode == 3; // NM_802_11_MODE_AP
} catch (const sdbus::Error &e) {
DBUS_LOG_PROPERTY_GET_ERROR(wireless_device_, "Mode", e);
return false;
@@ -323,12 +323,12 @@ bool NetworkManagerWifiHotspotMedium::WifiHotspotActive() {
bool NetworkManagerWifiHotspotMedium::ConnectedToWifi() {
try {
auto mode = wireless_device_->Mode();
return mode == 2; // NM_802_11_MODE_INFRA
return mode == 2; // NM_802_11_MODE_INFRA
} catch (const sdbus::Error &e) {
DBUS_LOG_PROPERTY_GET_ERROR(wireless_device_, "Mode", e);
return false;
}
}
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
@@ -24,42 +24,43 @@
namespace nearby {
namespace linux {
class NetworkManagerWifiHotspotMedium : public api::WifiHotspotMedium {
public:
NetworkManagerWifiHotspotMedium(
sdbus::IConnection &system_bus,
std::shared_ptr<NetworkManager> network_manager,
sdbus::ObjectPath wireless_device_object_path)
: system_bus_(system_bus),
wireless_device_(std::make_unique<NetworkManagerWifiMedium>(
network_manager, system_bus, std::move(wireless_device_object_path))),
network_manager_(std::move(network_manager)) {}
NetworkManagerWifiHotspotMedium(
sdbus::IConnection &system_bus,
std::shared_ptr<NetworkManager> network_manager,
std::unique_ptr<NetworkManagerWifiMedium> wireless_device)
: system_bus_(system_bus),
wireless_device_(std::move(wireless_device)),
network_manager_(std::move(network_manager)) {}
public:
NetworkManagerWifiHotspotMedium(
sdbus::IConnection &system_bus,
std::shared_ptr<NetworkManager> network_manager,
sdbus::ObjectPath wireless_device_object_path)
: system_bus_(system_bus),
wireless_device_(std::make_unique<NetworkManagerWifiMedium>(
network_manager, system_bus,
std::move(wireless_device_object_path))),
network_manager_(std::move(network_manager)) {}
NetworkManagerWifiHotspotMedium(
sdbus::IConnection &system_bus,
std::shared_ptr<NetworkManager> network_manager,
std::unique_ptr<NetworkManagerWifiMedium> wireless_device)
: system_bus_(system_bus),
wireless_device_(std::move(wireless_device)),
network_manager_(std::move(network_manager)) {}
bool IsInterfaceValid() const override { return true; }
std::unique_ptr<api::WifiHotspotSocket> ConnectToService(
absl::string_view ip_address, int port,
CancellationFlag *cancellation_flag) override;
std::unique_ptr<api::WifiHotspotServerSocket> ListenForService(
int port) override;
bool IsInterfaceValid() const override { return true; }
std::unique_ptr<api::WifiHotspotSocket> ConnectToService(
absl::string_view ip_address, int port,
CancellationFlag *cancellation_flag) override;
std::unique_ptr<api::WifiHotspotServerSocket> ListenForService(
int port) override;
bool StartWifiHotspot(HotspotCredentials *hotspot_credentials) override;
bool StopWifiHotspot() override;
bool StartWifiHotspot(HotspotCredentials *hotspot_credentials) override;
bool StopWifiHotspot() override;
bool ConnectWifiHotspot(HotspotCredentials *hotspot_credentials) override;
bool DisconnectWifiHotspot() override;
bool ConnectWifiHotspot(HotspotCredentials *hotspot_credentials) override;
bool DisconnectWifiHotspot() override;
absl::optional<std::pair<std::int32_t, std::int32_t>> GetDynamicPortRange()
override {
return absl::nullopt;
absl::optional<std::pair<std::int32_t, std::int32_t>> GetDynamicPortRange()
override {
return absl::nullopt;
}
private:
private:
bool WifiHotspotActive();
bool ConnectedToWifi();
@@ -67,7 +68,7 @@ private:
std::unique_ptr<NetworkManagerWifiMedium> wireless_device_;
std::shared_ptr<NetworkManager> network_manager_;
};
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif
@@ -26,11 +26,11 @@ std::string NetworkManagerWifiHotspotServerSocket::GetIPAddress() const {
active_connection_path_);
auto ip4addresses = active_conn.GetIP4Addresses();
if (ip4addresses.empty()) {
NEARBY_LOGS(ERROR)
<< __func__
<< ": Could not find any IPv4 addresses for active connection "
<< active_connection_path_;
return std::string();
NEARBY_LOGS(ERROR)
<< __func__
<< ": Could not find any IPv4 addresses for active connection "
<< active_connection_path_;
return std::string();
}
return ip4addresses[0];
}
@@ -77,5 +77,5 @@ Exception NetworkManagerWifiHotspotServerSocket::Close() {
return {Exception::kSuccess};
}
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
@@ -24,12 +24,13 @@ namespace nearby {
namespace linux {
class NetworkManagerWifiHotspotServerSocket
: public api::WifiHotspotServerSocket {
public:
public:
NetworkManagerWifiHotspotServerSocket(
int socket, sdbus::IConnection &system_bus,
sdbus::ObjectPath active_connection_path,
std::shared_ptr<NetworkManager> network_manager)
: fd_(socket), system_bus_(system_bus),
: fd_(socket),
system_bus_(system_bus),
active_connection_path_(std::move(active_connection_path)),
network_manager_(std::move(network_manager)) {}
@@ -38,13 +39,13 @@ public:
std::unique_ptr<api::WifiHotspotSocket> Accept() override;
Exception Close() override;
private:
private:
sdbus::UnixFd fd_;
sdbus::IConnection &system_bus_;
sdbus::ObjectPath active_connection_path_;
std::shared_ptr<NetworkManager> network_manager_;
};
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif
@@ -21,9 +21,10 @@
namespace nearby {
namespace linux {
class WifiHotspotSocket : public api::WifiHotspotSocket {
public:
public:
explicit WifiHotspotSocket(int connection_fd)
: fd_(sdbus::UnixFd(connection_fd)), output_stream_(fd_),
: fd_(sdbus::UnixFd(connection_fd)),
output_stream_(fd_),
input_stream_(fd_) {}
nearby::InputStream &GetInputStream() override { return input_stream_; };
@@ -35,12 +36,12 @@ public:
return Exception{Exception::kSuccess};
};
private:
private:
sdbus::UnixFd fd_;
OutputStream output_stream_;
InputStream input_stream_;
};
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif
@@ -13,17 +13,17 @@
// limitations under the License.
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <cerrno>
#include <cstdint>
#include <cstring>
#include <memory>
#include <netinet/in.h>
#include <sdbus-c++/Types.h>
#include <sys/socket.h>
#include <utility>
#include <sdbus-c++/Error.h>
#include <sdbus-c++/IConnection.h>
#include <utility>
#include <sdbus-c++/Types.h>
#include "absl/strings/substitute.h"
#include "internal/platform/implementation/linux/avahi.h"
@@ -44,11 +44,11 @@ WifiLanMedium::WifiLanMedium(sdbus::IConnection &system_bus)
bool WifiLanMedium::IsNetworkConnected() const {
auto state = network_manager_->getState();
return state >= 50; // NM_STATE_CONNECTED_LOCAL
return state >= 50; // NM_STATE_CONNECTED_LOCAL
}
std::optional<std::pair<std::string, std::string>>
entry_group_key(const NsdServiceInfo &nsd_service_info) {
std::optional<std::pair<std::string, std::string>> entry_group_key(
const NsdServiceInfo &nsd_service_info) {
auto name = nsd_service_info.GetServiceName();
if (name.empty()) {
NEARBY_LOGS(ERROR) << __func__ << ": service name cannot be empty";
@@ -101,8 +101,8 @@ bool WifiLanMedium::StartAdvertising(const NsdServiceInfo &nsd_service_info) {
try {
entry_group->AddService(
-1, // AVAHI_IF_UNSPEC
-1, // AVAHI_PROTO_UNSPED
-1, // AVAHI_IF_UNSPEC
-1, // AVAHI_PROTO_UNSPED
0, nsd_service_info.GetServiceName(), nsd_service_info.GetServiceType(),
std::string(), std::string(), nsd_service_info.GetPort(), txt_records);
entry_group->Commit();
@@ -139,7 +139,6 @@ bool WifiLanMedium::StopAdvertising(const NsdServiceInfo &nsd_service_info) {
bool WifiLanMedium::StartDiscovery(
const std::string &service_type,
api::WifiLanMedium::DiscoveredServiceCallback callback) {
{
absl::ReaderMutexLock l(&service_browsers_mutex_);
if (service_browsers_.count(service_type) != 0) {
@@ -153,8 +152,8 @@ bool WifiLanMedium::StartDiscovery(
try {
sdbus::ObjectPath browser_object_path =
avahi_->ServiceBrowserPrepare(-1, // AVAHI_IF_UNSPEC
-1, // AVAHI_PROTO_UNSPED
avahi_->ServiceBrowserPrepare(-1, // AVAHI_IF_UNSPEC
-1, // AVAHI_PROTO_UNSPED
service_type, std::string(), 0);
NEARBY_LOGS(VERBOSE)
<< __func__
@@ -200,9 +199,9 @@ bool WifiLanMedium::StopDiscovery(const std::string &service_type) {
return true;
}
std::unique_ptr<api::WifiLanSocket>
WifiLanMedium::ConnectToService(const std::string &ip_address, int port,
CancellationFlag *cancellation_flag) {
std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
const std::string &ip_address, int port,
CancellationFlag *cancellation_flag) {
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
NEARBY_LOGS(ERROR) << __func__
@@ -229,8 +228,8 @@ WifiLanMedium::ConnectToService(const std::string &ip_address, int port,
return std::make_unique<WifiLanSocket>(std::move(fd));
}
std::unique_ptr<api::WifiLanServerSocket>
WifiLanMedium::ListenForService(int port) {
std::unique_ptr<api::WifiLanServerSocket> WifiLanMedium::ListenForService(
int port) {
auto sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
NEARBY_LOGS(ERROR) << __func__
@@ -268,5 +267,5 @@ absl::optional<std::pair<std::int32_t, std::int32_t>> GetDynamicPortRange() {
return absl::nullopt;
}
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
@@ -26,7 +26,7 @@
namespace nearby {
namespace linux {
class WifiLanMedium : public api::WifiLanMedium {
public:
public:
explicit WifiLanMedium(sdbus::IConnection &system_bus);
bool IsNetworkConnected() const override;
@@ -42,23 +42,23 @@ public:
bool StopDiscovery(const std::string &service_type) override
ABSL_LOCKS_EXCLUDED(service_browsers_mutex_);
std::unique_ptr<api::WifiLanSocket>
ConnectToService(const NsdServiceInfo &remote_service_info,
CancellationFlag *cancellation_flag) override {
std::unique_ptr<api::WifiLanSocket> ConnectToService(
const NsdServiceInfo &remote_service_info,
CancellationFlag *cancellation_flag) override {
return ConnectToService(remote_service_info.GetIPAddress(),
remote_service_info.GetPort(), cancellation_flag);
};
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;
absl::optional<std::pair<std::int32_t, std::int32_t>>
GetDynamicPortRange() 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;
absl::optional<std::pair<std::int32_t, std::int32_t>> GetDynamicPortRange()
override {
return std::nullopt;
}
private:
private:
sdbus::IConnection &system_bus_;
std::shared_ptr<NetworkManager> network_manager_;
@@ -74,7 +74,7 @@ private:
absl::flat_hash_map<std::string, std::unique_ptr<avahi::ServiceBrowser>>
service_browsers_ ABSL_GUARDED_BY(service_browsers_mutex_);
};
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif
@@ -13,13 +13,13 @@
// limitations under the License.
#include <arpa/inet.h>
#include <cerrno>
#include <cstring>
#include <ifaddrs.h>
#include <memory>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cerrno>
#include <cstring>
#include <memory>
#include <sdbus-c++/Types.h>
@@ -60,17 +60,17 @@ std::string WifiLanServerSocket::GetIPAddress() const {
address_data = ip4config.AddressData();
} catch (const sdbus::Error &e) {
DBUS_LOG_PROPERTY_GET_ERROR(&ip4config, "IP4Config", e);
continue;
continue;
}
if (address_data.size() > 0) {
return address_data[0]["address"];
return address_data[0]["address"];
}
}
}
NEARBY_LOGS(ERROR)
<< __func__ << ": Could not find any active IP addresses for this device";
<< __func__ << ": Could not find any active IP addresses for this device";
return std::string();
}
@@ -115,5 +115,5 @@ Exception WifiLanServerSocket::Close() {
return {Exception::kSuccess};
}
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
@@ -27,11 +27,12 @@
namespace nearby {
namespace linux {
class WifiLanServerSocket : public api::WifiLanServerSocket {
public:
public:
explicit WifiLanServerSocket(int socket,
std::shared_ptr<NetworkManager> network_manager,
sdbus::IConnection &system_bus)
: fd_(sdbus::UnixFd(socket)), network_manager_(std::move(network_manager)),
std::shared_ptr<NetworkManager> network_manager,
sdbus::IConnection &system_bus)
: fd_(sdbus::UnixFd(socket)),
network_manager_(std::move(network_manager)),
system_bus_(system_bus) {}
std::string GetIPAddress() const override;
@@ -40,11 +41,11 @@ public:
std::unique_ptr<api::WifiLanSocket> Accept() override;
Exception Close() override;
private:
private:
sdbus::UnixFd fd_;
std::shared_ptr<NetworkManager> network_manager_;
sdbus::IConnection &system_bus_;
};
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif
@@ -27,16 +27,12 @@
namespace nearby {
namespace linux {
class WifiLanSocket : public api::WifiLanSocket {
public:
public:
explicit WifiLanSocket(sdbus::UnixFd fd)
: fd_(fd), output_stream_(fd), input_stream_(fd) {}
nearby::InputStream &GetInputStream() override {
return input_stream_;
};
nearby::OutputStream &GetOutputStream() override {
return output_stream_;
};
nearby::InputStream &GetInputStream() override { return input_stream_; };
nearby::OutputStream &GetOutputStream() override { return output_stream_; };
Exception Close() override {
input_stream_.Close();
output_stream_.Close();
@@ -44,12 +40,12 @@ public:
return Exception{Exception::kSuccess};
};
private:
private:
sdbus::UnixFd fd_;
OutputStream output_stream_;
InputStream input_stream_;
};
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
#endif
@@ -13,9 +13,9 @@
// limitations under the License.
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstdint>
#include <memory>
#include <netinet/in.h>
#include <type_traits>
#include <sdbus-c++/Error.h>
@@ -36,39 +36,41 @@ namespace linux {
std::ostream &operator<<(std::ostream &s,
const ActiveConnectionStateReason &reason) {
switch (reason) {
case kStateReasonUnknown:
return s << "The reason for the active connection state change is unknown.";
case kStateReasonNone:
return s << "No reason was given for the active connection state change.";
case kStateReasonUserDisconnected:
return s << "The active connection changed state because the user "
"disconnected it.";
case kStateReasonDeviceDisconnected:
return s << "The active connection changed state because the device it was "
case kStateReasonUnknown:
return s
<< "The reason for the active connection state change is unknown.";
case kStateReasonNone:
return s << "No reason was given for the active connection state change.";
case kStateReasonUserDisconnected:
return s << "The active connection changed state because the user "
"disconnected it.";
case kStateReasonDeviceDisconnected:
return s
<< "The active connection changed state because the device it was "
"using was disconnected.";
case kStateReasonServiceStopped:
return s << "The service providing the VPN connection was stopped.";
case kStateReasonIPConfigInvalid:
return s << "The IP config of the active connection was invalid.";
case kStateReasonConnectTimeout:
return s << "The connection attempt to the VPN service timed out.";
case kStateReasonServiceStartTimeout:
return s << "A timeout occurred while starting the service providing the "
"VPN connection.";
case kStateReasonServiceStartFailed:
return s << "Starting the service providing the VPN connection failed.";
case kStateReasonNoSecrets:
return s << "Necessary secrets for the connection were not provided.";
case kStateReasonLoginFailed:
return s << "Authentication to the server failed.";
case kStateReasonConnectionRemoved:
return s << "The connection was deleted from settings.";
case kStateReasonDependencyFailed:
return s << "Master connection of this connection failed to activate.";
case kStateReasonDeviceRealizeFailed:
return s << "Could not create the software device link.";
case kStateReasonDeviceRemoved:
return s << "The device this connection depended on disappeared.";
case kStateReasonServiceStopped:
return s << "The service providing the VPN connection was stopped.";
case kStateReasonIPConfigInvalid:
return s << "The IP config of the active connection was invalid.";
case kStateReasonConnectTimeout:
return s << "The connection attempt to the VPN service timed out.";
case kStateReasonServiceStartTimeout:
return s << "A timeout occurred while starting the service providing the "
"VPN connection.";
case kStateReasonServiceStartFailed:
return s << "Starting the service providing the VPN connection failed.";
case kStateReasonNoSecrets:
return s << "Necessary secrets for the connection were not provided.";
case kStateReasonLoginFailed:
return s << "Authentication to the server failed.";
case kStateReasonConnectionRemoved:
return s << "The connection was deleted from settings.";
case kStateReasonDependencyFailed:
return s << "Master connection of this connection failed to activate.";
case kStateReasonDeviceRealizeFailed:
return s << "Could not create the software device link.";
case kStateReasonDeviceRemoved:
return s << "The device this connection depended on disappeared.";
}
}
@@ -312,25 +314,23 @@ NetworkManagerWifiMedium::SearchBySSID(absl::string_view ssid,
return ap;
}
static inline std::pair<std::string, std::string>
AuthAlgAndKeyMgmt(api::WifiAuthType auth_type) {
static inline std::pair<std::string, std::string> AuthAlgAndKeyMgmt(
api::WifiAuthType auth_type) {
switch (auth_type) {
case api::WifiAuthType::kUnknown:
return {"open", "none"};
case api::WifiAuthType::kOpen:
return {"open", "none"};
case api::WifiAuthType::kWpaPsk:
return {"shared", "wpa-psk"};
case api::WifiAuthType::kWep:
return {"none", "wep"};
case api::WifiAuthType::kUnknown:
return {"open", "none"};
case api::WifiAuthType::kOpen:
return {"open", "none"};
case api::WifiAuthType::kWpaPsk:
return {"shared", "wpa-psk"};
case api::WifiAuthType::kWep:
return {"none", "wep"};
}
}
api::WifiConnectionStatus
NetworkManagerWifiMedium::ConnectToNetwork(absl::string_view ssid,
absl::string_view password,
api::WifiAuthType auth_type) {
api::WifiConnectionStatus NetworkManagerWifiMedium::ConnectToNetwork(
absl::string_view ssid, absl::string_view password,
api::WifiAuthType auth_type) {
auto ap = SearchBySSID(ssid);
if (ap == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": " << getObjectPath()
@@ -424,7 +424,7 @@ NetworkManagerWifiMedium::ConnectToNetwork(absl::string_view ssid,
bool NetworkManagerWifiMedium::VerifyInternetConnectivity() {
try {
std::uint32_t connectivity = network_manager_->CheckConnectivity();
return connectivity == 4; // NM_CONNECTIVITY_FULL
return connectivity == 4; // NM_CONNECTIVITY_FULL
} catch (const sdbus::Error &e) {
DBUS_LOG_METHOD_CALL_ERROR(network_manager_, "CheckConnectivity", e);
return false;
@@ -465,5 +465,5 @@ NetworkManagerWifiMedium::GetActiveConnection() {
return conn;
}
} // namespace linux
} // namespace nearby
} // namespace linux
} // namespace nearby
@@ -16,15 +16,15 @@
#define PLATFORM_IMPL_LINUX_WIFI_LAN_SOCKET_H_
namespace nearby {
namespace api {
class WifiLanSocket {
public:
~WifiLanSocket() = default;
namespace api {
class WifiLanSocket {
public:
~WifiLanSocket() = default;
private:
int fd;
};
}
}
private:
int fd;
};
} // namespace api
} // namespace nearby
#endif