bluez5-util.c 94.2 KB
Newer Older
1 2 3 4
/***
  This file is part of PulseAudio.

  Copyright 2008-2013 João Paulo Rechi Vita
pali's avatar
pali committed
5
  Copyrigth 2018-2019 Pali Rohár <pali.rohar@gmail.com>
6 7 8 9 10 11 12 13 14 15 16 17

  PulseAudio is free software; you can redistribute it and/or modify
  it under the terms of the GNU Lesser General Public License as
  published by the Free Software Foundation; either version 2.1 of the
  License, or (at your option) any later version.

  PulseAudio is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
18
  License along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
19 20 21 22 23 24
***/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

25 26
#include <errno.h>

27 28
#include <pulse/rtclock.h>
#include <pulse/timeval.h>
29 30 31
#include <pulse/xmalloc.h>

#include <pulsecore/core.h>
32 33 34
#include <pulsecore/core-util.h>
#include <pulsecore/dbus-shared.h>
#include <pulsecore/log.h>
35 36 37 38
#include <pulsecore/macro.h>
#include <pulsecore/refcnt.h>
#include <pulsecore/shared.h>

pali's avatar
pali committed
39
#include "a2dp-codec-util.h"
40 41
#include "a2dp-codecs.h"

42 43
#include "bluez5-util.h"

44 45
#define WAIT_FOR_PROFILES_TIMEOUT_USEC (3 * PA_USEC_PER_SEC)

46
#define BLUEZ_SERVICE "org.bluez"
47 48
#define BLUEZ_ADAPTER_INTERFACE BLUEZ_SERVICE ".Adapter1"
#define BLUEZ_DEVICE_INTERFACE BLUEZ_SERVICE ".Device1"
49
#define BLUEZ_MEDIA_INTERFACE BLUEZ_SERVICE ".Media1"
50
#define BLUEZ_MEDIA_ENDPOINT_INTERFACE BLUEZ_SERVICE ".MediaEndpoint1"
51
#define BLUEZ_MEDIA_TRANSPORT_INTERFACE BLUEZ_SERVICE ".MediaTransport1"
52

53 54
#define BLUEZ_ERROR_NOT_SUPPORTED "org.bluez.Error.NotSupported"

55 56 57
#define A2DP_OBJECT_MANAGER_PATH "/A2DPEndpoint"
#define A2DP_SOURCE_ENDPOINT A2DP_OBJECT_MANAGER_PATH "/Source"
#define A2DP_SINK_ENDPOINT A2DP_OBJECT_MANAGER_PATH "/Sink"
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82

#define OBJECT_MANAGER_INTROSPECT_XML                                          \
    DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE                                  \
    "<node>\n"                                                                 \
    " <interface name=\"org.freedesktop.DBus.ObjectManager\">\n"               \
    "  <method name=\"GetManagedObjects\">\n"                                  \
    "   <arg name=\"objects\" direction=\"out\" type=\"a{oa{sa{sv}}}\"/>\n"    \
    "  </method>\n"                                                            \
    "  <signal name=\"InterfacesAdded\">\n"                                    \
    "   <arg name=\"object\" type=\"o\"/>\n"                                   \
    "   <arg name=\"interfaces\" type=\"a{sa{sv}}\"/>\n"                       \
    "  </signal>\n"                                                            \
    "  <signal name=\"InterfacesRemoved\">\n"                                  \
    "   <arg name=\"object\" type=\"o\"/>\n"                                   \
    "   <arg name=\"interfaces\" type=\"as\"/>\n"                              \
    "  </signal>\n"                                                            \
    " </interface>\n"                                                          \
    " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"              \
    "  <method name=\"Introspect\">\n"                                         \
    "   <arg name=\"data\" direction=\"out\" type=\"s\"/>\n"                   \
    "  </method>\n"                                                            \
    " </interface>\n"                                                          \
    " <node name=\"A2DPSink\"/>\n"                                             \
    " <node name=\"A2DPSource\"/>\n"                                           \
    "</node>\n"
83 84 85

#define ENDPOINT_INTROSPECT_XML                                         \
    DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE                           \
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
    "<node>\n"                                                          \
    " <interface name=\"" BLUEZ_MEDIA_ENDPOINT_INTERFACE "\">\n"        \
    "  <method name=\"SetConfiguration\">\n"                            \
    "   <arg name=\"transport\" direction=\"in\" type=\"o\"/>\n"        \
    "   <arg name=\"properties\" direction=\"in\" type=\"ay\"/>\n"      \
    "  </method>\n"                                                     \
    "  <method name=\"SelectConfiguration\">\n"                         \
    "   <arg name=\"capabilities\" direction=\"in\" type=\"ay\"/>\n"    \
    "   <arg name=\"configuration\" direction=\"out\" type=\"ay\"/>\n"  \
    "  </method>\n"                                                     \
    "  <method name=\"ClearConfiguration\">\n"                          \
    "   <arg name=\"transport\" direction=\"in\" type=\"o\"/>\n"        \
    "  </method>\n"                                                     \
    "  <method name=\"Release\">\n"                                     \
    "  </method>\n"                                                     \
    " </interface>\n"                                                   \
    " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"       \
    "  <method name=\"Introspect\">\n"                                  \
    "   <arg name=\"data\" type=\"s\" direction=\"out\"/>\n"            \
    "  </method>\n"                                                     \
    " </interface>\n"                                                   \
    "</node>\n"
108

109 110 111 112
struct pa_bluetooth_discovery {
    PA_REFCNT_DECLARE;

    pa_core *core;
113 114 115
    pa_dbus_connection *connection;
    bool filter_added;
    bool matches_added;
116
    bool objects_listed;
117
    pa_hook hooks[PA_BLUETOOTH_HOOK_MAX];
118
    pa_hashmap *adapters;
119
    pa_hashmap *devices;
120
    pa_hashmap *transports;
121
    pa_hashmap *pending_transport_fds;
122

123
    int headset_backend;
124
    pa_bluetooth_backend *hsphfpd_backend;
125
    pa_bluetooth_backend *legacy_hsp_backend;
126
    PA_LLIST_HEAD(pa_dbus_pending, pending);
127 128
};

129 130 131 132 133 134 135
struct pending_transport_fd {
    pa_bluetooth_discovery *discovery;
    char *path;
    size_t imtu, omtu;
    int fd;
};

136 137 138 139 140
struct a2dp_codec_capabilities {
    uint8_t size;
    uint8_t buffer[]; /* max size is 254 bytes */
};

