OSDN Git Service

a0c1e4035c1cc16b4045314ea59bb22a2fd6e2e3
[android-x86/external-bluetooth-bluez.git] / utils / audio / control.c
1 /*
2  *
3  *  BlueZ - Bluetooth protocol stack for Linux
4  *
5  *  Copyright (C) 2006-2007  Nokia Corporation
6  *  Copyright (C) 2004-2008  Marcel Holtmann <marcel@holtmann.org>
7  *
8  *
9  *  This program is free software; you can redistribute it and/or modify
10  *  it under the terms of the GNU General Public License as published by
11  *  the Free Software Foundation; either version 2 of the License, or
12  *  (at your option) any later version.
13  *
14  *  This program is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *
19  *  You should have received a copy of the GNU General Public License
20  *  along with this program; if not, write to the Free Software
21  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
22  *
23  */
24
25 #ifdef HAVE_CONFIG_H
26 #include <config.h>
27 #endif
28
29 #include <stdlib.h>
30 #include <stdint.h>
31 #include <errno.h>
32 #include <unistd.h>
33 #include <assert.h>
34 #include <signal.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <fcntl.h>
38 #include <netinet/in.h>
39
40 #include <bluetooth/bluetooth.h>
41 #include <bluetooth/sdp.h>
42 #include <bluetooth/sdp_lib.h>
43 #include <bluetooth/l2cap.h>
44
45 #include <glib.h>
46 #include <dbus/dbus.h>
47 #include <gdbus.h>
48
49 #include "dbus-service.h"
50 #include "logging.h"
51 #include "uinput.h"
52 #include "device.h"
53 #include "manager.h"
54 #include "avdtp.h"
55 #include "control.h"
56 #include "sdpd.h"
57 #include "glib-helper.h"
58
59 #define AVCTP_PSM 23
60
61 /* Message types */
62 #define AVCTP_COMMAND           0
63 #define AVCTP_RESPONSE          1
64
65 /* Packet types */
66 #define AVCTP_PACKET_SINGLE     0
67 #define AVCTP_PACKET_START      1
68 #define AVCTP_PACKET_CONTINUE   2
69 #define AVCTP_PACKET_END        3
70
71 /* ctype entries */
72 #define CTYPE_CONTROL           0x0
73 #define CTYPE_STATUS            0x1
74 #define CTYPE_ACCEPTED          0x9
75 #define CTYPE_STABLE            0xC
76
77 /* opcodes */
78 #define OP_UNITINFO             0x30
79 #define OP_SUBUNITINFO          0x31
80 #define OP_PASSTHROUGH          0x7c
81
82 /* subunits of interest */
83 #define SUBUNIT_PANEL           0x09
84
85 /* operands in passthrough commands */
86 #define VOLUP_OP                0x41
87 #define VOLDOWN_OP              0x42
88 #define MUTE_OP                 0x43
89
90 #define PLAY_OP                 0x44
91 #define STOP_OP                 0x45
92 #define PAUSE_OP                0x46
93 #define REWIND_OP               0x48
94 #define FAST_FORWARD_OP         0x49
95 #define NEXT_OP                 0x4b
96 #define PREV_OP                 0x4c
97
98 static DBusConnection *connection = NULL;
99
100 static uint32_t tg_record_id = 0;
101 #ifndef ANDROID
102 static uint32_t ct_record_id = 0;
103 #endif
104
105 static GIOChannel *avctp_server = NULL;
106 static gchar *input_device_name = NULL;
107 static GSList *sessions = NULL;
108
109 typedef enum {
110         AVCTP_STATE_DISCONNECTED = 0,
111         AVCTP_STATE_CONNECTING,
112         AVCTP_STATE_CONNECTED
113 } avctp_state_t;
114
115 #if __BYTE_ORDER == __LITTLE_ENDIAN
116
117 struct avctp_header {
118         uint8_t ipid:1;
119         uint8_t cr:1;
120         uint8_t packet_type:2;
121         uint8_t transaction:4;
122         uint16_t pid;
123 } __attribute__ ((packed));
124
125 struct avrcp_header {
126         uint8_t code:4;
127         uint8_t _hdr0:4;
128         uint8_t subunit_id:3;
129         uint8_t subunit_type:5;
130         uint8_t opcode;
131 } __attribute__ ((packed));
132
133 #elif __BYTE_ORDER == __BIG_ENDIAN
134
135 struct avctp_header {
136         uint8_t transaction:4;
137         uint8_t packet_type:2;
138         uint8_t cr:1;
139         uint8_t ipid:1;
140         uint16_t pid;
141 } __attribute__ ((packed));
142
143 struct avrcp_header {
144         uint8_t _hdr0:4;
145         uint8_t code:4;
146         uint8_t subunit_type:5;
147         uint8_t subunit_id:3;
148         uint8_t opcode;
149 } __attribute__ ((packed));
150
151 #else
152 #error "Unknown byte order"
153 #endif
154
155 struct avctp {
156         struct audio_device *dev;
157
158         avctp_state_t state;
159
160         bdaddr_t src;
161         bdaddr_t dst;
162
163         int uinput;
164
165         int sock;
166
167         guint io;
168
169         uint16_t mtu;
170 };
171
172 struct control {
173         struct avctp *session;
174 };
175
176 static sdp_record_t *avrcp_ct_record()
177 {
178         sdp_list_t *svclass_id, *pfseq, *apseq, *root;
179         uuid_t root_uuid, l2cap, avctp, avrct;
180         sdp_profile_desc_t profile[1];
181         sdp_list_t *aproto, *proto[2];
182         sdp_record_t *record;
183         sdp_data_t *psm, *version, *features;
184         int16_t lp = AVCTP_PSM, ver = 0x0100, feat = 0x000f;
185
186         record = sdp_record_alloc();
187         if (!record)
188                 return NULL;
189
190         sdp_uuid16_create(&root_uuid, PUBLIC_BROWSE_GROUP);
191         root = sdp_list_append(0, &root_uuid);
192         sdp_set_browse_groups(record, root);
193
194         /* Service Class ID List */
195         sdp_uuid16_create(&avrct, AV_REMOTE_SVCLASS_ID);
196         svclass_id = sdp_list_append(0, &avrct);
197         sdp_set_service_classes(record, svclass_id);
198
199         /* Protocol Descriptor List */
200         sdp_uuid16_create(&l2cap, L2CAP_UUID);
201         proto[0] = sdp_list_append(0, &l2cap);
202         psm = sdp_data_alloc(SDP_UINT16, &lp);
203         proto[0] = sdp_list_append(proto[0], psm);
204         apseq = sdp_list_append(0, proto[0]);
205
206         sdp_uuid16_create(&avctp, AVCTP_UUID);
207         proto[1] = sdp_list_append(0, &avctp);
208         version = sdp_data_alloc(SDP_UINT16, &ver);
209         proto[1] = sdp_list_append(proto[1], version);
210         apseq = sdp_list_append(apseq, proto[1]);
211
212         aproto = sdp_list_append(0, apseq);
213         sdp_set_access_protos(record, aproto);
214
215         /* Bluetooth Profile Descriptor List */
216         sdp_uuid16_create(&profile[0].uuid, AV_REMOTE_PROFILE_ID);
217         profile[0].version = ver;
218         pfseq = sdp_list_append(0, &profile[0]);
219         sdp_set_profile_descs(record, pfseq);
220
221         features = sdp_data_alloc(SDP_UINT16, &feat);
222         sdp_attr_add(record, SDP_ATTR_SUPPORTED_FEATURES, features);
223
224         sdp_set_info_attr(record, "AVRCP CT", 0, 0);
225
226         free(psm);
227         free(version);
228         sdp_list_free(proto[0], 0);
229         sdp_list_free(proto[1], 0);
230         sdp_list_free(apseq, 0);
231         sdp_list_free(pfseq, 0);
232         sdp_list_free(aproto, 0);
233         sdp_list_free(root, 0);
234         sdp_list_free(svclass_id, 0);
235
236         return record;
237 }
238
239 static sdp_record_t *avrcp_tg_record()
240 {
241         sdp_list_t *svclass_id, *pfseq, *apseq, *root;
242         uuid_t root_uuid, l2cap, avctp, avrtg;
243         sdp_profile_desc_t profile[1];
244         sdp_list_t *aproto, *proto[2];
245         sdp_record_t *record;
246         sdp_data_t *psm, *version, *features;
247         uint16_t lp = AVCTP_PSM, ver = 0x0100, feat = 0x000f;
248
249         record = sdp_record_alloc();
250         if (!record)
251                 return NULL;
252
253         sdp_uuid16_create(&root_uuid, PUBLIC_BROWSE_GROUP);
254         root = sdp_list_append(0, &root_uuid);
255         sdp_set_browse_groups(record, root);
256
257         /* Service Class ID List */
258         sdp_uuid16_create(&avrtg, AV_REMOTE_TARGET_SVCLASS_ID);
259         svclass_id = sdp_list_append(0, &avrtg);
260         sdp_set_service_classes(record, svclass_id);
261
262         /* Protocol Descriptor List */
263         sdp_uuid16_create(&l2cap, L2CAP_UUID);
264         proto[0] = sdp_list_append(0, &l2cap);
265         psm = sdp_data_alloc(SDP_UINT16, &lp);
266         proto[0] = sdp_list_append(proto[0], psm);
267         apseq = sdp_list_append(0, proto[0]);
268
269         sdp_uuid16_create(&avctp, AVCTP_UUID);
270         proto[1] = sdp_list_append(0, &avctp);
271         version = sdp_data_alloc(SDP_UINT16, &ver);
272         proto[1] = sdp_list_append(proto[1], version);
273         apseq = sdp_list_append(apseq, proto[1]);
274
275         aproto = sdp_list_append(0, apseq);
276         sdp_set_access_protos(record, aproto);
277
278         /* Bluetooth Profile Descriptor List */
279         sdp_uuid16_create(&profile[0].uuid, AV_REMOTE_PROFILE_ID);
280         profile[0].version = ver;
281         pfseq = sdp_list_append(0, &profile[0]);
282         sdp_set_profile_descs(record, pfseq);
283
284         features = sdp_data_alloc(SDP_UINT16, &feat);
285         sdp_attr_add(record, SDP_ATTR_SUPPORTED_FEATURES, features);
286
287         sdp_set_info_attr(record, "AVRCP TG", 0, 0);
288
289         free(psm);
290         free(version);
291         sdp_list_free(proto[0], 0);
292         sdp_list_free(proto[1], 0);
293         sdp_list_free(apseq, 0);
294         sdp_list_free(aproto, 0);
295         sdp_list_free(pfseq, 0);
296         sdp_list_free(root, 0);
297         sdp_list_free(svclass_id, 0);
298
299         return record;
300 }
301
302 static struct avctp *find_session(const bdaddr_t *src, const bdaddr_t *dst)
303 {
304         GSList *l;
305
306         for (l = sessions; l != NULL; l = g_slist_next(l)) {
307                 struct avctp *s = l->data;
308
309                 if (bacmp(src, &s->src) || bacmp(dst, &s->dst))
310                         continue;
311
312                 return s;
313         }
314
315         return NULL;
316 }
317
318 static struct avctp *avctp_get(const bdaddr_t *src, const bdaddr_t *dst)
319 {
320         struct avctp *session;
321
322         assert(src != NULL);
323         assert(dst != NULL);
324
325         session = find_session(src, dst);
326         if (session)
327                 return session;
328
329         session = g_new0(struct avctp, 1);
330
331         session->uinput = -1;
332         session->sock = -1;
333         bacpy(&session->src, src);
334         bacpy(&session->dst, dst);
335
336         sessions = g_slist_append(sessions, session);
337
338         return session;
339 }
340
341 static int send_event(int fd, uint16_t type, uint16_t code, int32_t value)
342 {
343         struct uinput_event event;
344
345         memset(&event, 0, sizeof(event));
346         event.type      = type;
347         event.code      = code;
348         event.value     = value;
349
350         return write(fd, &event, sizeof(event));
351 }
352
353 static void send_key(int fd, uint16_t key, int pressed)
354 {
355         if (fd < 0)
356                 return;
357
358         send_event(fd, EV_KEY, key, pressed);
359         send_event(fd, EV_SYN, SYN_REPORT, 0);
360 }
361
362 static void handle_panel_passthrough(struct avctp *session,
363                                         const unsigned char *operands,
364                                         int operand_count)
365 {
366         const char *status;
367         int pressed;
368
369         if (operand_count == 0)
370                 return;
371
372         if (operands[0] & 0x80) {
373                 status = "released";
374                 pressed = 0;
375         } else {
376                 status = "pressed";
377                 pressed = 1;
378         }
379
380         switch (operands[0] & 0x7F) {
381         case PLAY_OP:
382                 debug("AVRCP: PLAY %s", status);
383                 send_key(session->uinput, KEY_PLAYPAUSE, pressed);
384                 break;
385         case STOP_OP:
386                 debug("AVRCP: STOP %s", status);
387                 send_key(session->uinput, KEY_STOP, pressed);
388                 break;
389         case PAUSE_OP:
390                 debug("AVRCP: PAUSE %s", status);
391                 send_key(session->uinput, KEY_PLAYPAUSE, pressed);
392                 break;
393         case NEXT_OP:
394                 debug("AVRCP: NEXT %s", status);
395                 send_key(session->uinput, KEY_NEXTSONG, pressed);
396                 break;
397         case PREV_OP:
398                 debug("AVRCP: PREV %s", status);
399                 send_key(session->uinput, KEY_PREVIOUSSONG, pressed);
400                 break;
401         case REWIND_OP:
402                 debug("AVRCP: REWIND %s", status);
403                 send_key(session->uinput, KEY_REWIND, pressed);
404                 break;
405         case FAST_FORWARD_OP:
406                 debug("AVRCP: FAST FORWARD %s", status);
407                 send_key(session->uinput, KEY_FORWARD, pressed);
408                 break;
409         default:
410                 debug("AVRCP: unknown button 0x%02X %s", operands[0] & 0x7F, status);
411                 break;
412         }
413 }
414
415 static void avctp_unref(struct avctp *session)
416 {
417         sessions = g_slist_remove(sessions, session);
418
419         if (session->state == AVCTP_STATE_CONNECTED)
420                 g_dbus_emit_signal(session->dev->conn,
421                                                 session->dev->path,
422                                                 AUDIO_CONTROL_INTERFACE,
423                                                 "Disconnected",
424                                                 DBUS_TYPE_INVALID);
425         if (session->sock >= 0)
426                 close(session->sock);
427         if (session->io)
428                 g_source_remove(session->io);
429
430         if (session->dev && session->dev->control)
431                 session->dev->control->session = NULL;
432
433         if (session->uinput >= 0) {
434                 ioctl(session->uinput, UI_DEV_DESTROY);
435                 close(session->uinput);
436         }
437
438         g_free(session);
439 }
440
441 static gboolean session_cb(GIOChannel *chan, GIOCondition cond,
442                                 gpointer data)
443 {
444         struct avctp *session = data;
445         unsigned char buf[1024], *operands;
446         struct avctp_header *avctp;
447         struct avrcp_header *avrcp;
448         int ret, packet_size, operand_count;
449
450         if (!(cond | G_IO_IN))
451                 goto failed;
452
453         ret = read(session->sock, buf, sizeof(buf));
454         if (ret <= 0)
455                 goto failed;
456
457         debug("Got %d bytes of data for AVCTP session %p", ret, session);
458
459         if (ret < sizeof(struct avctp_header)) {
460                 error("Too small AVCTP packet");
461                 goto failed;
462         }
463
464         packet_size = ret;
465
466         avctp = (struct avctp_header *) buf;
467
468         debug("AVCTP transaction %u, packet type %u, C/R %u, IPID %u, "
469                         "PID 0x%04X",
470                         avctp->transaction, avctp->packet_type,
471                         avctp->cr, avctp->ipid, ntohs(avctp->pid));
472
473         ret -= sizeof(struct avctp_header);
474         if (ret < sizeof(struct avrcp_header)) {
475                 error("Too small AVRCP packet");
476                 goto failed;
477         }
478
479         avrcp = (struct avrcp_header *) (buf + sizeof(struct avctp_header));
480
481         ret -= sizeof(struct avrcp_header);
482
483         operands = buf + sizeof(struct avctp_header) + sizeof(struct avrcp_header);
484         operand_count = ret;
485
486         debug("AVRCP %s 0x%01X, subunit_type 0x%02X, subunit_id 0x%01X, "
487                         "opcode 0x%02X, %d operands",
488                         avctp->cr ? "response" : "command",
489                         avrcp->code, avrcp->subunit_type, avrcp->subunit_id,
490                         avrcp->opcode, operand_count);
491
492         if (avctp->packet_type == AVCTP_PACKET_SINGLE &&
493                         avctp->cr == AVCTP_COMMAND &&
494                         avctp->pid == htons(AV_REMOTE_SVCLASS_ID) &&
495                         avrcp->code == CTYPE_CONTROL &&
496                         avrcp->subunit_type == SUBUNIT_PANEL &&
497                         avrcp->opcode == OP_PASSTHROUGH) {
498                 handle_panel_passthrough(session, operands, operand_count);
499                 avctp->cr = AVCTP_RESPONSE;
500                 avrcp->code = CTYPE_ACCEPTED;
501                 ret = write(session->sock, buf, packet_size);
502         }
503
504         if (avctp->packet_type == AVCTP_PACKET_SINGLE &&
505                         avctp->cr == AVCTP_COMMAND &&
506                         avctp->pid == htons(AV_REMOTE_SVCLASS_ID) &&
507                         avrcp->code == CTYPE_STATUS &&
508                         (avrcp->opcode == OP_UNITINFO
509                         || avrcp->opcode == OP_SUBUNITINFO)) {
510                 avctp->cr = AVCTP_RESPONSE;
511                 avrcp->code = CTYPE_STABLE;
512                 debug("reply to %s", avrcp->opcode == OP_UNITINFO ?
513                                 "OP_UNITINFO" : "OP_SUBUNITINFO");
514                 ret = write(session->sock, buf, packet_size);
515         }
516
517         return TRUE;
518
519 failed:
520         debug("AVCTP session %p got disconnected", session);
521         avctp_unref(session);
522         return FALSE;
523 }
524
525 static int uinput_create(char *name)
526 {
527         struct uinput_dev dev;
528         int fd, err;
529
530         fd = open("/dev/uinput", O_RDWR);
531         if (fd < 0) {
532                 fd = open("/dev/input/uinput", O_RDWR);
533                 if (fd < 0) {
534                         fd = open("/dev/misc/uinput", O_RDWR);
535                         if (fd < 0) {
536                                 err = errno;
537                                 error("Can't open input device: %s (%d)",
538                                                         strerror(err), err);
539                                 return -err;
540                         }
541                 }
542         }
543
544         memset(&dev, 0, sizeof(dev));
545         if (name)
546                 strncpy(dev.name, name, UINPUT_MAX_NAME_SIZE);
547
548         dev.id.bustype = BUS_BLUETOOTH;
549         dev.id.vendor  = 0x0000;
550         dev.id.product = 0x0000;
551         dev.id.version = 0x0000;
552
553         if (write(fd, &dev, sizeof(dev)) < 0) {
554                 err = errno;
555                 error("Can't write device information: %s (%d)",
556                                                 strerror(err), err);
557                 close(fd);
558                 errno = err;
559                 return -err;
560         }
561
562         ioctl(fd, UI_SET_EVBIT, EV_KEY);
563         ioctl(fd, UI_SET_EVBIT, EV_REL);
564         ioctl(fd, UI_SET_EVBIT, EV_REP);
565         ioctl(fd, UI_SET_EVBIT, EV_SYN);
566
567         ioctl(fd, UI_SET_KEYBIT, KEY_PLAYPAUSE);
568         ioctl(fd, UI_SET_KEYBIT, KEY_STOP);
569         ioctl(fd, UI_SET_KEYBIT, KEY_NEXTSONG);
570         ioctl(fd, UI_SET_KEYBIT, KEY_PREVIOUSSONG);
571         ioctl(fd, UI_SET_KEYBIT, KEY_REWIND);
572         ioctl(fd, UI_SET_KEYBIT, KEY_FORWARD);
573
574         if (ioctl(fd, UI_DEV_CREATE, NULL) < 0) {
575                 err = errno;
576                 error("Can't create uinput device: %s (%d)",
577                                                 strerror(err), err);
578                 close(fd);
579                 errno = err;
580                 return -err;
581         }
582
583         return fd;
584 }
585
586 static void init_uinput(struct avctp *session)
587 {
588         char address[18], *name;
589         GError *err = NULL;
590
591         ba2str(&session->dst, address);
592
593         /* use device name from config file if specified */
594         name = input_device_name;
595         if (!name)
596                 name = session->dev->name ? session->dev->name : address;
597
598         session->uinput = uinput_create(name);
599         if (session->uinput < 0)
600                 error("AVRCP: failed to init uinput for %s", name);
601         else
602                 debug("AVRCP: uinput initialized for %s", name);
603 }
604
605 static void avctp_connect_session(struct avctp *session)
606 {
607         GIOChannel *io;
608
609         session->state = AVCTP_STATE_CONNECTED;
610         session->dev = manager_device_connected(&session->dst,
611                                                 AVRCP_TARGET_UUID);
612         session->dev->control->session = session;
613
614         init_uinput(session);
615
616         g_dbus_emit_signal(session->dev->conn, session->dev->path,
617                                         AUDIO_CONTROL_INTERFACE, "Connected",
618                                         DBUS_TYPE_INVALID);
619
620         if (session->io)
621                 g_source_remove(session->io);
622
623         io = g_io_channel_unix_new(session->sock);
624         session->io = g_io_add_watch(io,
625                         G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
626                         (GIOFunc) session_cb, session);
627         g_io_channel_unref(io);
628 }
629
630 static void auth_cb(DBusError *derr, void *user_data)
631 {
632         struct avctp *session = user_data;
633
634         if (derr && dbus_error_is_set(derr)) {
635                 error("Access denied: %s", derr->message);
636                 if (dbus_error_has_name(derr, DBUS_ERROR_NO_REPLY)) {
637                         debug("Canceling authorization request");
638                         service_cancel_auth(&session->src, &session->dst);
639                 }
640
641                 avctp_unref(session);
642                 return;
643         }
644
645         avctp_connect_session(session);
646 }
647
648 static void avctp_server_cb(GIOChannel *chan, int err, const bdaddr_t *src,
649                                 const bdaddr_t *dst, gpointer data)
650 {
651         socklen_t size;
652         struct l2cap_options l2o;
653         struct avctp *session;
654         GIOCondition flags = G_IO_ERR | G_IO_HUP | G_IO_NVAL;
655         struct audio_device *dev;
656         char address[18];
657
658         if (err < 0) {
659                 error("AVCTP server socket: %s (%d)", strerror(-err), -err);
660                 return;
661         }
662
663         session = avctp_get(src, dst);
664
665         if (!session) {
666                 error("Unable to create new AVCTP session");
667                 goto drop;
668         }
669
670         if (session->sock >= 0) {
671                 error("Refusing unexpected connect from %s", address);
672                 goto drop;
673         }
674
675         dev = manager_find_device(&session->dst, AUDIO_CONTROL_INTERFACE, FALSE);
676
677         if (!dev) {
678                 error("Unable to get audio device object for %s", address);
679                 goto drop;
680         }
681
682         if (!dev->control)
683                 dev->control = control_init(dev);
684
685         device_remove_control_timer(dev);
686
687         session->state = AVCTP_STATE_CONNECTING;
688         session->sock = g_io_channel_unix_get_fd(chan);
689
690         memset(&l2o, 0, sizeof(l2o));
691         size = sizeof(l2o);
692         if (getsockopt(session->sock, SOL_L2CAP, L2CAP_OPTIONS, &l2o, &size) < 0) {
693                 err = errno;
694                 error("getsockopt(L2CAP_OPTIONS): %s (%d)", strerror(err),
695                                 err);
696                 avctp_unref(session);
697                 goto drop;
698         }
699
700         session->mtu = l2o.imtu;
701
702         session->io = g_io_add_watch(chan, flags, (GIOFunc) session_cb,
703                                 session);
704         g_io_channel_unref(chan);
705
706         if (avdtp_is_connected(src, dst))
707                 goto proceed;
708
709         if (service_req_auth(src, dst, AVRCP_TARGET_UUID, auth_cb, session) < 0)
710                 goto drop;
711
712         return;
713
714 proceed:
715         avctp_connect_session(session);
716
717         return;
718
719 drop:
720         close(session->sock);
721 }
722
723 static GIOChannel *avctp_server_socket(gboolean master)
724 {
725         int lm;
726         GIOChannel *io;
727
728         lm = L2CAP_LM_SECURE;
729
730         if (master)
731                 lm |= L2CAP_LM_MASTER;
732
733         io = bt_l2cap_listen(BDADDR_ANY, AVCTP_PSM, 0, lm, avctp_server_cb,
734                                 NULL);
735         if (!io) {
736                 error("Unable to allocate new io channel");
737                 return NULL;
738         }
739
740         return io;
741 }
742
743 static void avctp_connect_cb(GIOChannel *chan, int err, const bdaddr_t *src,
744                         const bdaddr_t *dst, gpointer data)
745 {
746         struct avctp *session = data;
747         struct l2cap_options l2o;
748         socklen_t len;
749         int sk;
750         char address[18];
751
752         if (err < 0) {
753                 avctp_unref(session);
754                 error("AVCTP connect(%s): %s (%d)", address, strerror(-err),
755                                 -err);
756                 return;
757         }
758
759         ba2str(&session->dst, address);
760         debug("AVCTP: connected to %s", address);
761
762         g_io_channel_set_close_on_unref(chan, FALSE);
763         sk = g_io_channel_unix_get_fd(chan);
764         session->sock = sk;
765
766         memset(&l2o, 0, sizeof(l2o));
767         len = sizeof(l2o);
768         if (getsockopt(sk, SOL_L2CAP, L2CAP_OPTIONS, &l2o, &len) < 0) {
769                 err = errno;
770                 avctp_unref(session);
771                 error("getsockopt(L2CAP_OPTIONS): %s (%d)", strerror(err),
772                                 err);
773                 return;
774         }
775
776         init_uinput(session);
777
778         g_dbus_emit_signal(session->dev->conn, session->dev->path,
779                                         AUDIO_CONTROL_INTERFACE, "Connected",
780                                         DBUS_TYPE_INVALID);
781
782         session->state = AVCTP_STATE_CONNECTED;
783         session->mtu = l2o.imtu;
784         session->io = g_io_add_watch(chan,
785                                 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
786                                 (GIOFunc) session_cb, session);
787 }
788
789 gboolean avrcp_connect(struct audio_device *dev)
790 {
791         struct control *control = dev->control;
792         struct avctp *session;
793         int err;
794
795         if (control->session)
796                 return TRUE;
797
798         session = avctp_get(&dev->src, &dev->dst);
799         if (!session) {
800                 error("Unable to create new AVCTP session");
801                 return FALSE;
802         }
803
804         device_remove_control_timer(dev);
805
806         session->dev = dev;
807         session->state = AVCTP_STATE_CONNECTING;
808
809         err = bt_l2cap_connect(&dev->src, &dev->dst, AVCTP_PSM, 0,
810                                 avctp_connect_cb, session);
811         if (err < 0) {
812                 avctp_unref(session);
813                 error("Connect failed. %s(%d)", strerror(-err), -err);
814                 return FALSE;
815         }
816
817         control->session = session;
818
819         return TRUE;
820 }
821
822 void avrcp_disconnect(struct audio_device *dev)
823 {
824         struct control *control = dev->control;
825         struct avctp *session = control->session;
826
827         if (!session)
828                 return;
829
830         avctp_unref(session);
831         control->session = NULL;
832 }
833
834 int avrcp_init(DBusConnection *conn, GKeyFile *config)
835 {
836         sdp_record_t *record;
837         gboolean tmp, master = TRUE;
838         GError *err = NULL;
839
840         if (avctp_server)
841                 return 0;
842
843         if (config) {
844                 tmp = g_key_file_get_boolean(config, "General",
845                                                         "Master", &err);
846                 if (err) {
847                         debug("audio.conf: %s", err->message);
848                         g_error_free(err);
849                         err = NULL;
850                 } else
851                         master = tmp;
852
853                 input_device_name = g_key_file_get_string(config,
854                         "AVRCP", "InputDeviceName", &err);
855                 if (err) {
856                         debug("InputDeviceName not specified in audio.conf");
857                         input_device_name = NULL;
858                         g_error_free(err);
859                 }
860         }
861
862         connection = dbus_connection_ref(conn);
863
864         record = avrcp_tg_record();
865         if (!record) {
866                 error("Unable to allocate new service record");
867                 return -1;
868         }
869
870         if (add_record_to_server(BDADDR_ANY, record) < 0) {
871                 error("Unable to register AVRCP target service record");
872                 sdp_record_free(record);
873                 return -1;
874         }
875         tg_record_id = record->handle;
876
877 #ifndef ANDROID
878         record = avrcp_ct_record();
879         if (!record) {
880                 error("Unable to allocate new service record");
881                 return -1;
882         }
883
884         if (add_record_to_server(BDADDR_ANY, record) < 0) {
885                 error("Unable to register AVRCP controller service record");
886                 sdp_record_free(record);
887                 return -1;
888         }
889         ct_record_id = record->handle;
890 #endif
891
892         avctp_server = avctp_server_socket(master);
893         if (!avctp_server)
894                 return -1;
895
896         return 0;
897 }
898
899 void avrcp_exit(void)
900 {
901         if (!avctp_server)
902                 return;
903
904         g_io_channel_close(avctp_server);
905         g_io_channel_unref(avctp_server);
906         avctp_server = NULL;
907
908 #ifndef ANDROID
909         remove_record_from_server(ct_record_id);
910         ct_record_id = 0;
911 #endif
912         remove_record_from_server(tg_record_id);
913         tg_record_id = 0;
914
915         dbus_connection_unref(connection);
916         connection = NULL;
917 }
918
919 static DBusMessage *control_is_connected(DBusConnection *conn,
920                                                 DBusMessage *msg,
921                                                 void *data)
922 {
923         struct audio_device *device = data;
924         struct control *control = device->control;
925         DBusMessage *reply;
926         dbus_bool_t connected;
927
928         reply = dbus_message_new_method_return(msg);
929         if (!reply)
930                 return NULL;
931
932         connected = (control->session != NULL);
933
934         dbus_message_append_args(reply, DBUS_TYPE_BOOLEAN, &connected,
935                                         DBUS_TYPE_INVALID);
936
937         return reply;
938 }
939
940 static GDBusMethodTable control_methods[] = {
941         { "IsConnected",        "",     "b",    control_is_connected },
942         { NULL, NULL, NULL, NULL }
943 };
944
945 static GDBusSignalTable control_signals[] = {
946         { "Connected",                  ""      },
947         { "Disconnected",               ""      },
948         { NULL, NULL }
949 };
950
951 struct control *control_init(struct audio_device *dev)
952 {
953         if (!g_dbus_register_interface(dev->conn, dev->path,
954                                         AUDIO_CONTROL_INTERFACE,
955                                         control_methods, control_signals, NULL,
956                                         dev, NULL))
957                 return NULL;
958
959         return g_new0(struct control, 1);
960 }
961
962 void control_free(struct audio_device *dev)
963 {
964         struct control *control = dev->control;
965
966         if (control->session)
967                 avctp_unref(control->session);
968
969         g_free(control);
970         dev->control = NULL;
971 }
972
973 gboolean control_is_active(struct audio_device *dev)
974 {
975         struct control *control = dev->control;
976
977         if (control->session &&
978                         control->session->state != AVCTP_STATE_DISCONNECTED)
979                 return TRUE;
980
981         return FALSE;
982 }