1/*
2 *
3 *  BlueZ - Bluetooth protocol stack for Linux
4 *
5 *  Copyright (C) 2006-2007  Nokia Corporation
6 *  Copyright (C) 2004-2009  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 "logging.h"
50#include "error.h"
51#include "uinput.h"
52#include "adapter.h"
53#include "../src/device.h"
54#include "device.h"
55#include "manager.h"
56#include "avdtp.h"
57#include "control.h"
58#include "sdpd.h"
59#include "glib-helper.h"
60#include "btio.h"
61#include "dbus-common.h"
62
63#define AVCTP_PSM 23
64
65/* Message types */
66#define AVCTP_COMMAND		0
67#define AVCTP_RESPONSE		1
68
69/* Packet types */
70#define AVCTP_PACKET_SINGLE	0
71#define AVCTP_PACKET_START	1
72#define AVCTP_PACKET_CONTINUE	2
73#define AVCTP_PACKET_END	3
74
75/* ctype entries */
76#define CTYPE_CONTROL		0x0
77#define CTYPE_STATUS		0x1
78#define CTYPE_NOT_IMPLEMENTED	0x8
79#define CTYPE_ACCEPTED		0x9
80#define CTYPE_REJECTED		0xA
81#define CTYPE_STABLE		0xC
82
83/* opcodes */
84#define OP_UNITINFO		0x30
85#define OP_SUBUNITINFO		0x31
86#define OP_PASSTHROUGH		0x7c
87
88/* subunits of interest */
89#define SUBUNIT_PANEL		0x09
90
91/* operands in passthrough commands */
92#define VOL_UP_OP		0x41
93#define VOL_DOWN_OP		0x42
94#define MUTE_OP			0x43
95#define PLAY_OP			0x44
96#define STOP_OP			0x45
97#define PAUSE_OP		0x46
98#define RECORD_OP		0x47
99#define REWIND_OP		0x48
100#define FAST_FORWARD_OP		0x49
101#define EJECT_OP		0x4a
102#define FORWARD_OP		0x4b
103#define BACKWARD_OP		0x4c
104
105static DBusConnection *connection = NULL;
106static gchar *input_device_name = NULL;
107static GSList *servers = NULL;
108
109#if __BYTE_ORDER == __LITTLE_ENDIAN
110
111struct avctp_header {
112	uint8_t ipid:1;
113	uint8_t cr:1;
114	uint8_t packet_type:2;
115	uint8_t transaction:4;
116	uint16_t pid;
117} __attribute__ ((packed));
118#define AVCTP_HEADER_LENGTH 3
119
120struct avrcp_header {
121	uint8_t code:4;
122	uint8_t _hdr0:4;
123	uint8_t subunit_id:3;
124	uint8_t subunit_type:5;
125	uint8_t opcode;
126} __attribute__ ((packed));
127#define AVRCP_HEADER_LENGTH 3
128
129#elif __BYTE_ORDER == __BIG_ENDIAN
130
131struct avctp_header {
132	uint8_t transaction:4;
133	uint8_t packet_type:2;
134	uint8_t cr:1;
135	uint8_t ipid:1;
136	uint16_t pid;
137} __attribute__ ((packed));
138#define AVCTP_HEADER_LENGTH 3
139
140struct avrcp_header {
141	uint8_t _hdr0:4;
142	uint8_t code:4;
143	uint8_t subunit_type:5;
144	uint8_t subunit_id:3;
145	uint8_t opcode;
146} __attribute__ ((packed));
147#define AVRCP_HEADER_LENGTH 3
148
149#else
150#error "Unknown byte order"
151#endif
152
153struct avctp_state_callback {
154	avctp_state_cb cb;
155	void *user_data;
156	unsigned int id;
157};
158
159struct avctp_server {
160	bdaddr_t src;
161	GIOChannel *io;
162	uint32_t tg_record_id;
163#ifndef ANDROID
164	uint32_t ct_record_id;
165#endif
166};
167
168struct control {
169	struct audio_device *dev;
170
171	avctp_state_t state;
172
173	int uinput;
174
175	GIOChannel *io;
176	guint io_id;
177
178	uint16_t mtu;
179
180	gboolean target;
181};
182
183static struct {
184	const char *name;
185	uint8_t avrcp;
186	uint16_t uinput;
187} key_map[] = {
188	{ "PLAY",		PLAY_OP,		KEY_PLAYCD },
189	{ "STOP",		STOP_OP,		KEY_STOPCD },
190	{ "PAUSE",		PAUSE_OP,		KEY_PAUSECD },
191	{ "FORWARD",		FORWARD_OP,		KEY_NEXTSONG },
192	{ "BACKWARD",		BACKWARD_OP,		KEY_PREVIOUSSONG },
193	{ "REWIND",		REWIND_OP,		KEY_REWIND },
194	{ "FAST FORWARD",	FAST_FORWARD_OP,	KEY_FASTFORWARD },
195	{ NULL }
196};
197
198static GSList *avctp_callbacks = NULL;
199
200static sdp_record_t *avrcp_ct_record()
201{
202	sdp_list_t *svclass_id, *pfseq, *apseq, *root;
203	uuid_t root_uuid, l2cap, avctp, avrct;
204	sdp_profile_desc_t profile[1];
205	sdp_list_t *aproto, *proto[2];
206	sdp_record_t *record;
207	sdp_data_t *psm, *version, *features;
208	uint16_t lp = AVCTP_PSM, ver = 0x0100, feat = 0x000f;
209
210	record = sdp_record_alloc();
211	if (!record)
212		return NULL;
213
214	sdp_uuid16_create(&root_uuid, PUBLIC_BROWSE_GROUP);
215	root = sdp_list_append(0, &root_uuid);
216	sdp_set_browse_groups(record, root);
217
218	/* Service Class ID List */
219	sdp_uuid16_create(&avrct, AV_REMOTE_SVCLASS_ID);
220	svclass_id = sdp_list_append(0, &avrct);
221	sdp_set_service_classes(record, svclass_id);
222
223	/* Protocol Descriptor List */
224	sdp_uuid16_create(&l2cap, L2CAP_UUID);
225	proto[0] = sdp_list_append(0, &l2cap);
226	psm = sdp_data_alloc(SDP_UINT16, &lp);
227	proto[0] = sdp_list_append(proto[0], psm);
228	apseq = sdp_list_append(0, proto[0]);
229
230	sdp_uuid16_create(&avctp, AVCTP_UUID);
231	proto[1] = sdp_list_append(0, &avctp);
232	version = sdp_data_alloc(SDP_UINT16, &ver);
233	proto[1] = sdp_list_append(proto[1], version);
234	apseq = sdp_list_append(apseq, proto[1]);
235
236	aproto = sdp_list_append(0, apseq);
237	sdp_set_access_protos(record, aproto);
238
239	/* Bluetooth Profile Descriptor List */
240	sdp_uuid16_create(&profile[0].uuid, AV_REMOTE_PROFILE_ID);
241	profile[0].version = ver;
242	pfseq = sdp_list_append(0, &profile[0]);
243	sdp_set_profile_descs(record, pfseq);
244
245	features = sdp_data_alloc(SDP_UINT16, &feat);
246	sdp_attr_add(record, SDP_ATTR_SUPPORTED_FEATURES, features);
247
248	sdp_set_info_attr(record, "AVRCP CT", 0, 0);
249
250	free(psm);
251	free(version);
252	sdp_list_free(proto[0], 0);
253	sdp_list_free(proto[1], 0);
254	sdp_list_free(apseq, 0);
255	sdp_list_free(pfseq, 0);
256	sdp_list_free(aproto, 0);
257	sdp_list_free(root, 0);
258	sdp_list_free(svclass_id, 0);
259
260	return record;
261}
262
263static sdp_record_t *avrcp_tg_record()
264{
265	sdp_list_t *svclass_id, *pfseq, *apseq, *root;
266	uuid_t root_uuid, l2cap, avctp, avrtg;
267	sdp_profile_desc_t profile[1];
268	sdp_list_t *aproto, *proto[2];
269	sdp_record_t *record;
270	sdp_data_t *psm, *version, *features;
271	uint16_t lp = AVCTP_PSM, ver = 0x0100, feat = 0x000f;
272
273	record = sdp_record_alloc();
274	if (!record)
275		return NULL;
276
277	sdp_uuid16_create(&root_uuid, PUBLIC_BROWSE_GROUP);
278	root = sdp_list_append(0, &root_uuid);
279	sdp_set_browse_groups(record, root);
280
281	/* Service Class ID List */
282	sdp_uuid16_create(&avrtg, AV_REMOTE_TARGET_SVCLASS_ID);
283	svclass_id = sdp_list_append(0, &avrtg);
284	sdp_set_service_classes(record, svclass_id);
285
286	/* Protocol Descriptor List */
287	sdp_uuid16_create(&l2cap, L2CAP_UUID);
288	proto[0] = sdp_list_append(0, &l2cap);
289	psm = sdp_data_alloc(SDP_UINT16, &lp);
290	proto[0] = sdp_list_append(proto[0], psm);
291	apseq = sdp_list_append(0, proto[0]);
292
293	sdp_uuid16_create(&avctp, AVCTP_UUID);
294	proto[1] = sdp_list_append(0, &avctp);
295	version = sdp_data_alloc(SDP_UINT16, &ver);
296	proto[1] = sdp_list_append(proto[1], version);
297	apseq = sdp_list_append(apseq, proto[1]);
298
299	aproto = sdp_list_append(0, apseq);
300	sdp_set_access_protos(record, aproto);
301
302	/* Bluetooth Profile Descriptor List */
303	sdp_uuid16_create(&profile[0].uuid, AV_REMOTE_PROFILE_ID);
304	profile[0].version = ver;
305	pfseq = sdp_list_append(0, &profile[0]);
306	sdp_set_profile_descs(record, pfseq);
307
308	features = sdp_data_alloc(SDP_UINT16, &feat);
309	sdp_attr_add(record, SDP_ATTR_SUPPORTED_FEATURES, features);
310
311	sdp_set_info_attr(record, "AVRCP TG", 0, 0);
312
313	free(psm);
314	free(version);
315	sdp_list_free(proto[0], 0);
316	sdp_list_free(proto[1], 0);
317	sdp_list_free(apseq, 0);
318	sdp_list_free(aproto, 0);
319	sdp_list_free(pfseq, 0);
320	sdp_list_free(root, 0);
321	sdp_list_free(svclass_id, 0);
322
323	return record;
324}
325
326static int send_event(int fd, uint16_t type, uint16_t code, int32_t value)
327{
328	struct uinput_event event;
329
330	memset(&event, 0, sizeof(event));
331	event.type	= type;
332	event.code	= code;
333	event.value	= value;
334
335	return write(fd, &event, sizeof(event));
336}
337
338static void send_key(int fd, uint16_t key, int pressed)
339{
340	if (fd < 0)
341		return;
342
343	send_event(fd, EV_KEY, key, pressed);
344	send_event(fd, EV_SYN, SYN_REPORT, 0);
345}
346
347static void handle_panel_passthrough(struct control *control,
348					const unsigned char *operands,
349					int operand_count)
350{
351	const char *status;
352	int pressed, i;
353
354	if (operand_count == 0)
355		return;
356
357	if (operands[0] & 0x80) {
358		status = "released";
359		pressed = 0;
360	} else {
361		status = "pressed";
362		pressed = 1;
363	}
364
365	for (i = 0; key_map[i].name != NULL; i++) {
366		if ((operands[0] & 0x7F) == key_map[i].avrcp) {
367			debug("AVRCP: %s %s", key_map[i].name, status);
368			send_key(control->uinput, key_map[i].uinput, pressed);
369			break;
370		}
371	}
372
373	if (key_map[i].name == NULL)
374		debug("AVRCP: unknown button 0x%02X %s",
375						operands[0] & 0x7F, status);
376}
377
378static void avctp_disconnected(struct audio_device *dev)
379{
380	struct control *control = dev->control;
381
382	if (!control)
383		return;
384
385	if (control->io) {
386		g_io_channel_shutdown(control->io, TRUE, NULL);
387		g_io_channel_unref(control->io);
388		control->io = NULL;
389	}
390
391	if (control->io_id) {
392		g_source_remove(control->io_id);
393		control->io_id = 0;
394	}
395
396	if (control->uinput >= 0) {
397		ioctl(control->uinput, UI_DEV_DESTROY);
398		close(control->uinput);
399		control->uinput = -1;
400	}
401}
402
403static void avctp_set_state(struct control *control, avctp_state_t new_state)
404{
405	GSList *l;
406	struct audio_device *dev = control->dev;
407	avdtp_session_state_t old_state = control->state;
408	gboolean value;
409
410	switch (new_state) {
411	case AVCTP_STATE_DISCONNECTED:
412		avctp_disconnected(control->dev);
413
414		if (old_state != AVCTP_STATE_CONNECTED)
415			break;
416
417		value = FALSE;
418		g_dbus_emit_signal(dev->conn, dev->path,
419					AUDIO_CONTROL_INTERFACE,
420					"Disconnected", DBUS_TYPE_INVALID);
421		emit_property_changed(dev->conn, dev->path,
422					AUDIO_CONTROL_INTERFACE, "Connected",
423					DBUS_TYPE_BOOLEAN, &value);
424		break;
425	case AVCTP_STATE_CONNECTING:
426		break;
427	case AVCTP_STATE_CONNECTED:
428		value = TRUE;
429		g_dbus_emit_signal(control->dev->conn, control->dev->path,
430				AUDIO_CONTROL_INTERFACE, "Connected",
431				DBUS_TYPE_INVALID);
432		emit_property_changed(control->dev->conn, control->dev->path,
433				AUDIO_CONTROL_INTERFACE, "Connected",
434				DBUS_TYPE_BOOLEAN, &value);
435		break;
436	default:
437		error("Invalid AVCTP state %d", new_state);
438		return;
439	}
440
441	control->state = new_state;
442
443	for (l = avctp_callbacks; l != NULL; l = l->next) {
444		struct avctp_state_callback *cb = l->data;
445		cb->cb(control->dev, old_state, new_state, cb->user_data);
446	}
447}
448
449static gboolean control_cb(GIOChannel *chan, GIOCondition cond,
450				gpointer data)
451{
452	struct control *control = data;
453	unsigned char buf[1024], *operands;
454	struct avctp_header *avctp;
455	struct avrcp_header *avrcp;
456	int ret, packet_size, operand_count, sock;
457
458	if (!(cond | G_IO_IN))
459		goto failed;
460
461	sock = g_io_channel_unix_get_fd(control->io);
462
463	ret = read(sock, buf, sizeof(buf));
464	if (ret <= 0)
465		goto failed;
466
467	debug("Got %d bytes of data for AVCTP session %p", ret, control);
468
469	if ((unsigned int) ret < sizeof(struct avctp_header)) {
470		error("Too small AVCTP packet");
471		goto failed;
472	}
473
474	packet_size = ret;
475
476	avctp = (struct avctp_header *) buf;
477
478	debug("AVCTP transaction %u, packet type %u, C/R %u, IPID %u, "
479			"PID 0x%04X",
480			avctp->transaction, avctp->packet_type,
481			avctp->cr, avctp->ipid, ntohs(avctp->pid));
482
483	ret -= sizeof(struct avctp_header);
484	if ((unsigned int) ret < sizeof(struct avrcp_header)) {
485		error("Too small AVRCP packet");
486		goto failed;
487	}
488
489	avrcp = (struct avrcp_header *) (buf + sizeof(struct avctp_header));
490
491	ret -= sizeof(struct avrcp_header);
492
493	operands = buf + sizeof(struct avctp_header) + sizeof(struct avrcp_header);
494	operand_count = ret;
495
496	debug("AVRCP %s 0x%01X, subunit_type 0x%02X, subunit_id 0x%01X, "
497			"opcode 0x%02X, %d operands",
498			avctp->cr ? "response" : "command",
499			avrcp->code, avrcp->subunit_type, avrcp->subunit_id,
500			avrcp->opcode, operand_count);
501
502	if (avctp->packet_type != AVCTP_PACKET_SINGLE) {
503		avctp->cr = AVCTP_RESPONSE;
504		avrcp->code = CTYPE_NOT_IMPLEMENTED;
505	} else if (avctp->pid != htons(AV_REMOTE_SVCLASS_ID)) {
506		avctp->ipid = 1;
507		avctp->cr = AVCTP_RESPONSE;
508		avrcp->code = CTYPE_REJECTED;
509	} else if (avctp->cr == AVCTP_COMMAND &&
510			avrcp->code == CTYPE_CONTROL &&
511			avrcp->subunit_type == SUBUNIT_PANEL &&
512			avrcp->opcode == OP_PASSTHROUGH) {
513		handle_panel_passthrough(control, operands, operand_count);
514		avctp->cr = AVCTP_RESPONSE;
515		avrcp->code = CTYPE_ACCEPTED;
516	} else if (avctp->cr == AVCTP_COMMAND &&
517			avrcp->code == CTYPE_STATUS &&
518			(avrcp->opcode == OP_UNITINFO
519			|| avrcp->opcode == OP_SUBUNITINFO)) {
520		avctp->cr = AVCTP_RESPONSE;
521		avrcp->code = CTYPE_STABLE;
522		/* The first operand should be 0x07 for the UNITINFO response.
523		 * Neither AVRCP (section 22.1, page 117) nor AVC Digital
524		 * Interface Command Set (section 9.2.1, page 45) specs
525		 * explain this value but both use it */
526		if (operand_count >= 1 && avrcp->opcode == OP_UNITINFO)
527			operands[0] = 0x07;
528		if (operand_count >= 2)
529			operands[1] = SUBUNIT_PANEL << 3;
530		debug("reply to %s", avrcp->opcode == OP_UNITINFO ?
531				"OP_UNITINFO" : "OP_SUBUNITINFO");
532	} else {
533		avctp->cr = AVCTP_RESPONSE;
534		avrcp->code = CTYPE_REJECTED;
535	}
536	ret = write(sock, buf, packet_size);
537
538	return TRUE;
539
540failed:
541	debug("AVCTP session %p got disconnected", control);
542	avctp_set_state(control, AVCTP_STATE_DISCONNECTED);
543	return FALSE;
544}
545
546static int uinput_create(char *name)
547{
548	struct uinput_dev dev;
549	int fd, err, i;
550
551	fd = open("/dev/uinput", O_RDWR);
552	if (fd < 0) {
553		fd = open("/dev/input/uinput", O_RDWR);
554		if (fd < 0) {
555			fd = open("/dev/misc/uinput", O_RDWR);
556			if (fd < 0) {
557				err = errno;
558				error("Can't open input device: %s (%d)",
559							strerror(err), err);
560				return -err;
561			}
562		}
563	}
564
565	memset(&dev, 0, sizeof(dev));
566	if (name)
567		strncpy(dev.name, name, UINPUT_MAX_NAME_SIZE - 1);
568
569	dev.id.bustype = BUS_BLUETOOTH;
570	dev.id.vendor  = 0x0000;
571	dev.id.product = 0x0000;
572	dev.id.version = 0x0000;
573
574	if (write(fd, &dev, sizeof(dev)) < 0) {
575		err = errno;
576		error("Can't write device information: %s (%d)",
577						strerror(err), err);
578		close(fd);
579		errno = err;
580		return -err;
581	}
582
583	ioctl(fd, UI_SET_EVBIT, EV_KEY);
584	ioctl(fd, UI_SET_EVBIT, EV_REL);
585	ioctl(fd, UI_SET_EVBIT, EV_REP);
586	ioctl(fd, UI_SET_EVBIT, EV_SYN);
587
588	for (i = 0; key_map[i].name != NULL; i++)
589		ioctl(fd, UI_SET_KEYBIT, key_map[i].uinput);
590
591	if (ioctl(fd, UI_DEV_CREATE, NULL) < 0) {
592		err = errno;
593		error("Can't create uinput device: %s (%d)",
594						strerror(err), err);
595		close(fd);
596		errno = err;
597		return -err;
598	}
599
600	return fd;
601}
602
603static void init_uinput(struct control *control)
604{
605	char address[18], *name;
606
607	ba2str(&control->dev->dst, address);
608
609	/* Use device name from config file if specified */
610	name = input_device_name;
611	if (!name)
612		name = address;
613
614	control->uinput = uinput_create(name);
615	if (control->uinput < 0)
616		error("AVRCP: failed to init uinput for %s", address);
617	else
618		debug("AVRCP: uinput initialized for %s", address);
619}
620
621static void avctp_connect_cb(GIOChannel *chan, GError *err, gpointer data)
622{
623	struct control *control = data;
624	char address[18];
625	uint16_t imtu;
626	GError *gerr = NULL;
627
628	if (err) {
629		avctp_set_state(control, AVCTP_STATE_DISCONNECTED);
630		error("%s", err->message);
631		return;
632	}
633
634	bt_io_get(chan, BT_IO_L2CAP, &gerr,
635			BT_IO_OPT_DEST, &address,
636			BT_IO_OPT_IMTU, &imtu,
637			BT_IO_OPT_INVALID);
638	if (gerr) {
639		avctp_set_state(control, AVCTP_STATE_DISCONNECTED);
640		error("%s", gerr->message);
641		g_error_free(gerr);
642		return;
643	}
644
645	debug("AVCTP: connected to %s", address);
646
647	if (!control->io)
648		control->io = g_io_channel_ref(chan);
649
650	init_uinput(control);
651
652	avctp_set_state(control, AVCTP_STATE_CONNECTED);
653	control->mtu = imtu;
654	control->io_id = g_io_add_watch(chan,
655				G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
656				(GIOFunc) control_cb, control);
657}
658
659static void auth_cb(DBusError *derr, void *user_data)
660{
661	struct control *control = user_data;
662	GError *err = NULL;
663
664	if (derr && dbus_error_is_set(derr)) {
665		error("Access denied: %s", derr->message);
666		avctp_set_state(control, AVCTP_STATE_DISCONNECTED);
667		return;
668	}
669
670	if (!bt_io_accept(control->io, avctp_connect_cb, control,
671								NULL, &err)) {
672		error("bt_io_accept: %s", err->message);
673		g_error_free(err);
674		avctp_set_state(control, AVCTP_STATE_DISCONNECTED);
675	}
676}
677
678static void avctp_confirm_cb(GIOChannel *chan, gpointer data)
679{
680	struct control *control = NULL;
681	struct audio_device *dev;
682	char address[18];
683	bdaddr_t src, dst;
684	GError *err = NULL;
685
686	bt_io_get(chan, BT_IO_L2CAP, &err,
687			BT_IO_OPT_SOURCE_BDADDR, &src,
688			BT_IO_OPT_DEST_BDADDR, &dst,
689			BT_IO_OPT_DEST, address,
690			BT_IO_OPT_INVALID);
691	if (err) {
692		error("%s", err->message);
693		g_error_free(err);
694		g_io_channel_shutdown(chan, TRUE, NULL);
695		return;
696	}
697
698	dev = manager_get_device(&src, &dst, TRUE);
699	if (!dev) {
700		error("Unable to get audio device object for %s", address);
701		goto drop;
702	}
703
704	if (!dev->control) {
705		btd_device_add_uuid(dev->btd_dev, AVRCP_REMOTE_UUID);
706		if (!dev->control)
707			goto drop;
708	}
709
710	control = dev->control;
711
712	if (control->io) {
713		error("Refusing unexpected connect from %s", address);
714		goto drop;
715	}
716
717	avctp_set_state(control, AVCTP_STATE_CONNECTING);
718	control->io = g_io_channel_ref(chan);
719
720	if (audio_device_request_authorization(dev, AVRCP_TARGET_UUID,
721						auth_cb, dev->control) < 0)
722		goto drop;
723
724	return;
725
726drop:
727	if (!control || !control->io)
728		g_io_channel_shutdown(chan, TRUE, NULL);
729	if (control)
730		avctp_set_state(control, AVCTP_STATE_DISCONNECTED);
731}
732
733static GIOChannel *avctp_server_socket(const bdaddr_t *src, gboolean master)
734{
735	GError *err = NULL;
736	GIOChannel *io;
737
738	io = bt_io_listen(BT_IO_L2CAP, NULL, avctp_confirm_cb, NULL,
739				NULL, &err,
740				BT_IO_OPT_SOURCE_BDADDR, src,
741				BT_IO_OPT_PSM, AVCTP_PSM,
742				BT_IO_OPT_SEC_LEVEL, BT_IO_SEC_MEDIUM,
743				BT_IO_OPT_MASTER, master,
744				BT_IO_OPT_INVALID);
745	if (!io) {
746		error("%s", err->message);
747		g_error_free(err);
748	}
749
750	return io;
751}
752
753gboolean avrcp_connect(struct audio_device *dev)
754{
755	struct control *control = dev->control;
756	GError *err = NULL;
757	GIOChannel *io;
758
759	if (control->state > AVCTP_STATE_DISCONNECTED)
760		return TRUE;
761
762	avctp_set_state(control, AVCTP_STATE_CONNECTING);
763
764	io = bt_io_connect(BT_IO_L2CAP, avctp_connect_cb, control, NULL, &err,
765				BT_IO_OPT_SOURCE_BDADDR, &dev->src,
766				BT_IO_OPT_DEST_BDADDR, &dev->dst,
767				BT_IO_OPT_PSM, AVCTP_PSM,
768				BT_IO_OPT_INVALID);
769	if (err) {
770		avctp_set_state(control, AVCTP_STATE_DISCONNECTED);
771		error("%s", err->message);
772		g_error_free(err);
773		return FALSE;
774	}
775
776	control->io = io;
777
778	return TRUE;
779}
780
781void avrcp_disconnect(struct audio_device *dev)
782{
783	struct control *control = dev->control;
784
785	if (!(control && control->io))
786		return;
787
788	avctp_set_state(control, AVCTP_STATE_DISCONNECTED);
789}
790
791int avrcp_register(DBusConnection *conn, const bdaddr_t *src, GKeyFile *config)
792{
793	sdp_record_t *record;
794	gboolean tmp, master = TRUE;
795	GError *err = NULL;
796	struct avctp_server *server;
797
798	if (config) {
799		tmp = g_key_file_get_boolean(config, "General",
800							"Master", &err);
801		if (err) {
802			debug("audio.conf: %s", err->message);
803			g_error_free(err);
804		} else
805			master = tmp;
806		err = NULL;
807		input_device_name = g_key_file_get_string(config,
808			"AVRCP", "InputDeviceName", &err);
809		if (err) {
810			debug("audio.conf: %s", err->message);
811			input_device_name = NULL;
812			g_error_free(err);
813		}
814	}
815
816	server = g_new0(struct avctp_server, 1);
817	if (!server)
818		return -ENOMEM;
819
820	if (!connection)
821		connection = dbus_connection_ref(conn);
822
823	record = avrcp_tg_record();
824	if (!record) {
825		error("Unable to allocate new service record");
826		return -1;
827	}
828
829	if (add_record_to_server(src, record) < 0) {
830		error("Unable to register AVRCP target service record");
831		sdp_record_free(record);
832		return -1;
833	}
834	server->tg_record_id = record->handle;
835
836#ifndef ANDROID
837	record = avrcp_ct_record();
838	if (!record) {
839		error("Unable to allocate new service record");
840		return -1;
841	}
842
843	if (add_record_to_server(src, record) < 0) {
844		error("Unable to register AVRCP controller service record");
845		sdp_record_free(record);
846		return -1;
847	}
848	server->ct_record_id = record->handle;
849#endif
850
851	server->io = avctp_server_socket(src, master);
852	if (!server->io) {
853#ifndef ANDROID
854		remove_record_from_server(server->ct_record_id);
855#endif
856		remove_record_from_server(server->tg_record_id);
857		g_free(server);
858		return -1;
859	}
860
861	bacpy(&server->src, src);
862
863	servers = g_slist_append(servers, server);
864
865	return 0;
866}
867
868static struct avctp_server *find_server(GSList *list, const bdaddr_t *src)
869{
870	GSList *l;
871
872	for (l = list; l; l = l->next) {
873		struct avctp_server *server = l->data;
874
875		if (bacmp(&server->src, src) == 0)
876			return server;
877	}
878
879	return NULL;
880}
881
882void avrcp_unregister(const bdaddr_t *src)
883{
884	struct avctp_server *server;
885
886	server = find_server(servers, src);
887	if (!server)
888		return;
889
890	servers = g_slist_remove(servers, server);
891
892#ifndef ANDROID
893	remove_record_from_server(server->ct_record_id);
894#endif
895	remove_record_from_server(server->tg_record_id);
896
897	g_io_channel_shutdown(server->io, TRUE, NULL);
898	g_io_channel_unref(server->io);
899	g_free(server);
900
901	if (servers)
902		return;
903
904	dbus_connection_unref(connection);
905	connection = NULL;
906}
907
908static DBusMessage *control_is_connected(DBusConnection *conn,
909						DBusMessage *msg,
910						void *data)
911{
912	struct audio_device *device = data;
913	struct control *control = device->control;
914	DBusMessage *reply;
915	dbus_bool_t connected;
916
917	reply = dbus_message_new_method_return(msg);
918	if (!reply)
919		return NULL;
920
921	connected = (control->state == AVCTP_STATE_CONNECTED);
922
923	dbus_message_append_args(reply, DBUS_TYPE_BOOLEAN, &connected,
924					DBUS_TYPE_INVALID);
925
926	return reply;
927}
928
929static int avctp_send_passthrough(struct control *control, uint8_t op)
930{
931	unsigned char buf[AVCTP_HEADER_LENGTH + AVRCP_HEADER_LENGTH + 2];
932	struct avctp_header *avctp = (void *) buf;
933	struct avrcp_header *avrcp = (void *) &buf[AVCTP_HEADER_LENGTH];
934	uint8_t *operands = &buf[AVCTP_HEADER_LENGTH + AVRCP_HEADER_LENGTH];
935	int err, sk = g_io_channel_unix_get_fd(control->io);
936	static uint8_t transaction = 0;
937
938	memset(buf, 0, sizeof(buf));
939
940	avctp->transaction = transaction++;
941	avctp->packet_type = AVCTP_PACKET_SINGLE;
942	avctp->cr = AVCTP_COMMAND;
943	avctp->pid = htons(AV_REMOTE_SVCLASS_ID);
944
945	avrcp->code = CTYPE_CONTROL;
946	avrcp->subunit_type = SUBUNIT_PANEL;
947	avrcp->opcode = OP_PASSTHROUGH;
948
949	operands[0] = op & 0x7f;
950	operands[1] = 0;
951
952	err = write(sk, buf, sizeof(buf));
953	if (err < 0)
954		return err;
955
956	/* Button release */
957	avctp->transaction = transaction++;
958	operands[0] |= 0x80;
959
960	return write(sk, buf, sizeof(buf));
961}
962
963static DBusMessage *volume_up(DBusConnection *conn, DBusMessage *msg,
964								void *data)
965{
966	struct audio_device *device = data;
967	struct control *control = device->control;
968	DBusMessage *reply;
969	int err;
970
971	reply = dbus_message_new_method_return(msg);
972	if (!reply)
973		return NULL;
974
975	if (control->state != AVCTP_STATE_CONNECTED)
976		return g_dbus_create_error(msg,
977					ERROR_INTERFACE ".NotConnected",
978					"Device not Connected");
979
980	if (!control->target)
981		return g_dbus_create_error(msg,
982					ERROR_INTERFACE ".NotSupported",
983					"AVRCP Target role not supported");
984
985	err = avctp_send_passthrough(control, VOL_UP_OP);
986	if (err < 0)
987		return g_dbus_create_error(msg, ERROR_INTERFACE ".Failed",
988							strerror(-err));
989
990	return dbus_message_new_method_return(msg);
991}
992
993static DBusMessage *volume_down(DBusConnection *conn, DBusMessage *msg,
994								void *data)
995{
996	struct audio_device *device = data;
997	struct control *control = device->control;
998	DBusMessage *reply;
999	int err;
1000
1001	reply = dbus_message_new_method_return(msg);
1002	if (!reply)
1003		return NULL;
1004
1005	if (control->state != AVCTP_STATE_CONNECTED)
1006		return g_dbus_create_error(msg,
1007					ERROR_INTERFACE ".NotConnected",
1008					"Device not Connected");
1009
1010	if (!control->target)
1011		return g_dbus_create_error(msg,
1012					ERROR_INTERFACE ".NotSupported",
1013					"AVRCP Target role not supported");
1014
1015	err = avctp_send_passthrough(control, VOL_DOWN_OP);
1016	if (err < 0)
1017		return g_dbus_create_error(msg, ERROR_INTERFACE ".Failed",
1018							strerror(-err));
1019
1020	return dbus_message_new_method_return(msg);
1021}
1022
1023static DBusMessage *control_get_properties(DBusConnection *conn,
1024					DBusMessage *msg, void *data)
1025{
1026	struct audio_device *device = data;
1027	DBusMessage *reply;
1028	DBusMessageIter iter;
1029	DBusMessageIter dict;
1030	gboolean value;
1031
1032	reply = dbus_message_new_method_return(msg);
1033	if (!reply)
1034		return NULL;
1035
1036	dbus_message_iter_init_append(reply, &iter);
1037
1038	dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
1039			DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
1040			DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
1041			DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict);
1042
1043	/* Connected */
1044	value = (device->control->state == AVCTP_STATE_CONNECTED);
1045	dict_append_entry(&dict, "Connected", DBUS_TYPE_BOOLEAN, &value);
1046
1047	dbus_message_iter_close_container(&iter, &dict);
1048
1049	return reply;
1050}
1051
1052static GDBusMethodTable control_methods[] = {
1053	{ "IsConnected",	"",	"b",	control_is_connected,
1054						G_DBUS_METHOD_FLAG_DEPRECATED },
1055	{ "GetProperties",	"",	"a{sv}",control_get_properties },
1056	{ "VolumeUp",		"",	"",	volume_up },
1057	{ "VolumeDown",		"",	"",	volume_down },
1058	{ NULL, NULL, NULL, NULL }
1059};
1060
1061static GDBusSignalTable control_signals[] = {
1062	{ "Connected",			"",	G_DBUS_SIGNAL_FLAG_DEPRECATED},
1063	{ "Disconnected",		"",	G_DBUS_SIGNAL_FLAG_DEPRECATED},
1064	{ "PropertyChanged",		"sv"	},
1065	{ NULL, NULL }
1066};
1067
1068static void path_unregister(void *data)
1069{
1070	struct audio_device *dev = data;
1071	struct control *control = dev->control;
1072
1073	debug("Unregistered interface %s on path %s",
1074		AUDIO_CONTROL_INTERFACE, dev->path);
1075
1076	if (control->state != AVCTP_STATE_DISCONNECTED)
1077		avctp_disconnected(dev);
1078
1079	g_free(control);
1080	dev->control = NULL;
1081}
1082
1083void control_unregister(struct audio_device *dev)
1084{
1085	g_dbus_unregister_interface(dev->conn, dev->path,
1086		AUDIO_CONTROL_INTERFACE);
1087}
1088
1089void control_update(struct audio_device *dev, uint16_t uuid16)
1090{
1091	struct control *control = dev->control;
1092
1093	if (uuid16 == AV_REMOTE_TARGET_SVCLASS_ID)
1094		control->target = TRUE;
1095}
1096
1097struct control *control_init(struct audio_device *dev, uint16_t uuid16)
1098{
1099	struct control *control;
1100
1101	if (!g_dbus_register_interface(dev->conn, dev->path,
1102					AUDIO_CONTROL_INTERFACE,
1103					control_methods, control_signals, NULL,
1104					dev, path_unregister))
1105		return NULL;
1106
1107	debug("Registered interface %s on path %s",
1108		AUDIO_CONTROL_INTERFACE, dev->path);
1109
1110	control = g_new0(struct control, 1);
1111	control->dev = dev;
1112	control->state = AVCTP_STATE_DISCONNECTED;
1113	control->uinput = -1;
1114
1115	if (uuid16 == AV_REMOTE_TARGET_SVCLASS_ID)
1116		control->target = TRUE;
1117
1118	return control;
1119}
1120
1121gboolean control_is_active(struct audio_device *dev)
1122{
1123	struct control *control = dev->control;
1124
1125	if (control && control->state != AVCTP_STATE_DISCONNECTED)
1126		return TRUE;
1127
1128	return FALSE;
1129}
1130
1131unsigned int avctp_add_state_cb(avctp_state_cb cb, void *user_data)
1132{
1133	struct avctp_state_callback *state_cb;
1134	static unsigned int id = 0;
1135
1136	state_cb = g_new(struct avctp_state_callback, 1);
1137	state_cb->cb = cb;
1138	state_cb->user_data = user_data;
1139	state_cb->id = ++id;
1140
1141	avctp_callbacks = g_slist_append(avctp_callbacks, state_cb);
1142
1143	return state_cb->id;
1144}
1145
1146gboolean avctp_remove_state_cb(unsigned int id)
1147{
1148	GSList *l;
1149
1150	for (l = avctp_callbacks; l != NULL; l = l->next) {
1151		struct avctp_state_callback *cb = l->data;
1152		if (cb && cb->id == id) {
1153			avctp_callbacks = g_slist_remove(avctp_callbacks, cb);
1154			g_free(cb);
1155			return TRUE;
1156		}
1157	}
1158
1159	return FALSE;
1160}
1161