141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
static pa_dbus_pending* send_and_add_to_pending(pa_bluetooth_discovery *y, DBusMessage *m,
                                                                  DBusPendingCallNotifyFunction func, void *call_data) {
    pa_dbus_pending *p;
    DBusPendingCall *call;

    pa_assert(y);
    pa_assert(m);

    pa_assert_se(dbus_connection_send_with_reply(pa_dbus_connection_get(y->connection), m, &call, -1));

    p = pa_dbus_pending_new(pa_dbus_connection_get(y->connection), m, call, y, call_data);
    PA_LLIST_PREPEND(pa_dbus_pending, y->pending, p);
    dbus_pending_call_set_notify(call, func, p, NULL);

    return p;
}

158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
static const char *check_variant_property(DBusMessageIter *i) {
    const char *key;

    pa_assert(i);

    if (dbus_message_iter_get_arg_type(i) != DBUS_TYPE_STRING) {
        pa_log_error("Property name not a string.");
        return NULL;
    }

    dbus_message_iter_get_basic(i, &key);

    if (!dbus_message_iter_next(i)) {
        pa_log_error("Property value missing");
        return NULL;
    }

    if (dbus_message_iter_get_arg_type(i) != DBUS_TYPE_VARIANT) {
        pa_log_error("Property value not a variant.");
        return NULL;
    }

    return key;
}

183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
pa_bluetooth_transport *pa_bluetooth_transport_new(pa_bluetooth_device *d, const char *owner, const char *path,
                                                   pa_bluetooth_profile_t p, const uint8_t *config, size_t size) {
    pa_bluetooth_transport *t;

    t = pa_xnew0(pa_bluetooth_transport, 1);
    t->device = d;
    t->owner = pa_xstrdup(owner);
    t->path = pa_xstrdup(path);
    t->profile = p;
    t->config_size = size;

    if (size > 0) {
        t->config = pa_xnew(uint8_t, size);
        memcpy(t->config, config, size);
    }

    return t;
}

static const char *transport_state_to_string(pa_bluetooth_transport_state_t state) {
    switch(state) {
        case PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED:
            return "disconnected";
        case PA_BLUETOOTH_TRANSPORT_STATE_IDLE:
            return "idle";
        case PA_BLUETOOTH_TRANSPORT_STATE_PLAYING:
            return "playing";
    }

    return "invalid";
}

215
static bool device_supports_profile(pa_bluetooth_device *device, pa_bluetooth_profile_t profile) {
216 217 218 219 220 221
    const struct a2dp_codec_capabilities *a2dp_codec_capabilities;
    const pa_a2dp_codec *a2dp_codec;
    bool is_a2dp_sink;
    pa_hashmap *endpoints;
    void *state;

222
    switch (profile) {
223
        case PA_BLUETOOTH_PROFILE_HSP_HEAD_UNIT:
224
            return !!pa_hashmap_get(device->uuids, PA_BLUETOOTH_UUID_HSP_HS)
225 226 227 228 229 230 231
                || !!pa_hashmap_get(device->uuids, PA_BLUETOOTH_UUID_HSP_HS_ALT);
        case PA_BLUETOOTH_PROFILE_HFP_HEAD_UNIT:
            return !!pa_hashmap_get(device->uuids, PA_BLUETOOTH_UUID_HFP_HF);
        case PA_BLUETOOTH_PROFILE_HSP_AUDIO_GATEWAY:
            return !!pa_hashmap_get(device->uuids, PA_BLUETOOTH_UUID_HSP_AG);
        case PA_BLUETOOTH_PROFILE_HFP_AUDIO_GATEWAY:
            return !!pa_hashmap_get(device->uuids, PA_BLUETOOTH_UUID_HFP_AG);
232
        case PA_BLUETOOTH_PROFILE_OFF:
233 234 235
            return true;
        default:
            break;
236 237
    }

238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
    a2dp_codec = pa_bluetooth_profile_to_a2dp_codec(profile);
    is_a2dp_sink = pa_bluetooth_profile_is_a2dp_sink(profile);

    if (is_a2dp_sink && !pa_hashmap_get(device->uuids, PA_BLUETOOTH_UUID_A2DP_SINK))
        return false;
    else if (!is_a2dp_sink && !pa_hashmap_get(device->uuids, PA_BLUETOOTH_UUID_A2DP_SOURCE))
        return false;

    if (is_a2dp_sink)
        endpoints = pa_hashmap_get(device->a2dp_sink_endpoints, &a2dp_codec->id);
    else
        endpoints = pa_hashmap_get(device->a2dp_source_endpoints, &a2dp_codec->id);

    if (!endpoints)
        return false;

    PA_HASHMAP_FOREACH(a2dp_codec_capabilities, endpoints, state) {
        if (a2dp_codec->can_accept_capabilities(a2dp_codec_capabilities->buffer, a2dp_codec_capabilities->size, is_a2dp_sink))
            return true;
    }

    return false;
260 261 262 263 264 265 266 267 268
}

static bool device_is_profile_connected(pa_bluetooth_device *device, pa_bluetooth_profile_t profile) {
    if (device->transports[profile] && device->transports[profile]->state != PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED)
        return true;
    else
        return false;
}

269
static unsigned device_count_disconnected_profile_uuids(pa_bluetooth_device *device) {
270
    pa_bluetooth_profile_t profile;
271
    unsigned bluetooth_profile_count;
272 273
    unsigned count = 0;

274 275
    bluetooth_profile_count = pa_bluetooth_profile_count();
    for (profile = 0; profile < bluetooth_profile_count; profile++) {
276
        if (!device_supports_profile(device, profile) || pa_bluetooth_profile_is_a2dp(profile))
277 278 279 280 281 282
            continue;

        if (!device_is_profile_connected(device, profile))
            count++;
    }

283 284 285 286 287 288
    if (pa_hashmap_get(device->uuids, PA_BLUETOOTH_UUID_A2DP_SINK) && !pa_bluetooth_device_a2dp_sink_transport_connected(device))
        count++;

    if (pa_hashmap_get(device->uuids, PA_BLUETOOTH_UUID_A2DP_SOURCE) && !pa_bluetooth_device_a2dp_source_transport_connected(device))
        count++;

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
    return count;
}

static void device_stop_waiting_for_profiles(pa_bluetooth_device *device) {
    if (!device->wait_for_profiles_timer)
        return;

    device->discovery->core->mainloop->time_free(device->wait_for_profiles_timer);
    device->wait_for_profiles_timer = NULL;
}

