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