l2cap socket psm is not generated once per BleV2Medium initialisation. Accept() waits till all other l2cap connections are closed to create a new connection

This commit is contained in:
kidfromjupiter
2026-02-06 12:28:58 +00:00
parent 2718d9942b
commit cdfe437831
4 changed files with 23 additions and 14 deletions
@@ -72,12 +72,13 @@ void BleL2capServerSocket::AcceptPoll(int& client_fd, sockaddr_l2& client_addr,
}
// Stop requested
if (fds[1].revents & POLLIN) {
DrainFd(stop_pipe_[0]);
client_fd = -1;
errno = EINTR; // optional: helps caller treat as "interrupted"
return; // <-- THIS is the key
}
if (fds[1].revents & POLLIN) {
absl::MutexLock l(&mutex_);
DrainFd(stop_pipe_[0]);
client_fd = -1;
errno = EINTR; // optional: helps caller treat as "interrupted"
return; // <-- THIS is the key
}
// Listen socket error/hangup
if (fds[0].revents & (POLLERR | POLLHUP | POLLNVAL)) {
@@ -106,10 +107,13 @@ if (fds[1].revents & POLLIN) {
}
}
std::unique_ptr<api::ble::BleL2capSocket> BleL2capServerSocket::Accept() {
Prng prng;
psm_ = 0x80 + (prng.NextUint32() % 0x80);
// blocking accept until the previous server_fd_ is closed.
// We need to keep accepting connections on the same psm. That's why we do this
absl::MutexLock lock(&mutex_);
auto idle = [this] {return server_fd_ == -1;};
mutex_.Await(absl::Condition(&idle));
server_fd_ = socket(AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP);
server_fd_ = socket(AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP);
if (server_fd_ < 0) {
LOG(ERROR) << "Failed to create L2CAP server socket: "
<< std::strerror(errno);
@@ -222,5 +226,6 @@ Exception BleL2capServerSocket::Close() {
}
} // namespace linux
} // namespace nearby
@@ -48,8 +48,7 @@ class BleL2capServerSocket final : public api::ble::BleL2capServerSocket {
void SetCloseNotifier(absl::AnyInvocable<void()> notifier);
private:
mutable absl::Mutex mutex_;
absl::CondVar cond_;
absl::Mutex mutex_;
int psm_ = 0;
int server_fd_ = -1;
int stop_pipe_[2] = {-1, -1}; // read end [0], write end [1]
@@ -65,6 +65,11 @@ BleV2Medium::BleV2Medium(BluetoothAdapter &adapter)
adv_manager_(std::make_unique<bluez::LEAdvertisementManager>(*system_bus_,
adapter)),
cur_adv_(nullptr) {
// generating psm value for l2cap socket
Prng prng;
psm_ = 0x80 + (prng.NextUint32() % 0x80);
if (adv_monitor_manager_) {
LOG(INFO)
<< __func__
@@ -464,9 +469,7 @@ BleV2Medium::OpenL2capServerSocket(const std::string &service_id) {
LOG(INFO) << __func__ << ": Opening L2CAP server socket for service "
<< service_id;
Prng prng;
auto psm = 0x80 + (prng.NextUint32() % 0x80);
auto server_socket = std::make_unique<linux::BleL2capServerSocket>(psm);
auto server_socket = std::make_unique<linux::BleL2capServerSocket>(psm_);
return server_socket;
}
@@ -158,6 +158,8 @@ class BleV2Medium final : public api::ble::BleMedium {
std::unique_ptr<bluez::LEAdvertisementManager> adv_manager_;
int psm_;
absl::Mutex cur_adv_mutex_;
std::unique_ptr<bluez::LEAdvertisement> cur_adv_
ABSL_GUARDED_BY(cur_adv_mutex_);