static void wait_for_profiles_cb(pa_mainloop_api *api, pa_time_event* event, const struct timeval *tv, void *userdata) {
    pa_bluetooth_device *device = userdata;
    pa_strbuf *buf;
    pa_bluetooth_profile_t profile;
304
    unsigned bluetooth_profile_count;
305 306 307 308 309 310 311
    bool first = true;
    char *profiles_str;

    device_stop_waiting_for_profiles(device);

    buf = pa_strbuf_new();

312 313
    bluetooth_profile_count = pa_bluetooth_profile_count();
    for (profile = 0; profile < bluetooth_profile_count; profile++) {
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
        if (device_is_profile_connected(device, profile))
            continue;

        if (!device_supports_profile(device, profile))
            continue;

        if (first)
            first = false;
        else
            pa_strbuf_puts(buf, ", ");

        pa_strbuf_puts(buf, pa_bluetooth_profile_to_string(profile));
    }

    profiles_str = pa_strbuf_to_string_free(buf);
    pa_log_debug("Timeout expired, and device %s still has disconnected profiles: %s",
                 device->path, profiles_str);
    pa_xfree(profiles_str);
    pa_hook_fire(&device->discovery->hooks[PA_BLUETOOTH_HOOK_DEVICE_CONNECTION_CHANGED], device);
}

static void device_start_waiting_for_profiles(pa_bluetooth_device *device) {
    pa_assert(!device->wait_for_profiles_timer);
    device->wait_for_profiles_timer = pa_core_rttime_new(device->discovery->core,
                                                         pa_rtclock_now() + WAIT_FOR_PROFILES_TIMEOUT_USEC,
                                                         wait_for_profiles_cb, device);
}

342
void pa_bluetooth_transport_set_state(pa_bluetooth_transport *t, pa_bluetooth_transport_state_t state) {
343
    bool old_any_connected;
344
    unsigned n_disconnected_profile_uuids;
345 346
    bool new_device_appeared;
    bool device_disconnected;
347 348 349 350 351 352 353 354

    pa_assert(t);

    if (t->state == state)
        return;

    old_any_connected = pa_bluetooth_device_any_transport_connected(t->device);

355
    pa_log_debug("Transport %s state: %s -> %s",
356 357 358 359 360 361
                 t->path, transport_state_to_string(t->state), transport_state_to_string(state));

    t->state = state;

    pa_hook_fire(&t->device->discovery->hooks[PA_BLUETOOTH_HOOK_TRANSPORT_STATE_CHANGED], t);

362 363 364 365 366 367 368
    /* If there are profiles that are expected to get connected soon (based
     * on the UUID list), we wait for a bit before announcing the new
     * device, so that all profiles have time to get connected before the
     * card object is created. If we didn't wait, the card would always
     * have only one profile marked as available in the initial state,
     * which would prevent module-card-restore from restoring the initial
     * profile properly. */
369

370
    n_disconnected_profile_uuids = device_count_disconnected_profile_uuids(t->device);
371

372 373
    new_device_appeared = !old_any_connected && pa_bluetooth_device_any_transport_connected(t->device);
    device_disconnected = old_any_connected && !pa_bluetooth_device_any_transport_connected(t->device);
374

375
    if (new_device_appeared) {
376
        if (n_disconnected_profile_uuids > 0)
377 378 379
            device_start_waiting_for_profiles(t->device);
        else
            pa_hook_fire(&t->device->discovery->hooks[PA_BLUETOOTH_HOOK_DEVICE_CONNECTION_CHANGED], t->device);
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
        return;
    }

    if (device_disconnected) {
        if (t->device->wait_for_profiles_timer) {
            /* If the timer is still running when the device disconnects, we
             * never sent the notification of the device getting connected, so
             * we don't need to send a notification about the disconnection
             * either. Let's just stop the timer. */
            device_stop_waiting_for_profiles(t->device);
        } else
            pa_hook_fire(&t->device->discovery->hooks[PA_BLUETOOTH_HOOK_DEVICE_CONNECTION_CHANGED], t->device);
        return;
    }

395
    if (n_disconnected_profile_uuids == 0 && t->device->wait_for_profiles_timer) {
396 397 398 399
        /* All profiles are now connected, so we can stop the wait timer and
         * send a notification of the new device. */
        device_stop_waiting_for_profiles(t->device);
        pa_hook_fire(&t->device->discovery->hooks[PA_BLUETOOTH_HOOK_DEVICE_CONNECTION_CHANGED], t->device);
400
    }
401 402
}

403 404 405 406 407
pa_bluetooth_transport *pa_bluetooth_transport_get(pa_bluetooth_discovery *y, const char *path) {
    pa_assert(path);
    return pa_hashmap_get(y->transports, path);
}

408 409 410 411
pa_hashmap *pa_bluetooth_transport_get_all(pa_bluetooth_discovery *y) {
    return y->transports;
}

412
void pa_bluetooth_transport_put(pa_bluetooth_transport *t) {
413 414 415 416
    pa_assert(t);

    t->device->transports[t->profile] = t;
    pa_assert_se(pa_hashmap_put(t->device->discovery->transports, t->path, t) >= 0);
417
    pa_bluetooth_transport_set_state(t, PA_BLUETOOTH_TRANSPORT_STATE_IDLE);
418 419 420 421 422
}

void pa_bluetooth_transport_free(pa_bluetooth_transport *t) {
    pa_assert(t);

423 424
    if (t->destroy)
        t->destroy(t);
425 426 427 428

    pa_bluetooth_transport_set_state(t, PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED);
    pa_hashmap_remove(t->device->discovery->transports, t->path);
    t->device->transports[t->profile] = NULL;
429

430 431 432 433 434 435
    pa_xfree(t->owner);
    pa_xfree(t->path);
    pa_xfree(t->config);
    pa_xfree(t);
}

