• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /***
2   This file is part of PulseAudio.
3 
4   Copyright 2014 Wim Taymans <wim.taymans at gmail.com>
5 
6   PulseAudio is free software; you can redistribute it and/or modify
7   it under the terms of the GNU Lesser General Public License as
8   published by the Free Software Foundation; either version 2.1 of the
9   License, or (at your option) any later version.
10 
11   PulseAudio is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   General Public License for more details.
15 
16   You should have received a copy of the GNU Lesser General Public
17   License along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
18 ***/
19 
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
23 
24 #include <pulsecore/shared.h>
25 #include <pulsecore/core-error.h>
26 #include <pulsecore/core-util.h>
27 #include <pulsecore/dbus-shared.h>
28 #include <pulsecore/log.h>
29 
30 #include <errno.h>
31 #include <sys/types.h>
32 #include <sys/socket.h>
33 
34 #include <bluetooth/bluetooth.h>
35 #include <bluetooth/sco.h>
36 
37 #include "bluez5-util.h"
38 
39 struct pa_bluetooth_backend {
40   pa_core *core;
41   pa_dbus_connection *connection;
42   pa_bluetooth_discovery *discovery;
43   bool enable_hs_role;
44 
45   PA_LLIST_HEAD(pa_dbus_pending, pending);
46 };
47 
48 struct transport_data {
49     int rfcomm_fd;
50     pa_io_event *rfcomm_io;
51     int sco_fd;
52     pa_io_event *sco_io;
53     pa_mainloop_api *mainloop;
54 };
55 
56 #define BLUEZ_SERVICE "org.bluez"
57 #define BLUEZ_MEDIA_TRANSPORT_INTERFACE BLUEZ_SERVICE ".MediaTransport1"
58 
59 #define BLUEZ_ERROR_NOT_SUPPORTED "org.bluez.Error.NotSupported"
60 
61 #define BLUEZ_PROFILE_MANAGER_INTERFACE BLUEZ_SERVICE ".ProfileManager1"
62 #define BLUEZ_PROFILE_INTERFACE BLUEZ_SERVICE ".Profile1"
63 
64 #define HSP_AG_PROFILE "/Profile/HSPAGProfile"
65 #define HSP_HS_PROFILE "/Profile/HSPHSProfile"
66 
67 /* RFCOMM channel for HSP headset role
68  * The choice seems to be a bit arbitrary -- it looks like at least channels 2, 4 and 5 also work*/
69 #define HSP_HS_DEFAULT_CHANNEL  3
70 
71 #define PROFILE_INTROSPECT_XML                                          \
72     DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE                           \
73     "<node>"                                                            \
74     " <interface name=\"" BLUEZ_PROFILE_INTERFACE "\">"                 \
75     "  <method name=\"Release\">"                                       \
76     "  </method>"                                                       \
77     "  <method name=\"RequestDisconnection\">"                          \
78     "   <arg name=\"device\" direction=\"in\" type=\"o\"/>"             \
79     "  </method>"                                                       \
80     "  <method name=\"NewConnection\">"                                 \
81     "   <arg name=\"device\" direction=\"in\" type=\"o\"/>"             \
82     "   <arg name=\"fd\" direction=\"in\" type=\"h\"/>"                 \
83     "   <arg name=\"opts\" direction=\"in\" type=\"a{sv}\"/>"           \
84     "  </method>"                                                       \
85     " </interface>"                                                     \
86     " <interface name=\"org.freedesktop.DBus.Introspectable\">"         \
87     "  <method name=\"Introspect\">"                                    \
88     "   <arg name=\"data\" type=\"s\" direction=\"out\"/>"              \
89     "  </method>"                                                       \
90     " </interface>"                                                     \
91     "</node>"
92 
send_and_add_to_pending(pa_bluetooth_backend * backend,DBusMessage * m,DBusPendingCallNotifyFunction func,void * call_data)93 static pa_dbus_pending* send_and_add_to_pending(pa_bluetooth_backend *backend, DBusMessage *m,
94         DBusPendingCallNotifyFunction func, void *call_data) {
95 
96     pa_dbus_pending *p;
97     DBusPendingCall *call;
98 
99     pa_assert(backend);
100     pa_assert(m);
101 
102     pa_assert_se(dbus_connection_send_with_reply(pa_dbus_connection_get(backend->connection), m, &call, -1));
103 
104     p = pa_dbus_pending_new(pa_dbus_connection_get(backend->connection), m, call, backend, call_data);
105     PA_LLIST_PREPEND(pa_dbus_pending, backend->pending, p);
106     dbus_pending_call_set_notify(call, func, p, NULL);
107 
108     return p;
109 }
110 
sco_do_connect(pa_bluetooth_transport * t)111 static int sco_do_connect(pa_bluetooth_transport *t) {
112     pa_bluetooth_device *d = t->device;
113     struct sockaddr_sco addr;
114     socklen_t len;
115     int err, i;
116     int sock;
117     bdaddr_t src;
118     bdaddr_t dst;
119     const char *src_addr, *dst_addr;
120 
121     src_addr = d->adapter->address;
122     dst_addr = d->address;
123 
124     /* don't use ba2str to avoid -lbluetooth */
125     for (i = 5; i >= 0; i--, src_addr += 3)
126         src.b[i] = strtol(src_addr, NULL, 16);
127     for (i = 5; i >= 0; i--, dst_addr += 3)
128         dst.b[i] = strtol(dst_addr, NULL, 16);
129 
130     sock = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO);
131     if (sock < 0) {
132         pa_log_error("socket(SEQPACKET, SCO) %s", pa_cstrerror(errno));
133         return -1;
134     }
135 
136     len = sizeof(addr);
137     memset(&addr, 0, len);
138     addr.sco_family = AF_BLUETOOTH;
139     bacpy(&addr.sco_bdaddr, &src);
140 
141     if (bind(sock, (struct sockaddr *) &addr, len) < 0) {
142         pa_log_error("bind(): %s", pa_cstrerror(errno));
143         goto fail_close;
144     }
145 
146     memset(&addr, 0, len);
147     addr.sco_family = AF_BLUETOOTH;
148     bacpy(&addr.sco_bdaddr, &dst);
149 
150     pa_log_info("doing connect");
151     err = connect(sock, (struct sockaddr *) &addr, len);
152     if (err < 0 && !(errno == EAGAIN || errno == EINPROGRESS)) {
153         pa_log_error("connect(): %s", pa_cstrerror(errno));
154         goto fail_close;
155     }
156     return sock;
157 
158 fail_close:
159     close(sock);
160     return -1;
161 }
162 
sco_do_accept(pa_bluetooth_transport * t)163 static int sco_do_accept(pa_bluetooth_transport *t) {
164     struct transport_data *trd = t->userdata;
165     struct sockaddr_sco addr;
166     socklen_t optlen;
167     int sock;
168 
169     memset(&addr, 0, sizeof(addr));
170     optlen = sizeof(addr);
171 
172     pa_log_info ("doing accept");
173     sock = accept(trd->sco_fd, (struct sockaddr *) &addr, &optlen);
174     if (sock < 0) {
175         if (errno != EAGAIN)
176             pa_log_error("accept(): %s", pa_cstrerror(errno));
177         goto fail;
178     }
179     return sock;
180 
181 fail:
182     return -1;
183 }
184 
sco_acquire_cb(pa_bluetooth_transport * t,bool optional,size_t * imtu,size_t * omtu)185 static int sco_acquire_cb(pa_bluetooth_transport *t, bool optional, size_t *imtu, size_t *omtu) {
186     int sock;
187     socklen_t len;
188 
189     if (optional)
190         sock = sco_do_accept(t);
191     else
192         sock = sco_do_connect(t);
193 
194     if (sock < 0)
195         goto fail;
196 
197     if (imtu) *imtu = 48;
198     if (omtu) *omtu = 48;
199 
200     if (t->device->autodetect_mtu) {
201         struct sco_options sco_opt;
202 
203         len = sizeof(sco_opt);
204         memset(&sco_opt, 0, len);
205 
206         if (getsockopt(sock, SOL_SCO, SCO_OPTIONS, &sco_opt, &len) < 0)
207             pa_log_warn("getsockopt(SCO_OPTIONS) failed, loading defaults");
208         else {
209             pa_log_debug("autodetected imtu = omtu = %u", sco_opt.mtu);
210             if (imtu) *imtu = sco_opt.mtu;
211             if (omtu) *omtu = sco_opt.mtu;
212         }
213     }
214 
215     return sock;
216 
217 fail:
218     return -1;
219 }
220 
sco_release_cb(pa_bluetooth_transport * t)221 static void sco_release_cb(pa_bluetooth_transport *t) {
222     pa_log_info("Transport %s released", t->path);
223     /* device will close the SCO socket for us */
224 }
225 
sco_io_callback(pa_mainloop_api * io,pa_io_event * e,int fd,pa_io_event_flags_t events,void * userdata)226 static void sco_io_callback(pa_mainloop_api *io, pa_io_event *e, int fd, pa_io_event_flags_t events, void *userdata) {
227     pa_bluetooth_transport *t = userdata;
228 
229     pa_assert(io);
230     pa_assert(t);
231 
232     if (events & (PA_IO_EVENT_HANGUP|PA_IO_EVENT_ERROR)) {
233         pa_log_error("error listening SCO connection: %s", pa_cstrerror(errno));
234         goto fail;
235     }
236 
237     if (t->state != PA_BLUETOOTH_TRANSPORT_STATE_PLAYING) {
238         pa_log_info("SCO incoming connection: changing state to PLAYING");
239         pa_bluetooth_transport_set_state (t, PA_BLUETOOTH_TRANSPORT_STATE_PLAYING);
240     }
241 
242 fail:
243     return;
244 }
245 
sco_listen(pa_bluetooth_transport * t)246 static int sco_listen(pa_bluetooth_transport *t) {
247     struct transport_data *trd = t->userdata;
248     struct sockaddr_sco addr;
249     int sock, i;
250     bdaddr_t src;
251     const char *src_addr;
252 
253     sock = socket(PF_BLUETOOTH, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, BTPROTO_SCO);
254     if (sock < 0) {
255         pa_log_error("socket(SEQPACKET, SCO) %s", pa_cstrerror(errno));
256         return -1;
257     }
258 
259     src_addr = t->device->adapter->address;
260 
261     /* don't use ba2str to avoid -lbluetooth */
262     for (i = 5; i >= 0; i--, src_addr += 3)
263         src.b[i] = strtol(src_addr, NULL, 16);
264 
265     /* Bind to local address */
266     memset(&addr, 0, sizeof(addr));
267     addr.sco_family = AF_BLUETOOTH;
268     bacpy(&addr.sco_bdaddr, &src);
269 
270     if (bind(sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
271         pa_log_error("bind(): %s", pa_cstrerror(errno));
272         goto fail_close;
273     }
274 
275     pa_log_info ("doing listen");
276     if (listen(sock, 1) < 0) {
277         pa_log_error("listen(): %s", pa_cstrerror(errno));
278         goto fail_close;
279     }
280 
281     trd->sco_fd = sock;
282     trd->sco_io = trd->mainloop->io_new(trd->mainloop, sock, PA_IO_EVENT_INPUT,
283         sco_io_callback, t);
284 
285     return sock;
286 
287 fail_close:
288     close(sock);
289     return -1;
290 }
291 
register_profile_reply(DBusPendingCall * pending,void * userdata)292 static void register_profile_reply(DBusPendingCall *pending, void *userdata) {
293     DBusMessage *r;
294     pa_dbus_pending *p;
295     pa_bluetooth_backend *b;
296     char *profile;
297 
298     pa_assert(pending);
299     pa_assert_se(p = userdata);
300     pa_assert_se(b = p->context_data);
301     pa_assert_se(profile = p->call_data);
302     pa_assert_se(r = dbus_pending_call_steal_reply(pending));
303 
304     if (dbus_message_is_error(r, BLUEZ_ERROR_NOT_SUPPORTED)) {
305         pa_log_info("Couldn't register profile %s because it is disabled in BlueZ", profile);
306         goto finish;
307     }
308 
309     if (dbus_message_get_type(r) == DBUS_MESSAGE_TYPE_ERROR) {
310         pa_log_error(BLUEZ_PROFILE_MANAGER_INTERFACE ".RegisterProfile() failed: %s: %s", dbus_message_get_error_name(r),
311                      pa_dbus_get_error_message(r));
312         goto finish;
313     }
314 
315 finish:
316     dbus_message_unref(r);
317 
318     PA_LLIST_REMOVE(pa_dbus_pending, b->pending, p);
319     pa_dbus_pending_free(p);
320 
321     pa_xfree(profile);
322 }
323 
register_profile(pa_bluetooth_backend * b,const char * profile,const char * uuid)324 static void register_profile(pa_bluetooth_backend *b, const char *profile, const char *uuid) {
325     DBusMessage *m;
326     DBusMessageIter i, d;
327     dbus_bool_t autoconnect;
328     dbus_uint16_t version, chan;
329 
330     pa_log_debug("Registering Profile %s %s", profile, uuid);
331 
332     pa_assert_se(m = dbus_message_new_method_call(BLUEZ_SERVICE, "/org/bluez", BLUEZ_PROFILE_MANAGER_INTERFACE, "RegisterProfile"));
333 
334     dbus_message_iter_init_append(m, &i);
335     pa_assert_se(dbus_message_iter_append_basic(&i, DBUS_TYPE_OBJECT_PATH, &profile));
336     pa_assert_se(dbus_message_iter_append_basic(&i, DBUS_TYPE_STRING, &uuid));
337     dbus_message_iter_open_container(&i, DBUS_TYPE_ARRAY, DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING DBUS_TYPE_STRING_AS_STRING
338             DBUS_TYPE_VARIANT_AS_STRING DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &d);
339     if (pa_bluetooth_uuid_is_hsp_hs(uuid)) {
340         /* In the headset role, the connection will only be initiated from the remote side */
341         autoconnect = 0;
342         pa_dbus_append_basic_variant_dict_entry(&d, "AutoConnect", DBUS_TYPE_BOOLEAN, &autoconnect);
343         chan = HSP_HS_DEFAULT_CHANNEL;
344         pa_dbus_append_basic_variant_dict_entry(&d, "Channel", DBUS_TYPE_UINT16, &chan);
345         /* HSP version 1.2 */
346         version = 0x0102;
347         pa_dbus_append_basic_variant_dict_entry(&d, "Version", DBUS_TYPE_UINT16, &version);
348     }
349     dbus_message_iter_close_container(&i, &d);
350 
351     send_and_add_to_pending(b, m, register_profile_reply, pa_xstrdup(profile));
352 }
353 
rfcomm_io_callback(pa_mainloop_api * io,pa_io_event * e,int fd,pa_io_event_flags_t events,void * userdata)354 static void rfcomm_io_callback(pa_mainloop_api *io, pa_io_event *e, int fd, pa_io_event_flags_t events, void *userdata) {
355     pa_bluetooth_transport *t = userdata;
356 
357     pa_assert(io);
358     pa_assert(t);
359 
360     if (events & (PA_IO_EVENT_HANGUP|PA_IO_EVENT_ERROR)) {
361         pa_log_info("Lost RFCOMM connection.");
362         goto fail;
363     }
364 
365     if (events & PA_IO_EVENT_INPUT) {
366         char buf[512];
367         ssize_t len;
368         int gain, dummy;
369         bool  do_reply = false;
370 
371         len = pa_read(fd, buf, 511, NULL);
372         if (len < 0) {
373             pa_log_error("RFCOMM read error: %s", pa_cstrerror(errno));
374             goto fail;
375         }
376         buf[len] = 0;
377         pa_log_debug("RFCOMM << %s", buf);
378 
379         /* There are only four HSP AT commands:
380          * AT+VGS=value: value between 0 and 15, sent by the HS to AG to set the speaker gain.
381          * +VGS=value is sent by AG to HS as a response to an AT+VGS command or when the gain
382          * is changed on the AG side.
383          * AT+VGM=value: value between 0 and 15, sent by the HS to AG to set the microphone gain.
384          * +VGM=value is sent by AG to HS as a response to an AT+VGM command or when the gain
385          * is changed on the AG side.
386          * AT+CKPD=200: Sent by HS when headset button is pressed.
387          * RING: Sent by AG to HS to notify of an incoming call. It can safely be ignored because
388          * it does not expect a reply. */
389         if (sscanf(buf, "AT+VGS=%d", &gain) == 1 || sscanf(buf, "\r\n+VGM=%d\r\n", &gain) == 1) {
390             t->speaker_gain = gain;
391             pa_hook_fire(pa_bluetooth_discovery_hook(t->device->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_SPEAKER_GAIN_CHANGED), t);
392             do_reply = true;
393 
394         } else if (sscanf(buf, "AT+VGM=%d", &gain) == 1 || sscanf(buf, "\r\n+VGS=%d\r\n", &gain) == 1) {
395             t->microphone_gain = gain;
396             pa_hook_fire(pa_bluetooth_discovery_hook(t->device->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_MICROPHONE_GAIN_CHANGED), t);
397             do_reply = true;
398         } else if (sscanf(buf, "AT+CKPD=%d", &dummy) == 1) {
399             do_reply = true;
400         } else {
401             do_reply = false;
402         }
403 
404         if (do_reply) {
405             pa_log_debug("RFCOMM >> OK");
406 
407             len = write(fd, "\r\nOK\r\n", 6);
408 
409             /* we ignore any errors, it's not critical and real errors should
410              * be caught with the HANGUP and ERROR events handled above */
411             if (len < 0)
412                 pa_log_error("RFCOMM write error: %s", pa_cstrerror(errno));
413         }
414     }
415 
416     return;
417 
418 fail:
419     pa_bluetooth_transport_unlink(t);
420     pa_bluetooth_transport_free(t);
421 }
422 
transport_destroy(pa_bluetooth_transport * t)423 static void transport_destroy(pa_bluetooth_transport *t) {
424     struct transport_data *trd = t->userdata;
425 
426     if (trd->sco_io) {
427         trd->mainloop->io_free(trd->sco_io);
428         shutdown(trd->sco_fd, SHUT_RDWR);
429         close (trd->sco_fd);
430     }
431 
432     trd->mainloop->io_free(trd->rfcomm_io);
433     shutdown(trd->rfcomm_fd, SHUT_RDWR);
434     close (trd->rfcomm_fd);
435 
436     pa_xfree(trd);
437 }
438 
set_speaker_gain(pa_bluetooth_transport * t,uint16_t gain)439 static void set_speaker_gain(pa_bluetooth_transport *t, uint16_t gain) {
440     struct transport_data *trd = t->userdata;
441     char buf[512];
442     ssize_t len, written;
443 
444     if (t->speaker_gain == gain)
445       return;
446 
447     t->speaker_gain = gain;
448 
449     /* If we are in the AG role, we send a command to the head set to change
450      * the speaker gain. In the HS role, source and sink are swapped, so
451      * in this case we notify the AG that the microphone gain has changed */
452     if (t->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT) {
453         len = sprintf(buf, "\r\n+VGS=%d\r\n", gain);
454         pa_log_debug("RFCOMM >> +VGS=%d", gain);
455     } else {
456         len = sprintf(buf, "\r\nAT+VGM=%d\r\n", gain);
457         pa_log_debug("RFCOMM >> AT+VGM=%d", gain);
458     }
459 
460     written = write(trd->rfcomm_fd, buf, len);
461 
462     if (written != len)
463         pa_log_error("RFCOMM write error: %s", pa_cstrerror(errno));
464 }
465 
set_microphone_gain(pa_bluetooth_transport * t,uint16_t gain)466 static void set_microphone_gain(pa_bluetooth_transport *t, uint16_t gain) {
467     struct transport_data *trd = t->userdata;
468     char buf[512];
469     ssize_t len, written;
470 
471     if (t->microphone_gain == gain)
472       return;
473 
474     t->microphone_gain = gain;
475 
476     /* If we are in the AG role, we send a command to the head set to change
477      * the microphone gain. In the HS role, source and sink are swapped, so
478      * in this case we notify the AG that the speaker gain has changed */
479     if (t->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT) {
480         len = sprintf(buf, "\r\n+VGM=%d\r\n", gain);
481         pa_log_debug("RFCOMM >> +VGM=%d", gain);
482     } else {
483         len = sprintf(buf, "\r\nAT+VGS=%d\r\n", gain);
484         pa_log_debug("RFCOMM >> AT+VGS=%d", gain);
485     }
486 
487     written = write (trd->rfcomm_fd, buf, len);
488 
489     if (written != len)
490         pa_log_error("RFCOMM write error: %s", pa_cstrerror(errno));
491 }
492 
profile_new_connection(DBusConnection * conn,DBusMessage * m,void * userdata)493 static DBusMessage *profile_new_connection(DBusConnection *conn, DBusMessage *m, void *userdata) {
494     pa_bluetooth_backend *b = userdata;
495     pa_bluetooth_device *d;
496     pa_bluetooth_transport *t;
497     pa_bluetooth_profile_t p;
498     DBusMessage *r;
499     int fd;
500     const char *sender, *path, PA_UNUSED *handler;
501     DBusMessageIter arg_i;
502     char *pathfd;
503     struct transport_data *trd;
504 
505     if (!dbus_message_iter_init(m, &arg_i) || !pa_streq(dbus_message_get_signature(m), "oha{sv}")) {
506         pa_log_error("Invalid signature found in NewConnection");
507         goto fail;
508     }
509 
510     handler = dbus_message_get_path(m);
511     if (pa_streq(handler, HSP_AG_PROFILE)) {
512         p = PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT;
513     } else if (pa_streq(handler, HSP_HS_PROFILE)) {
514         p = PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY;
515     } else {
516         pa_log_error("Invalid handler");
517         goto fail;
518     }
519 
520     pa_assert(dbus_message_iter_get_arg_type(&arg_i) == DBUS_TYPE_OBJECT_PATH);
521     dbus_message_iter_get_basic(&arg_i, &path);
522 
523     d = pa_bluetooth_discovery_get_device_by_path(b->discovery, path);
524     if (d == NULL) {
525         pa_log_error("Device doesnt exist for %s", path);
526         goto fail;
527     }
528 
529     pa_assert_se(dbus_message_iter_next(&arg_i));
530 
531     pa_assert(dbus_message_iter_get_arg_type(&arg_i) == DBUS_TYPE_UNIX_FD);
532     dbus_message_iter_get_basic(&arg_i, &fd);
533 
534     pa_log_debug("dbus: NewConnection path=%s, fd=%d, profile %s", path, fd,
535         pa_bluetooth_profile_to_string(p));
536 
537     sender = dbus_message_get_sender(m);
538 
539     pathfd = pa_sprintf_malloc ("%s/fd%d", path, fd);
540     t = pa_bluetooth_transport_new(d, sender, pathfd, p, NULL, 0);
541     pa_xfree(pathfd);
542 
543     t->acquire = sco_acquire_cb;
544     t->release = sco_release_cb;
545     t->destroy = transport_destroy;
546     t->set_speaker_gain = set_speaker_gain;
547     t->set_microphone_gain = set_microphone_gain;
548 
549     trd = pa_xnew0(struct transport_data, 1);
550     trd->rfcomm_fd = fd;
551     trd->mainloop = b->core->mainloop;
552     trd->rfcomm_io = trd->mainloop->io_new(b->core->mainloop, fd, PA_IO_EVENT_INPUT,
553         rfcomm_io_callback, t);
554     t->userdata =  trd;
555 
556     sco_listen(t);
557 
558     pa_bluetooth_transport_put(t);
559 
560     pa_log_debug("Transport %s available for profile %s", t->path, pa_bluetooth_profile_to_string(t->profile));
561 
562     pa_assert_se(r = dbus_message_new_method_return(m));
563 
564     return r;
565 
566 fail:
567     pa_assert_se(r = dbus_message_new_error(m, "org.bluez.Error.InvalidArguments", "Unable to handle new connection"));
568     return r;
569 }
570 
profile_request_disconnection(DBusConnection * conn,DBusMessage * m,void * userdata)571 static DBusMessage *profile_request_disconnection(DBusConnection *conn, DBusMessage *m, void *userdata) {
572     DBusMessage *r;
573 
574     pa_assert_se(r = dbus_message_new_method_return(m));
575 
576     return r;
577 }
578 
profile_handler(DBusConnection * c,DBusMessage * m,void * userdata)579 static DBusHandlerResult profile_handler(DBusConnection *c, DBusMessage *m, void *userdata) {
580     pa_bluetooth_backend *b = userdata;
581     DBusMessage *r = NULL;
582     const char *path, *interface, *member;
583 
584     pa_assert(b);
585 
586     path = dbus_message_get_path(m);
587     interface = dbus_message_get_interface(m);
588     member = dbus_message_get_member(m);
589 
590     pa_log_debug("dbus: path=%s, interface=%s, member=%s", path, interface, member);
591 
592     if (!pa_streq(path, HSP_AG_PROFILE) && !pa_streq(path, HSP_HS_PROFILE))
593         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
594 
595     if (dbus_message_is_method_call(m, "org.freedesktop.DBus.Introspectable", "Introspect")) {
596         const char *xml = PROFILE_INTROSPECT_XML;
597 
598         pa_assert_se(r = dbus_message_new_method_return(m));
599         pa_assert_se(dbus_message_append_args(r, DBUS_TYPE_STRING, &xml, DBUS_TYPE_INVALID));
600 
601     } else if (dbus_message_is_method_call(m, BLUEZ_PROFILE_INTERFACE, "Release")) {
602         pa_log_debug("Release not handled");
603         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
604     } else if (dbus_message_is_method_call(m, BLUEZ_PROFILE_INTERFACE, "RequestDisconnection")) {
605         r = profile_request_disconnection(c, m, userdata);
606     } else if (dbus_message_is_method_call(m, BLUEZ_PROFILE_INTERFACE, "NewConnection"))
607         r = profile_new_connection(c, m, userdata);
608     else
609         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
610 
611     if (r) {
612         pa_assert_se(dbus_connection_send(pa_dbus_connection_get(b->connection), r, NULL));
613         dbus_message_unref(r);
614     }
615 
616     return DBUS_HANDLER_RESULT_HANDLED;
617 }
618 
profile_init(pa_bluetooth_backend * b,pa_bluetooth_profile_t profile)619 static void profile_init(pa_bluetooth_backend *b, pa_bluetooth_profile_t profile) {
620     static const DBusObjectPathVTable vtable_profile = {
621         .message_function = profile_handler,
622     };
623     const char *object_name;
624     const char *uuid;
625 
626     pa_assert(b);
627 
628     switch (profile) {
629         case PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT:
630             object_name = HSP_AG_PROFILE;
631             uuid = PA_BLUETOOTH_UUID_HSP_AG;
632             break;
633         case PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY:
634             object_name = HSP_HS_PROFILE;
635             uuid = PA_BLUETOOTH_UUID_HSP_HS;
636             break;
637         default:
638             pa_assert_not_reached();
639             break;
640     }
641 
642     pa_assert_se(dbus_connection_register_object_path(pa_dbus_connection_get(b->connection), object_name, &vtable_profile, b));
643     register_profile(b, object_name, uuid);
644 }
645 
profile_done(pa_bluetooth_backend * b,pa_bluetooth_profile_t profile)646 static void profile_done(pa_bluetooth_backend *b, pa_bluetooth_profile_t profile) {
647     pa_assert(b);
648 
649     switch (profile) {
650         case PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT:
651             dbus_connection_unregister_object_path(pa_dbus_connection_get(b->connection), HSP_AG_PROFILE);
652             break;
653         case PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY:
654             dbus_connection_unregister_object_path(pa_dbus_connection_get(b->connection), HSP_HS_PROFILE);
655             break;
656         default:
657             pa_assert_not_reached();
658             break;
659     }
660 }
661 
pa_bluetooth_native_backend_enable_hs_role(pa_bluetooth_backend * native_backend,bool enable_hs_role)662 void pa_bluetooth_native_backend_enable_hs_role(pa_bluetooth_backend *native_backend, bool enable_hs_role) {
663 
664    if (enable_hs_role == native_backend->enable_hs_role)
665        return;
666 
667    if (enable_hs_role)
668        profile_init(native_backend, PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY);
669    else
670        profile_done(native_backend, PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY);
671 
672    native_backend->enable_hs_role = enable_hs_role;
673 }
674 
pa_bluetooth_native_backend_new(pa_core * c,pa_bluetooth_discovery * y,bool enable_hs_role)675 pa_bluetooth_backend *pa_bluetooth_native_backend_new(pa_core *c, pa_bluetooth_discovery *y, bool enable_hs_role) {
676     pa_bluetooth_backend *backend;
677     DBusError err;
678 
679     pa_log_debug("Bluetooth Headset Backend API support using the native backend");
680 
681     backend = pa_xnew0(pa_bluetooth_backend, 1);
682     backend->core = c;
683 
684     dbus_error_init(&err);
685     if (!(backend->connection = pa_dbus_bus_get(c, DBUS_BUS_SYSTEM, &err))) {
686         pa_log("Failed to get D-Bus connection: %s", err.message);
687         dbus_error_free(&err);
688         pa_xfree(backend);
689         return NULL;
690     }
691 
692     backend->discovery = y;
693     backend->enable_hs_role = enable_hs_role;
694 
695     if (enable_hs_role)
696        profile_init(backend, PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY);
697     profile_init(backend, PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT);
698 
699     return backend;
700 }
701 
pa_bluetooth_native_backend_free(pa_bluetooth_backend * backend)702 void pa_bluetooth_native_backend_free(pa_bluetooth_backend *backend) {
703     pa_assert(backend);
704 
705     pa_dbus_free_pending_list(&backend->pending);
706 
707     if (backend->enable_hs_role)
708        profile_done(backend, PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY);
709     profile_done(backend, PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT);
710 
711     pa_dbus_connection_unref(backend->connection);
712 
713     pa_xfree(backend);
714 }
715