436 437
static void bluez5_transport_acquire_reply(DBusPendingCall *pending, void *userdata) {
    DBusMessage *r;
438
    DBusError err;
439 440 441 442 443 444
    pa_dbus_pending *p;
    pa_bluetooth_discovery *y;
    pa_bluetooth_transport *t;
    struct pending_transport_fd *pending_transport_fd;
    char *path;
    int fd;
445 446
    uint16_t i, o;

447 448 449 450 451
    pa_assert(pending);
    pa_assert_se(p = userdata);
    pa_assert_se(y = p->context_data);
    pa_assert_se(path = p->call_data);
    pa_assert_se(r = dbus_pending_call_steal_reply(pending));
452 453 454

    dbus_error_init(&err);

455 456 457
    if (dbus_message_get_type(r) == DBUS_MESSAGE_TYPE_ERROR) {
        pa_log_error("Transport Acquire() failed for transport %s (%s)", path, pa_dbus_get_error_message(r));
        goto failed;
458 459
    }

460
    if (!dbus_message_get_args(r, &err, DBUS_TYPE_UNIX_FD, &fd, DBUS_TYPE_UINT16, &i, DBUS_TYPE_UINT16, &o, DBUS_TYPE_INVALID)) {
461
        pa_log_error("Failed to parse Acquire() reply: %s", err.message);
462 463 464 465 466 467 468 469 470 471 472 473 474 475
        goto failed;
    }

    pa_log_info("Transport %s acquired", path);
    goto success;

failed:
    /* If transport state is not disconnected then switch it to disconnected state and
     * then to idle state so sinks and sources are properly released and connection
     * attempt is marked as failed, this also trigger profile change to off */
    t = pa_bluetooth_transport_get(y, path);
    if (t && t->state > PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED) {
        pa_bluetooth_transport_set_state(t, PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED);
        pa_bluetooth_transport_set_state(t, PA_BLUETOOTH_TRANSPORT_STATE_IDLE);
476 477
    }

478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
    fd = -1;
    i = 0;
    o = 0;
    /* fall through, we need to put failure into pending_transport_fds hashmap */

success:
    pending_transport_fd = pa_hashmap_get(y->pending_transport_fds, path);
    if (!pending_transport_fd) {
        pending_transport_fd = pa_xnew0(struct pending_transport_fd, 1);
        pending_transport_fd->discovery = y;
        pending_transport_fd->path = pa_xstrdup(path);
        pa_hashmap_put(y->pending_transport_fds, pending_transport_fd->path, pending_transport_fd);
    } else if (pending_transport_fd->fd != fd) {
        pa_log_info("Closing staled pending fd %d for transport %s", pending_transport_fd->fd, path);
        close(pending_transport_fd->fd);
    }

    pending_transport_fd->fd = fd;
    pending_transport_fd->imtu = i;
    pending_transport_fd->omtu = o;

/* finish: */
    dbus_error_free(&err);
    dbus_message_unref(r);

    PA_LLIST_REMOVE(pa_dbus_pending, y->pending, p);
    pa_dbus_pending_free(p);

    pa_xfree(path);
}

static int bluez5_transport_acquire_cb(pa_bluetooth_transport *t, size_t *imtu, size_t *omtu) {
    struct pending_transport_fd *pending_transport_fd;
    DBusMessage *m;
    int fd;

    pa_assert(t);
    pa_assert(t->device);
    pa_assert(t->device->discovery);

    pending_transport_fd = pa_hashmap_remove(t->device->discovery->pending_transport_fds, t->path);
    if (!pending_transport_fd) {
        pa_assert_se(m = dbus_message_new_method_call(t->owner, t->path, BLUEZ_MEDIA_TRANSPORT_INTERFACE, "Acquire"));
        send_and_add_to_pending(t->device->discovery, m, bluez5_transport_acquire_reply, pa_xstrdup(t->path));
        return -EAGAIN;
    }

    fd = pending_transport_fd->fd;

527
    if (imtu)
528
        *imtu = pending_transport_fd->imtu;
529 530

    if (omtu)
531
        *omtu = pending_transport_fd->omtu;
532

533 534 535 536
    pa_xfree(pending_transport_fd->path);
    pa_xfree(pending_transport_fd);

    return fd;
537 538 539
}

static void bluez5_transport_release_cb(pa_bluetooth_transport *t) {
540
    DBusMessage *m;
541 542 543 544 545 546 547 548 549 550 551

    pa_assert(t);
    pa_assert(t->device);
    pa_assert(t->device->discovery);

    if (t->state <= PA_BLUETOOTH_TRANSPORT_STATE_IDLE) {
        pa_log_info("Transport %s auto-released by BlueZ or already released", t->path);
        return;
    }

    pa_assert_se(m = dbus_message_new_method_call(t->owner, t->path, BLUEZ_MEDIA_TRANSPORT_INTERFACE, "Release"));
552 553 554
    pa_assert_se(dbus_connection_send(pa_dbus_connection_get(t->device->discovery->connection), m, NULL));
    pa_log_info("Transport %s released", t->path);
}
555

556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
static void bluez5_transport_release_staled_pending_fd(struct pending_transport_fd *pending_transport_fd) {
    pa_bluetooth_transport *t;

    pa_assert(pending_transport_fd);
    pa_assert(pending_transport_fd->discovery);

    pa_log_info("Releasing staled pending transport %s", pending_transport_fd->path);

    t = pa_hashmap_get(pending_transport_fd->discovery->transports, pending_transport_fd->path);
    if (t)
        bluez5_transport_release_cb(t);

    close(pending_transport_fd->fd);

    pa_xfree(pending_transport_fd->path);
    pa_xfree(pending_transport_fd);
572 573 574
}

bool pa_bluetooth_device_any_transport_connected(const pa_bluetooth_device *d) {
575
    unsigned i, bluetooth_profile_count;
576 577 578

    pa_assert(d);

579
    if (!d->valid)
580 581
        return false;

582 583
    bluetooth_profile_count = pa_bluetooth_profile_count();
    for (i = 0; i < bluetooth_profile_count; i++)
584 585 586 587 588 589
        if (d->transports[i] && d->transports[i]->state != PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED)
            return true;

    return false;
}

590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
bool pa_bluetooth_device_a2dp_sink_transport_connected(const pa_bluetooth_device *d) {
    unsigned i, bluetooth_profile_count;

    pa_assert(d);

    if (!d->valid)
        return false;

    bluetooth_profile_count = pa_bluetooth_profile_count();
    for (i = 0; i < bluetooth_profile_count; i++)
        if (pa_bluetooth_profile_is_a2dp_sink(i) && d->transports[i] && d->transports[i]->state != PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED)
            return true;

    return false;
}

bool pa_bluetooth_device_a2dp_source_transport_connected(const pa_bluetooth_device *d) {
    unsigned i, bluetooth_profile_count;

    pa_assert(d);

    if (!d->valid)
        return false;

    bluetooth_profile_count = pa_bluetooth_profile_count();
    for (i = 0; i < bluetooth_profile_count; i++)
        if (pa_bluetooth_profile_is_a2dp_source(i) && d->transports[i] && d->transports[i]->state != PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED)
            return true;

    return false;
}

622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
static int transport_state_from_string(const char* value, pa_bluetooth_transport_state_t *state) {
    pa_assert(value);
    pa_assert(state);

    if (pa_streq(value, "idle"))
        *state = PA_BLUETOOTH_TRANSPORT_STATE_IDLE;
    else if (pa_streq(value, "pending") || pa_streq(value, "active"))
        *state = PA_BLUETOOTH_TRANSPORT_STATE_PLAYING;
    else
        return -1;

    return 0;
}

static void parse_transport_property(pa_bluetooth_transport *t, DBusMessageIter *i) {
    const char *key;
    DBusMessageIter variant_i;

    key = check_variant_property(i);
    if (key == NULL)
        return;

    dbus_message_iter_recurse(i, &variant_i);

    switch (dbus_message_iter_get_arg_type(&variant_i)) {

        case DBUS_TYPE_STRING: {

            const char *value;
            dbus_message_iter_get_basic(&variant_i, &value);

            if (pa_streq(key, "State")) {
                pa_bluetooth_transport_state_t state;

                if (transport_state_from_string(value, &state) < 0) {
                    pa_log_error("Invalid state received: %s", value);
                    return;
                }

661
                pa_bluetooth_transport_set_state(t, state);
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
            }

            break;
        }
    }

    return;
}

static int parse_transport_properties(pa_bluetooth_transport *t, DBusMessageIter *i) {
    DBusMessageIter element_i;

    dbus_message_iter_recurse(i, &element_i);

    while (dbus_message_iter_get_arg_type(&element_i) == DBUS_TYPE_DICT_ENTRY) {
        DBusMessageIter dict_i;

        dbus_message_iter_recurse(&element_i, &dict_i);

        parse_transport_property(t, &dict_i);

        dbus_message_iter_next(&element_i);
    }

    return 0;
}

689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
static unsigned pa_a2dp_codec_id_hash_func(const void *_p) {
    unsigned hash;
    const pa_a2dp_codec_id *p = _p;

    hash = p->codec_id;
    hash = 31 * hash + ((p->vendor_id >>  0) & 0xFF);
    hash = 31 * hash + ((p->vendor_id >>  8) & 0xFF);
    hash = 31 * hash + ((p->vendor_id >> 16) & 0xFF);
    hash = 31 * hash + ((p->vendor_id >> 24) & 0xFF);
    hash = 31 * hash + ((p->vendor_codec_id >> 0) & 0xFF);
    hash = 31 * hash + ((p->vendor_codec_id >> 8) & 0xFF);
    return hash;
}

static int pa_a2dp_codec_id_compare_func(const void *_a, const void *_b) {
    const pa_a2dp_codec_id *a = _a;
    const pa_a2dp_codec_id *b = _b;

    if (a->codec_id < b->codec_id)
        return -1;
    if (a->codec_id > b->codec_id)
        return 1;

    if (a->vendor_id < b->vendor_id)
        return -1;
    if (a->vendor_id > b->vendor_id)
        return 1;

    if (a->vendor_codec_id < b->vendor_codec_id)
        return -1;
    if (a->vendor_codec_id > b->vendor_codec_id)
        return 1;

    return 0;
}

725 726 727 728 729 730 731 732 733
static pa_bluetooth_device* device_create(pa_bluetooth_discovery *y, const char *path) {
    pa_bluetooth_device *d;

    pa_assert(y);
    pa_assert(path);

    d = pa_xnew0(pa_bluetooth_device, 1);
    d->discovery = y;
    d->path = pa_xstrdup(path);
734
    d->uuids = pa_hashmap_new_full(pa_idxset_string_hash_func, pa_idxset_string_compare_func, NULL, pa_xfree);
735 736 737
    d->a2dp_sink_endpoints = pa_hashmap_new_full(pa_a2dp_codec_id_hash_func, pa_a2dp_codec_id_compare_func, pa_xfree, (pa_free_cb_t)pa_hashmap_free);
    d->a2dp_source_endpoints = pa_hashmap_new_full(pa_a2dp_codec_id_hash_func, pa_a2dp_codec_id_compare_func, pa_xfree, (pa_free_cb_t)pa_hashmap_free);
    d->transports = pa_xnew0(pa_bluetooth_transport *, pa_bluetooth_profile_count());
738 739 740 741 742 743 744 745 746 747 748 749 750

    pa_hashmap_put(y->devices, d->path, d);

    return d;
}

pa_bluetooth_device* pa_bluetooth_discovery_get_device_by_path(pa_bluetooth_discovery *y, const char *path) {
    pa_bluetooth_device *d;

    pa_assert(y);
    pa_assert(PA_REFCNT_VALUE(y) > 0);
    pa_assert(path);

751 752
    if ((d = pa_hashmap_get(y->devices, path)) && d->valid)
        return d;
753 754 755 756 757 758 759 760 761 762 763 764 765 766

    return NULL;
}

pa_bluetooth_device* pa_bluetooth_discovery_get_device_by_address(pa_bluetooth_discovery *y, const char *remote, const char *local) {
    pa_bluetooth_device *d;
    void *state = NULL;

    pa_assert(y);
    pa_assert(PA_REFCNT_VALUE(y) > 0);
    pa_assert(remote);
    pa_assert(local);

    while ((d = pa_hashmap_iterate(y->devices, &state, NULL)))
767
        if (d->valid && pa_streq(d->address, remote) && pa_streq(d->adapter->address, local))
768
            return d;
769 770 771 772

    return NULL;
}

773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
static void remote_endpoint_remove(pa_bluetooth_discovery *y, const char *path) {
    pa_bluetooth_device *device;
    pa_hashmap *endpoints;
    void *devices_state;
    void *state;

    PA_HASHMAP_FOREACH(device, y->devices, devices_state) {
        PA_HASHMAP_FOREACH(endpoints, device->a2dp_sink_endpoints, state)
            pa_hashmap_remove_and_free(endpoints, path);

        PA_HASHMAP_FOREACH(endpoints, device->a2dp_source_endpoints, state)
            pa_hashmap_remove_and_free(endpoints, path);
    }

    pa_log_debug("Remote endpoint %s was removed", path);
}

790
static void device_free(pa_bluetooth_device *d) {
791
    unsigned i, bluetooth_profile_count;
792

793 794
    pa_assert(d);

795 796
    device_stop_waiting_for_profiles(d);

797 798
    pa_hook_fire(&d->discovery->hooks[PA_BLUETOOTH_HOOK_DEVICE_UNLINK], d);

799 800
    bluetooth_profile_count = pa_bluetooth_profile_count();
    for (i = 0; i < bluetooth_profile_count; i++) {
801 802 803 804 805 806 807 808
        pa_bluetooth_transport *t;

        if (!(t = d->transports[i]))
            continue;

        pa_bluetooth_transport_free(t);
    }

809 810 811
    pa_hashmap_free(d->uuids);
    pa_hashmap_free(d->a2dp_sink_endpoints);
    pa_hashmap_free(d->a2dp_source_endpoints);
812

813
    pa_xfree(d->transports);
814 815 816
    pa_xfree(d->path);
    pa_xfree(d->alias);
    pa_xfree(d->address);
817
    pa_xfree(d->adapter_path);
818 819 820 821 822 823 824 825 826 827 828 829 830 831
    pa_xfree(d);
}

static void device_remove(pa_bluetooth_discovery *y, const char *path) {
    pa_bluetooth_device *d;

    if (!(d = pa_hashmap_remove(y->devices, path)))
        pa_log_warn("Unknown device removed %s", path);
    else {
        pa_log_debug("Device %s removed", path);
        device_free(d);
    }
}

832
static void device_set_valid(pa_bluetooth_device *device, bool valid) {
833 834
    bool old_any_connected;

835 836
    pa_assert(device);

837
    if (valid == device->valid)
838 839
        return;

840
    old_any_connected = pa_bluetooth_device_any_transport_connected(device);
841
    device->valid = valid;
842 843 844

    if (pa_bluetooth_device_any_transport_connected(device) != old_any_connected)
        pa_hook_fire(&device->discovery->hooks[PA_BLUETOOTH_HOOK_DEVICE_CONNECTION_CHANGED], device);
845 846
}

847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
static void device_update_valid(pa_bluetooth_device *d) {
    pa_assert(d);

    if (!d->properties_received) {
        pa_assert(!d->valid);
        return;
    }

    /* Check if mandatory properties are set. */
    if (!d->address || !d->adapter_path || !d->alias) {
        device_set_valid(d, false);
        return;
    }

    if (!d->adapter || !d->adapter->valid) {
        device_set_valid(d, false);
        return;
    }

    device_set_valid(d, true);
}

static void device_set_adapter(pa_bluetooth_device *device, pa_bluetooth_adapter *adapter) {
    pa_assert(device);

    if (adapter == device->adapter)
        return;

    device->adapter = adapter;

    device_update_valid(device);
}

880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
static pa_bluetooth_adapter* adapter_create(pa_bluetooth_discovery *y, const char *path) {
    pa_bluetooth_adapter *a;

    pa_assert(y);
    pa_assert(path);

    a = pa_xnew0(pa_bluetooth_adapter, 1);
    a->discovery = y;
    a->path = pa_xstrdup(path);

    pa_hashmap_put(y->adapters, a->path, a);

    return a;
}

895 896 897 898 899 900 901 902
static void adapter_free(pa_bluetooth_adapter *a) {
    pa_bluetooth_device *d;
    void *state;

    pa_assert(a);
    pa_assert(a->discovery);

    PA_HASHMAP_FOREACH(d, a->discovery->devices, state)
903 904
        if (d->adapter == a)
            device_set_adapter(d, NULL);
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921

    pa_xfree(a->path);
    pa_xfree(a->address);
    pa_xfree(a);
}

static void adapter_remove(pa_bluetooth_discovery *y, const char *path) {
    pa_bluetooth_adapter *a;

    if (!(a = pa_hashmap_remove(y->adapters, path)))
        pa_log_warn("Unknown adapter removed %s", path);
    else {
        pa_log_debug("Adapter %s removed", path);
        adapter_free(a);
    }
}

922
static void parse_device_property(pa_bluetooth_device *d, DBusMessageIter *i) {
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
    const char *key;
    DBusMessageIter variant_i;

    pa_assert(d);

    key = check_variant_property(i);
    if (key == NULL) {
        pa_log_error("Received invalid property for device %s", d->path);
        return;
    }

    dbus_message_iter_recurse(i, &variant_i);

    switch (dbus_message_iter_get_arg_type(&variant_i)) {

        case DBUS_TYPE_STRING: {
            const char *value;
            dbus_message_iter_get_basic(&variant_i, &value);

            if (pa_streq(key, "Alias")) {
                pa_xfree(d->alias);
                d->alias = pa_xstrdup(value);
                pa_log_debug("%s: %s", key, value);
            } else if (pa_streq(key, "Address")) {
947
                if (d->properties_received) {
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
                    pa_log_warn("Device property 'Address' expected to be constant but changed for %s, ignoring", d->path);
                    return;
                }

                if (d->address) {
                    pa_log_warn("Device %s: Received a duplicate 'Address' property, ignoring", d->path);
                    return;
                }

                d->address = pa_xstrdup(value);
                pa_log_debug("%s: %s", key, value);
            }

            break;
        }

        case DBUS_TYPE_OBJECT_PATH: {
            const char *value;
            dbus_message_iter_get_basic(&variant_i, &value);

            if (pa_streq(key, "Adapter")) {

970
                if (d->properties_received) {
971 972 973 974
                    pa_log_warn("Device property 'Adapter' expected to be constant but changed for %s, ignoring", d->path);
                    return;
                }

975
                if (d->adapter_path) {
976 977 978 979
                    pa_log_warn("Device %s: Received a duplicate 'Adapter' property, ignoring", d->path);
                    return;
                }

980
                d->adapter_path = pa_xstrdup(value);
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
                pa_log_debug("%s: %s", key, value);
            }

            break;
        }

        case DBUS_TYPE_UINT32: {
            uint32_t value;
            dbus_message_iter_get_basic(&variant_i, &value);

            if (pa_streq(key, "Class")) {
                d->class_of_device = value;
                pa_log_debug("%s: %d", key, value);
            }

            break;
        }

        case DBUS_TYPE_ARRAY: {
            DBusMessageIter ai;
            dbus_message_iter_recurse(&variant_i, &ai);

            if (dbus_message_iter_get_arg_type(&ai) == DBUS_TYPE_STRING && pa_streq(key, "UUIDs")) {
1004 1005
                /* bluetoothd never removes UUIDs from a device object so we
                 * don't need to check for disappeared UUIDs here. */
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
                while (dbus_message_iter_get_arg_type(&ai) != DBUS_TYPE_INVALID) {
                    const char *value;
                    char *uuid;

                    dbus_message_iter_get_basic(&ai, &value);

                    if (pa_hashmap_get(d->uuids, value)) {
                        dbus_message_iter_next(&ai);
                        continue;
                    }

                    uuid = pa_xstrdup(value);
                    pa_hashmap_put(d->uuids, uuid, uuid);

                    pa_log_debug("%s: %s", key, value);
                    dbus_message_iter_next(&ai);
                }
            }

            break;
        }
    }
}

1030
static void parse_device_properties(pa_bluetooth_device *d, DBusMessageIter *i) {
1031 1032 1033 1034 1035 1036 1037 1038
    DBusMessageIter element_i;

    dbus_message_iter_recurse(i, &element_i);

    while (dbus_message_iter_get_arg_type(&element_i) == DBUS_TYPE_DICT_ENTRY) {
        DBusMessageIter dict_i;

        dbus_message_iter_recurse(&element_i, &dict_i);
1039
        parse_device_property(d, &dict_i);
1040 1041 1042
        dbus_message_iter_next(&element_i);
    }

1043 1044
    if (!d->properties_received) {
        d->properties_received = true;
1045
        device_update_valid(d);
1046

1047 1048 1049
        if (!d->address || !d->adapter_path || !d->alias)
            pa_log_error("Non-optional information missing for device %s", d->path);
    }
1050 1051
}

1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
static void parse_remote_endpoint_properties(pa_bluetooth_discovery *y, const char *endpoint, DBusMessageIter *i) {
    DBusMessageIter element_i;
    pa_bluetooth_device *device;
    pa_hashmap *codec_endpoints;
    pa_hashmap *endpoints;
    pa_a2dp_codec_id *a2dp_codec_id;
    struct a2dp_codec_capabilities *a2dp_codec_capabilities;
    const char *uuid = NULL;
    const char *device_path = NULL;
    uint8_t codec_id = 0;
    bool have_codec_id = false;
    const uint8_t *capabilities = NULL;
    int capabilities_size = 0;

    pa_log_debug("Parsing remote endpoint %s", endpoint);

    dbus_message_iter_recurse(i, &element_i);

    while (dbus_message_iter_get_arg_type(&element_i) == DBUS_TYPE_DICT_ENTRY) {
        DBusMessageIter dict_i, variant_i;
        const char *key;

        dbus_message_iter_recurse(&element_i, &dict_i);

        key = check_variant_property(&dict_i);
        if (key == NULL) {
            pa_log_error("Received invalid property for remote endpoint %s", endpoint);
            return;
        }

        dbus_message_iter_recurse(&dict_i, &variant_i);

        if (pa_streq(key, "UUID")) {
            if (dbus_message_iter_get_arg_type(&variant_i) != DBUS_TYPE_STRING) {
                pa_log_warn("Remote endpoint %s property 'UUID' is not string, ignoring", endpoint);
                return;
            }

            dbus_message_iter_get_basic(&variant_i, &uuid);
        } else if (pa_streq(key, "Codec")) {
            if (dbus_message_iter_get_arg_type(&variant_i) != DBUS_TYPE_BYTE) {
                pa_log_warn("Remote endpoint %s property 'Codec' is not byte, ignoring", endpoint);
                return;
            }

            dbus_message_iter_get_basic(&variant_i, &codec_id);
            have_codec_id = true;
        } else if (pa_streq(key, "Capabilities")) {
            DBusMessageIter array;

            if (dbus_message_iter_get_arg_type(&variant_i) != DBUS_TYPE_ARRAY) {
                pa_log_warn("Remote endpoint %s property 'Capabilities' is not array, ignoring", endpoint);
                return;
            }

            dbus_message_iter_recurse(&variant_i, &array);
            if (dbus_message_iter_get_arg_type(&array) != DBUS_TYPE_BYTE) {
                pa_log_warn("Remote endpoint %s property 'Capabilities' is not array of bytes, ignoring", endpoint);
                return;
            }

            dbus_message_iter_get_fixed_array(&array, &capabilities, &capabilities_size);
        } else if (pa_streq(key, "Device")) {
            if (dbus_message_iter_get_arg_type(&variant_i) != DBUS_TYPE_OBJECT_PATH) {
                pa_log_warn("Remote endpoint %s property 'Device' is not path, ignoring", endpoint);
                return;
            }

            dbus_message_iter_get_basic(&variant_i, &device_path);
        }

        dbus_message_iter_next(&element_i);
    }

    if (!uuid) {
        pa_log_warn("Remote endpoint %s does not have property 'UUID', ignoring", endpoint);
        return;
    }

    if (!have_codec_id) {
        pa_log_warn("Remote endpoint %s does not have property 'Codec', ignoring", endpoint);
        return;
    }

    if (!capabilities || !capabilities_size) {
        pa_log_warn("Remote endpoint %s does not have property 'Capabilities', ignoring", endpoint);
        return;
    }

    if (!device_path) {
        pa_log_warn("Remote endpoint %s does not have property 'Device', ignoring", endpoint);
        return;
    }

    device = pa_hashmap_get(y->devices, device_path);
    if (!device) {
        pa_log_warn("Device for remote endpoint %s was not found", endpoint);
        return;
    }

    if (pa_streq(uuid, PA_BLUETOOTH_UUID_A2DP_SINK)) {
        codec_endpoints = device->a2dp_sink_endpoints;
    } else if (pa_streq(uuid, PA_BLUETOOTH_UUID_A2DP_SOURCE)) {
        codec_endpoints = device->a2dp_source_endpoints;
    } else {
        pa_log_warn("Remote endpoint %s does not have valid property 'UUID', ignoring", endpoint);
        return;
    }

    if (capabilities_size < 0 || capabilities_size > MAX_A2DP_CAPS_SIZE) {
        pa_log_warn("Remote endpoint %s does not have valid property 'Capabilities', ignoring", endpoint);
        return;
    }

    a2dp_codec_id = pa_xmalloc0(sizeof(*a2dp_codec_id));
    a2dp_codec_id->codec_id = codec_id;
    if (codec_id == A2DP_CODEC_VENDOR) {
        if ((size_t)capabilities_size < sizeof(a2dp_vendor_codec_t)) {
            pa_log_warn("Remote endpoint %s does not have valid property 'Capabilities', ignoring", endpoint);
            return;
        }
        a2dp_codec_id->vendor_id = A2DP_GET_VENDOR_ID(*(a2dp_vendor_codec_t *)capabilities);
        a2dp_codec_id->vendor_codec_id = A2DP_GET_CODEC_ID(*(a2dp_vendor_codec_t *)capabilities);
    } else {
        a2dp_codec_id->vendor_id = 0;
        a2dp_codec_id->vendor_codec_id = 0;
    }

    a2dp_codec_capabilities = pa_xmalloc0(sizeof(*a2dp_codec_capabilities) + capabilities_size);
    a2dp_codec_capabilities->size = capabilities_size;
    memcpy(a2dp_codec_capabilities->buffer, capabilities, capabilities_size);

    endpoints = pa_hashmap_get(codec_endpoints, a2dp_codec_id);
    if (!endpoints) {
        endpoints = pa_hashmap_new_full(pa_idxset_string_hash_func, pa_idxset_string_compare_func, pa_xfree, pa_xfree);
        pa_hashmap_put(codec_endpoints, a2dp_codec_id, endpoints);
    }

    if (pa_hashmap_remove_and_free(endpoints, endpoint) >= 0)
        pa_log_debug("Replacing existing remote endpoint %s", endpoint);
    pa_hashmap_put(endpoints, pa_xstrdup(endpoint), a2dp_codec_capabilities);
}

1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
static void parse_adapter_properties(pa_bluetooth_adapter *a, DBusMessageIter *i, bool is_property_change) {
    DBusMessageIter element_i;

    pa_assert(a);

    dbus_message_iter_recurse(i, &element_i);

    while (dbus_message_iter_get_arg_type(&element_i) == DBUS_TYPE_DICT_ENTRY) {
        DBusMessageIter dict_i, variant_i;
        const char *key;

        dbus_message_iter_recurse(&element_i, &dict_i);

        key = check_variant_property(&dict_i);
        if (key == NULL) {
            pa_log_error("Received invalid property for adapter %s", a->path);
            return;
        }

        dbus_message_iter_recurse(&dict_i, &variant_i);

        if (dbus_message_iter_get_arg_type(&variant_i) == DBUS_TYPE_STRING && pa_streq(key, "Address")) {
1217
            const char *value;
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230

            if (is_property_change) {
                pa_log_warn("Adapter property 'Address' expected to be constant but changed for %s, ignoring", a->path);
                return;
            }

            if (a->address) {
                pa_log_warn("Adapter %s received a duplicate 'Address' property, ignoring", a->path);
                return;
            }

            dbus_message_iter_get_basic(&variant_i, &value);
            a->address = pa_xstrdup(value);
1231
            a->valid = true;
1232 1233 1234 1235 1236 1237
        }

        dbus_message_iter_next(&element_i);
    }
}

1238
static void register_legacy_sbc_endpoint_reply(DBusPendingCall *pending, void *userdata) {
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
    DBusMessage *r;
    pa_dbus_pending *p;
    pa_bluetooth_discovery *y;
    char *endpoint;

    pa_assert(pending);
    pa_assert_se(p = userdata);
    pa_assert_se(y = p->context_data);
    pa_assert_se(endpoint = p->call_data);
    pa_assert_se(r = dbus_pending_call_steal_reply(pending));

    if (dbus_message_is_error(r, BLUEZ_ERROR_NOT_SUPPORTED)) {
1251
        pa_log_info("Couldn't register legacy sbc endpoint %s because it is disabled in BlueZ", endpoint);
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
        goto finish;
    }

    if (dbus_message_get_type(r) == DBUS_MESSAGE_TYPE_ERROR) {
        pa_log_error(BLUEZ_MEDIA_INTERFACE ".RegisterEndpoint() failed: %s: %s", dbus_message_get_error_name(r),
                     pa_dbus_get_error_message(r));
        goto finish;
    }

finish:
    dbus_message_unref(r);

    PA_LLIST_REMOVE(pa_dbus_pending, y->pending, p);
    pa_dbus_pending_free(p);

    pa_xfree(endpoint);
}

1270
static void register_legacy_sbc_endpoint(pa_bluetooth_discovery *y, const char *path, bool is_sink) {
1271 1272
    DBusMessage *m;
    DBusMessageIter i, d;
1273 1274 1275
    const pa_a2dp_codec *a2dp_codec_sbc;
    const char *endpoint;
    const char *uuid;
pali's avatar
pali committed
1276
    uint8_t codec_id;
1277 1278 1279 1280 1281 1282
    uint8_t capabilities_size;
    uint8_t capabilities[MAX_A2DP_CAPS_SIZE];

    pa_assert_se(a2dp_codec_sbc = pa_bluetooth_get_a2dp_codec("sbc"));
    uuid = is_sink ? PA_BLUETOOTH_UUID_A2DP_SINK : PA_BLUETOOTH_UUID_A2DP_SOURCE;
    endpoint = is_sink ? A2DP_SINK_ENDPOINT "/sbc" : A2DP_SOURCE_ENDPOINT "/sbc";
1283

1284
    pa_log_debug("Registering legacy sbc endpoint %s on adapter %s", endpoint, path);
1285

1286 1287
    codec_id = a2dp_codec_sbc->id.codec_id;
    capabilities_size = a2dp_codec_sbc->fill_capabilities(capabilities);
pali's avatar
pali committed
1288 1289
    pa_assert(capabilities_size != 0);

1290 1291 1292
    pa_assert_se(m = dbus_message_new_method_call(BLUEZ_SERVICE, path, BLUEZ_MEDIA_INTERFACE, "RegisterEndpoint"));

    dbus_message_iter_init_append(m, &i);
1293
    pa_assert_se(dbus_message_iter_append_basic(&i, DBUS_TYPE_OBJECT_PATH, &endpoint));
1294 1295 1296
    dbus_message_iter_open_container(&i, DBUS_TYPE_ARRAY, DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING DBUS_TYPE_STRING_AS_STRING
                                         DBUS_TYPE_VARIANT_AS_STRING DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &d);
    pa_dbus_append_basic_variant_dict_entry(&d, "UUID", DBUS_TYPE_STRING, &uuid);
pali's avatar
pali committed
1297 1298
    pa_dbus_append_basic_variant_dict_entry(&d, "Codec", DBUS_TYPE_BYTE, &codec_id);
    pa_dbus_append_basic_array_variant_dict_entry(&d, "Capabilities", DBUS_TYPE_BYTE, &capabilities, capabilities_size);
1299 1300 1301

    dbus_message_iter_close_container(&i, &d);

1302
    send_and_add_to_pending(y, m, register_legacy_sbc_endpoint_reply, pa_xstrdup(endpoint));
1303 1304
}

1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
static void register_application_reply(DBusPendingCall *pending, void *userdata) {
    DBusMessage *r;
    pa_dbus_pending *p;
    pa_bluetooth_adapter *a;
    pa_bluetooth_discovery *y;
    char *path;
    bool fallback = true;

    pa_assert(pending);
    pa_assert_se(p = userdata);
    pa_assert_se(y = p->context_data);
    pa_assert_se(path = p->call_data);
    pa_assert_se(r = dbus_pending_call_steal_reply(pending));