Home | History | Annotate | Download | only in audio
      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 (at) 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 <stdio.h>
     31 #include <stdint.h>
     32 #include <errno.h>
     33 #include <unistd.h>
     34 #include <assert.h>
     35 #include <signal.h>
     36 #include <netinet/in.h>
     37 
     38 #include <bluetooth/bluetooth.h>
     39 #include <bluetooth/sdp.h>
     40 #include <bluetooth/sdp_lib.h>
     41 
     42 #include <glib.h>
     43 #include <dbus/dbus.h>
     44 
     45 #include "log.h"
     46 
     47 #include "../src/manager.h"
     48 #include "../src/adapter.h"
     49 #include "../src/device.h"
     50 
     51 #include "device.h"
     52 #include "manager.h"
     53 #include "control.h"
     54 #include "avdtp.h"
     55 #include "glib-helper.h"
     56 #include "btio.h"
     57 #include "sink.h"
     58 #include "source.h"
     59 
     60 #include <bluetooth/l2cap.h>
     61 
     62 #define AVDTP_PSM 25
     63 
     64 #define MAX_SEID 0x3E
     65 
     66 #define AVDTP_DISCOVER				0x01
     67 #define AVDTP_GET_CAPABILITIES			0x02
     68 #define AVDTP_SET_CONFIGURATION			0x03
     69 #define AVDTP_GET_CONFIGURATION			0x04
     70 #define AVDTP_RECONFIGURE			0x05
     71 #define AVDTP_OPEN				0x06
     72 #define AVDTP_START				0x07
     73 #define AVDTP_CLOSE				0x08
     74 #define AVDTP_SUSPEND				0x09
     75 #define AVDTP_ABORT				0x0A
     76 #define AVDTP_SECURITY_CONTROL			0x0B
     77 #define AVDTP_GET_ALL_CAPABILITIES		0x0C
     78 #define AVDTP_DELAY_REPORT			0x0D
     79 
     80 #define AVDTP_PKT_TYPE_SINGLE			0x00
     81 #define AVDTP_PKT_TYPE_START			0x01
     82 #define AVDTP_PKT_TYPE_CONTINUE			0x02
     83 #define AVDTP_PKT_TYPE_END			0x03
     84 
     85 #define AVDTP_MSG_TYPE_COMMAND			0x00
     86 #define AVDTP_MSG_TYPE_GEN_REJECT		0x01
     87 #define AVDTP_MSG_TYPE_ACCEPT			0x02
     88 #define AVDTP_MSG_TYPE_REJECT			0x03
     89 
     90 #define REQ_TIMEOUT 4
     91 #define ABORT_TIMEOUT 2
     92 #define DISCONNECT_TIMEOUT 1
     93 #define STREAM_TIMEOUT 20
     94 
     95 #if __BYTE_ORDER == __LITTLE_ENDIAN
     96 
     97 struct avdtp_common_header {
     98 	uint8_t message_type:2;
     99 	uint8_t packet_type:2;
    100 	uint8_t transaction:4;
    101 } __attribute__ ((packed));
    102 
    103 struct avdtp_single_header {
    104 	uint8_t message_type:2;
    105 	uint8_t packet_type:2;
    106 	uint8_t transaction:4;
    107 	uint8_t signal_id:6;
    108 	uint8_t rfa0:2;
    109 } __attribute__ ((packed));
    110 
    111 struct avdtp_start_header {
    112 	uint8_t message_type:2;
    113 	uint8_t packet_type:2;
    114 	uint8_t transaction:4;
    115 	uint8_t no_of_packets;
    116 	uint8_t signal_id:6;
    117 	uint8_t rfa0:2;
    118 } __attribute__ ((packed));
    119 
    120 struct avdtp_continue_header {
    121 	uint8_t message_type:2;
    122 	uint8_t packet_type:2;
    123 	uint8_t transaction:4;
    124 } __attribute__ ((packed));
    125 
    126 struct seid_info {
    127 	uint8_t rfa0:1;
    128 	uint8_t inuse:1;
    129 	uint8_t seid:6;
    130 	uint8_t rfa2:3;
    131 	uint8_t type:1;
    132 	uint8_t media_type:4;
    133 } __attribute__ ((packed));
    134 
    135 struct seid {
    136 	uint8_t rfa0:2;
    137 	uint8_t seid:6;
    138 } __attribute__ ((packed));
    139 
    140 #elif __BYTE_ORDER == __BIG_ENDIAN
    141 
    142 struct avdtp_common_header {
    143 	uint8_t transaction:4;
    144 	uint8_t packet_type:2;
    145 	uint8_t message_type:2;
    146 } __attribute__ ((packed));
    147 
    148 struct avdtp_single_header {
    149 	uint8_t transaction:4;
    150 	uint8_t packet_type:2;
    151 	uint8_t message_type:2;
    152 	uint8_t rfa0:2;
    153 	uint8_t signal_id:6;
    154 } __attribute__ ((packed));
    155 
    156 struct avdtp_start_header {
    157 	uint8_t transaction:4;
    158 	uint8_t packet_type:2;
    159 	uint8_t message_type:2;
    160 	uint8_t no_of_packets;
    161 	uint8_t rfa0:2;
    162 	uint8_t signal_id:6;
    163 } __attribute__ ((packed));
    164 
    165 struct avdtp_continue_header {
    166 	uint8_t transaction:4;
    167 	uint8_t packet_type:2;
    168 	uint8_t message_type:2;
    169 } __attribute__ ((packed));
    170 
    171 struct seid_info {
    172 	uint8_t seid:6;
    173 	uint8_t inuse:1;
    174 	uint8_t rfa0:1;
    175 	uint8_t media_type:4;
    176 	uint8_t type:1;
    177 	uint8_t rfa2:3;
    178 } __attribute__ ((packed));
    179 
    180 struct seid {
    181 	uint8_t seid:6;
    182 	uint8_t rfa0:2;
    183 } __attribute__ ((packed));
    184 
    185 #else
    186 #error "Unknown byte order"
    187 #endif
    188 
    189 /* packets */
    190 
    191 struct discover_resp {
    192 	struct seid_info seps[0];
    193 } __attribute__ ((packed));
    194 
    195 struct getcap_resp {
    196 	uint8_t caps[0];
    197 } __attribute__ ((packed));
    198 
    199 struct start_req {
    200 	struct seid first_seid;
    201 	struct seid other_seids[0];
    202 } __attribute__ ((packed));
    203 
    204 struct suspend_req {
    205 	struct seid first_seid;
    206 	struct seid other_seids[0];
    207 } __attribute__ ((packed));
    208 
    209 struct seid_rej {
    210 	uint8_t error;
    211 } __attribute__ ((packed));
    212 
    213 struct conf_rej {
    214 	uint8_t category;
    215 	uint8_t error;
    216 } __attribute__ ((packed));
    217 
    218 #if __BYTE_ORDER == __LITTLE_ENDIAN
    219 
    220 struct seid_req {
    221 	uint8_t rfa0:2;
    222 	uint8_t acp_seid:6;
    223 } __attribute__ ((packed));
    224 
    225 struct setconf_req {
    226 	uint8_t rfa0:2;
    227 	uint8_t acp_seid:6;
    228 	uint8_t rfa1:2;
    229 	uint8_t int_seid:6;
    230 
    231 	uint8_t caps[0];
    232 } __attribute__ ((packed));
    233 
    234 struct stream_rej {
    235 	uint8_t rfa0:2;
    236 	uint8_t acp_seid:6;
    237 	uint8_t error;
    238 } __attribute__ ((packed));
    239 
    240 struct reconf_req {
    241 	uint8_t rfa0:2;
    242 	uint8_t acp_seid:6;
    243 
    244 	uint8_t serv_cap;
    245 	uint8_t serv_cap_len;
    246 
    247 	uint8_t caps[0];
    248 } __attribute__ ((packed));
    249 
    250 struct delay_req {
    251 	uint8_t rfa0:2;
    252 	uint8_t acp_seid:6;
    253 	uint16_t delay;
    254 } __attribute__ ((packed));
    255 
    256 #elif __BYTE_ORDER == __BIG_ENDIAN
    257 
    258 struct seid_req {
    259 	uint8_t acp_seid:6;
    260 	uint8_t rfa0:2;
    261 } __attribute__ ((packed));
    262 
    263 struct setconf_req {
    264 	uint8_t acp_seid:6;
    265 	uint8_t rfa0:2;
    266 	uint8_t int_seid:6;
    267 	uint8_t rfa1:2;
    268 
    269 	uint8_t caps[0];
    270 } __attribute__ ((packed));
    271 
    272 struct stream_rej {
    273 	uint8_t acp_seid:6;
    274 	uint8_t rfa0:2;
    275 	uint8_t error;
    276 } __attribute__ ((packed));
    277 
    278 struct reconf_req {
    279 	uint8_t acp_seid:6;
    280 	uint8_t rfa0:2;
    281 
    282 	uint8_t serv_cap;
    283 	uint8_t serv_cap_len;
    284 
    285 	uint8_t caps[0];
    286 } __attribute__ ((packed));
    287 
    288 struct delay_req {
    289 	uint8_t acp_seid:6;
    290 	uint8_t rfa0:2;
    291 	uint16_t delay;
    292 } __attribute__ ((packed));
    293 
    294 #else
    295 #error "Unknown byte order"
    296 #endif
    297 
    298 struct in_buf {
    299 	gboolean active;
    300 	int no_of_packets;
    301 	uint8_t transaction;
    302 	uint8_t message_type;
    303 	uint8_t signal_id;
    304 	uint8_t buf[1024];
    305 	uint8_t data_size;
    306 };
    307 
    308 struct pending_req {
    309 	uint8_t transaction;
    310 	uint8_t signal_id;
    311 	void *data;
    312 	size_t data_size;
    313 	struct avdtp_stream *stream; /* Set if the request targeted a stream */
    314 	guint timeout;
    315 };
    316 
    317 struct avdtp_remote_sep {
    318 	uint8_t seid;
    319 	uint8_t type;
    320 	uint8_t media_type;
    321 	struct avdtp_service_capability *codec;
    322 	gboolean delay_reporting;
    323 	GSList *caps; /* of type struct avdtp_service_capability */
    324 	struct avdtp_stream *stream;
    325 };
    326 
    327 struct avdtp_server {
    328 	bdaddr_t src;
    329 	uint16_t version;
    330 	GIOChannel *io;
    331 	GSList *seps;
    332 	GSList *sessions;
    333 };
    334 
    335 struct avdtp_local_sep {
    336 	avdtp_state_t state;
    337 	struct avdtp_stream *stream;
    338 	struct seid_info info;
    339 	uint8_t codec;
    340 	gboolean delay_reporting;
    341 	GSList *caps;
    342 	struct avdtp_sep_ind *ind;
    343 	struct avdtp_sep_cfm *cfm;
    344 	void *user_data;
    345 	struct avdtp_server *server;
    346 };
    347 
    348 struct stream_callback {
    349 	avdtp_stream_state_cb cb;
    350 	void *user_data;
    351 	unsigned int id;
    352 };
    353 
    354 struct avdtp_state_callback {
    355 	avdtp_session_state_cb cb;
    356 	void *user_data;
    357 	unsigned int id;
    358 };
    359 
    360 struct avdtp_stream {
    361 	GIOChannel *io;
    362 	uint16_t imtu;
    363 	uint16_t omtu;
    364 	struct avdtp *session;
    365 	struct avdtp_local_sep *lsep;
    366 	uint8_t rseid;
    367 	GSList *caps;
    368 	GSList *callbacks;
    369 	struct avdtp_service_capability *codec;
    370 	guint io_id;		/* Transport GSource ID */
    371 	guint timer;		/* Waiting for other side to close or open
    372 				 * the transport channel */
    373 	gboolean open_acp;	/* If we are in ACT role for Open */
    374 	gboolean close_int;	/* If we are in INT role for Close */
    375 	gboolean abort_int;	/* If we are in INT role for Abort */
    376 	guint idle_timer;
    377 	gboolean delay_reporting;
    378 	uint16_t delay;		/* AVDTP 1.3 Delay Reporting feature */
    379 };
    380 
    381 /* Structure describing an AVDTP connection between two devices */
    382 
    383 struct avdtp {
    384 	int ref;
    385 	int free_lock;
    386 
    387 	uint16_t version;
    388 
    389 	struct avdtp_server *server;
    390 	bdaddr_t dst;
    391 
    392 	avdtp_session_state_t state;
    393 
    394 	/* True if the session should be automatically disconnected */
    395 	gboolean auto_dc;
    396 
    397 	GIOChannel *io;
    398 	guint io_id;
    399 
    400 	GSList *seps; /* Elements of type struct avdtp_remote_sep * */
    401 
    402 	GSList *streams; /* Elements of type struct avdtp_stream * */
    403 
    404 	GSList *req_queue; /* Elements of type struct pending_req * */
    405 	GSList *prio_queue; /* Same as req_queue but is processed before it */
    406 
    407 	struct avdtp_stream *pending_open;
    408 
    409 	uint16_t imtu;
    410 	uint16_t omtu;
    411 
    412 	struct in_buf in;
    413 
    414 	char *buf;
    415 
    416 	avdtp_discover_cb_t discov_cb;
    417 	void *user_data;
    418 
    419 	struct pending_req *req;
    420 
    421 	guint dc_timer;
    422 
    423 	/* Attempt stream setup instead of disconnecting */
    424 	gboolean stream_setup;
    425 
    426 	DBusPendingCall *pending_auth;
    427 };
    428 
    429 static GSList *servers = NULL;
    430 
    431 static GSList *avdtp_callbacks = NULL;
    432 
    433 static gboolean auto_connect = TRUE;
    434 
    435 static int send_request(struct avdtp *session, gboolean priority,
    436 			struct avdtp_stream *stream, uint8_t signal_id,
    437 			void *buffer, size_t size);
    438 static gboolean avdtp_parse_resp(struct avdtp *session,
    439 					struct avdtp_stream *stream,
    440 					uint8_t transaction, uint8_t signal_id,
    441 					void *buf, int size);
    442 static gboolean avdtp_parse_rej(struct avdtp *session,
    443 					struct avdtp_stream *stream,
    444 					uint8_t transaction, uint8_t signal_id,
    445 					void *buf, int size);
    446 static int process_queue(struct avdtp *session);
    447 static void connection_lost(struct avdtp *session, int err);
    448 static void avdtp_sep_set_state(struct avdtp *session,
    449 				struct avdtp_local_sep *sep,
    450 				avdtp_state_t state);
    451 static void auth_cb(DBusError *derr, void *user_data);
    452 
    453 static struct avdtp_server *find_server(GSList *list, const bdaddr_t *src)
    454 {
    455 	GSList *l;
    456 
    457 	for (l = list; l; l = l->next) {
    458 		struct avdtp_server *server = l->data;
    459 
    460 		if (bacmp(&server->src, src) == 0)
    461 			return server;
    462 	}
    463 
    464 	return NULL;
    465 }
    466 
    467 static const char *avdtp_statestr(avdtp_state_t state)
    468 {
    469 	switch (state) {
    470 	case AVDTP_STATE_IDLE:
    471 		return "IDLE";
    472 	case AVDTP_STATE_CONFIGURED:
    473 		return "CONFIGURED";
    474 	case AVDTP_STATE_OPEN:
    475 		return "OPEN";
    476 	case AVDTP_STATE_STREAMING:
    477 		return "STREAMING";
    478 	case AVDTP_STATE_CLOSING:
    479 		return "CLOSING";
    480 	case AVDTP_STATE_ABORTING:
    481 		return "ABORTING";
    482 	default:
    483 		return "<unknown state>";
    484 	}
    485 }
    486 
    487 static gboolean try_send(int sk, void *data, size_t len)
    488 {
    489 	int err;
    490 
    491 	do {
    492 		err = send(sk, data, len, 0);
    493 	} while (err < 0 && errno == EINTR);
    494 
    495 	if (err < 0) {
    496 		error("send: %s (%d)", strerror(errno), errno);
    497 		return FALSE;
    498 	} else if ((size_t) err != len) {
    499 		error("try_send: complete buffer not sent (%d/%zu bytes)",
    500 								err, len);
    501 		return FALSE;
    502 	}
    503 
    504 	return TRUE;
    505 }
    506 
    507 static gboolean avdtp_send(struct avdtp *session, uint8_t transaction,
    508 				uint8_t message_type, uint8_t signal_id,
    509 				void *data, size_t len)
    510 {
    511 	unsigned int cont_fragments, sent;
    512 	struct avdtp_start_header start;
    513 	struct avdtp_continue_header cont;
    514 	int sock;
    515 
    516 	if (session->io == NULL) {
    517 		error("avdtp_send: session is closed");
    518 		return FALSE;
    519 	}
    520 
    521 	sock = g_io_channel_unix_get_fd(session->io);
    522 
    523 	/* Single packet - no fragmentation */
    524 	if (sizeof(struct avdtp_single_header) + len <= session->omtu) {
    525 		struct avdtp_single_header single;
    526 
    527 		memset(&single, 0, sizeof(single));
    528 
    529 		single.transaction = transaction;
    530 		single.packet_type = AVDTP_PKT_TYPE_SINGLE;
    531 		single.message_type = message_type;
    532 		single.signal_id = signal_id;
    533 
    534 		memcpy(session->buf, &single, sizeof(single));
    535 		memcpy(session->buf + sizeof(single), data, len);
    536 
    537 		return try_send(sock, session->buf, sizeof(single) + len);
    538 	}
    539 
    540 	/* Count the number of needed fragments */
    541 	cont_fragments = (len - (session->omtu - sizeof(start))) /
    542 					(session->omtu - sizeof(cont)) + 1;
    543 
    544 	DBG("%zu bytes split into %d fragments", len, cont_fragments + 1);
    545 
    546 	/* Send the start packet */
    547 	memset(&start, 0, sizeof(start));
    548 	start.transaction = transaction;
    549 	start.packet_type = AVDTP_PKT_TYPE_START;
    550 	start.message_type = message_type;
    551 	start.no_of_packets = cont_fragments + 1;
    552 	start.signal_id = signal_id;
    553 
    554 	memcpy(session->buf, &start, sizeof(start));
    555 	memcpy(session->buf + sizeof(start), data,
    556 					session->omtu - sizeof(start));
    557 
    558 	if (!try_send(sock, session->buf, session->omtu))
    559 		return FALSE;
    560 
    561 	DBG("first packet with %zu bytes sent", session->omtu - sizeof(start));
    562 
    563 	sent = session->omtu - sizeof(start);
    564 
    565 	/* Send the continue fragments and the end packet */
    566 	while (sent < len) {
    567 		int left, to_copy;
    568 
    569 		left = len - sent;
    570 		if (left + sizeof(cont) > session->omtu) {
    571 			cont.packet_type = AVDTP_PKT_TYPE_CONTINUE;
    572 			to_copy = session->omtu - sizeof(cont);
    573 			DBG("sending continue with %d bytes", to_copy);
    574 		} else {
    575 			cont.packet_type = AVDTP_PKT_TYPE_END;
    576 			to_copy = left;
    577 			DBG("sending end with %d bytes", to_copy);
    578 		}
    579 
    580 		cont.transaction = transaction;
    581 		cont.message_type = message_type;
    582 
    583 		memcpy(session->buf, &cont, sizeof(cont));
    584 		memcpy(session->buf + sizeof(cont), data + sent, to_copy);
    585 
    586 		if (!try_send(sock, session->buf, to_copy + sizeof(cont)))
    587 			return FALSE;
    588 
    589 		sent += to_copy;
    590 	}
    591 
    592 	return TRUE;
    593 }
    594 
    595 static void pending_req_free(struct pending_req *req)
    596 {
    597 	if (req->timeout)
    598 		g_source_remove(req->timeout);
    599 	g_free(req->data);
    600 	g_free(req);
    601 }
    602 
    603 static void close_stream(struct avdtp_stream *stream)
    604 {
    605 	int sock;
    606 
    607 	if (stream->io == NULL)
    608 		return;
    609 
    610 	sock = g_io_channel_unix_get_fd(stream->io);
    611 
    612 	shutdown(sock, SHUT_RDWR);
    613 
    614 	g_io_channel_shutdown(stream->io, FALSE, NULL);
    615 
    616 	g_io_channel_unref(stream->io);
    617 	stream->io = NULL;
    618 }
    619 
    620 static gboolean stream_close_timeout(gpointer user_data)
    621 {
    622 	struct avdtp_stream *stream = user_data;
    623 
    624 	DBG("Timed out waiting for peer to close the transport channel");
    625 
    626 	stream->timer = 0;
    627 
    628 	close_stream(stream);
    629 
    630 	return FALSE;
    631 }
    632 
    633 static gboolean stream_open_timeout(gpointer user_data)
    634 {
    635 	struct avdtp_stream *stream = user_data;
    636 
    637 	DBG("Timed out waiting for peer to open the transport channel");
    638 
    639 	stream->timer = 0;
    640 
    641 	stream->session->pending_open = NULL;
    642 
    643 	avdtp_abort(stream->session, stream);
    644 
    645 	return FALSE;
    646 }
    647 
    648 static gboolean disconnect_timeout(gpointer user_data)
    649 {
    650 	struct avdtp *session = user_data;
    651 	struct audio_device *dev;
    652 	gboolean stream_setup;
    653 
    654 	session->dc_timer = 0;
    655 	stream_setup = session->stream_setup;
    656 	session->stream_setup = FALSE;
    657 
    658 	dev = manager_get_device(&session->server->src, &session->dst, FALSE);
    659 
    660 	if (dev && dev->sink && stream_setup)
    661 		sink_setup_stream(dev->sink, session);
    662 	else if (dev && dev->source && stream_setup)
    663 		source_setup_stream(dev->source, session);
    664 	else
    665 		connection_lost(session, ETIMEDOUT);
    666 
    667 	return FALSE;
    668 }
    669 
    670 static void remove_disconnect_timer(struct avdtp *session)
    671 {
    672 	g_source_remove(session->dc_timer);
    673 	session->dc_timer = 0;
    674 	session->stream_setup = FALSE;
    675 }
    676 
    677 static void set_disconnect_timer(struct avdtp *session)
    678 {
    679 	if (session->dc_timer)
    680 		remove_disconnect_timer(session);
    681 
    682 	session->dc_timer = g_timeout_add_seconds(DISCONNECT_TIMEOUT,
    683 						disconnect_timeout,
    684 						session);
    685 }
    686 
    687 void avdtp_error_init(struct avdtp_error *err, uint8_t type, int id)
    688 {
    689 	err->type = type;
    690 	switch (type) {
    691 	case AVDTP_ERROR_ERRNO:
    692 		err->err.posix_errno = id;
    693 		break;
    694 	case AVDTP_ERROR_ERROR_CODE:
    695 		err->err.error_code = id;
    696 		break;
    697 	}
    698 }
    699 
    700 avdtp_error_type_t avdtp_error_type(struct avdtp_error *err)
    701 {
    702 	return err->type;
    703 }
    704 
    705 int avdtp_error_error_code(struct avdtp_error *err)
    706 {
    707 	assert(err->type == AVDTP_ERROR_ERROR_CODE);
    708 	return err->err.error_code;
    709 }
    710 
    711 int avdtp_error_posix_errno(struct avdtp_error *err)
    712 {
    713 	assert(err->type == AVDTP_ERROR_ERRNO);
    714 	return err->err.posix_errno;
    715 }
    716 
    717 static struct avdtp_stream *find_stream_by_rseid(struct avdtp *session,
    718 							uint8_t rseid)
    719 {
    720 	GSList *l;
    721 
    722 	for (l = session->streams; l != NULL; l = g_slist_next(l)) {
    723 		struct avdtp_stream *stream = l->data;
    724 
    725 		if (stream->rseid == rseid)
    726 			return stream;
    727 	}
    728 
    729 	return NULL;
    730 }
    731 
    732 static struct avdtp_remote_sep *find_remote_sep(GSList *seps, uint8_t seid)
    733 {
    734 	GSList *l;
    735 
    736 	for (l = seps; l != NULL; l = g_slist_next(l)) {
    737 		struct avdtp_remote_sep *sep = l->data;
    738 
    739 		if (sep->seid == seid)
    740 			return sep;
    741 	}
    742 
    743 	return NULL;
    744 }
    745 
    746 static void avdtp_set_state(struct avdtp *session,
    747 					avdtp_session_state_t new_state)
    748 {
    749 	GSList *l;
    750 	struct audio_device *dev;
    751 	bdaddr_t src, dst;
    752 	avdtp_session_state_t old_state = session->state;
    753 
    754 	session->state = new_state;
    755 
    756 	avdtp_get_peers(session, &src, &dst);
    757 	dev = manager_get_device(&src, &dst, FALSE);
    758 	if (dev == NULL) {
    759 		error("avdtp_set_state(): no matching audio device");
    760 		return;
    761 	}
    762 
    763 	for (l = avdtp_callbacks; l != NULL; l = l->next) {
    764 		struct avdtp_state_callback *cb = l->data;
    765 		cb->cb(dev, session, old_state, new_state, cb->user_data);
    766 	}
    767 }
    768 
    769 static void stream_free(struct avdtp_stream *stream)
    770 {
    771 	struct avdtp_remote_sep *rsep;
    772 
    773 	stream->lsep->info.inuse = 0;
    774 	stream->lsep->stream = NULL;
    775 
    776 	rsep = find_remote_sep(stream->session->seps, stream->rseid);
    777 	if (rsep)
    778 		rsep->stream = NULL;
    779 
    780 	if (stream->timer)
    781 		g_source_remove(stream->timer);
    782 
    783 	if (stream->io)
    784 		g_io_channel_unref(stream->io);
    785 
    786 	if (stream->io_id)
    787 		g_source_remove(stream->io_id);
    788 
    789 	g_slist_foreach(stream->callbacks, (GFunc) g_free, NULL);
    790 	g_slist_free(stream->callbacks);
    791 
    792 	g_slist_foreach(stream->caps, (GFunc) g_free, NULL);
    793 	g_slist_free(stream->caps);
    794 
    795 	g_free(stream);
    796 }
    797 
    798 static gboolean stream_timeout(gpointer user_data)
    799 {
    800 	struct avdtp_stream *stream = user_data;
    801 	struct avdtp *session = stream->session;
    802 
    803 	if (avdtp_close(session, stream, FALSE) < 0)
    804 		error("stream_timeout: closing AVDTP stream failed");
    805 
    806 	stream->idle_timer = 0;
    807 
    808 	return FALSE;
    809 }
    810 
    811 static gboolean transport_cb(GIOChannel *chan, GIOCondition cond,
    812 				gpointer data)
    813 {
    814 	struct avdtp_stream *stream = data;
    815 	struct avdtp_local_sep *sep = stream->lsep;
    816 
    817 	if (stream->close_int && sep->cfm && sep->cfm->close)
    818 		sep->cfm->close(stream->session, sep, stream, NULL,
    819 				sep->user_data);
    820 
    821 	if (!(cond & G_IO_NVAL))
    822 		close_stream(stream);
    823 
    824 	stream->io_id = 0;
    825 
    826 	if (!stream->abort_int)
    827 		avdtp_sep_set_state(stream->session, sep, AVDTP_STATE_IDLE);
    828 
    829 	return FALSE;
    830 }
    831 
    832 static void handle_transport_connect(struct avdtp *session, GIOChannel *io,
    833 					uint16_t imtu, uint16_t omtu)
    834 {
    835 	struct avdtp_stream *stream = session->pending_open;
    836 	struct avdtp_local_sep *sep = stream->lsep;
    837 
    838 	session->pending_open = NULL;
    839 
    840 	if (stream->timer) {
    841 		g_source_remove(stream->timer);
    842 		stream->timer = 0;
    843 	}
    844 
    845 	if (io == NULL) {
    846 		if (!stream->open_acp && sep->cfm && sep->cfm->open) {
    847 			struct avdtp_error err;
    848 			avdtp_error_init(&err, AVDTP_ERROR_ERRNO, EIO);
    849 			sep->cfm->open(session, sep, NULL, &err,
    850 					sep->user_data);
    851 		}
    852 		return;
    853 	}
    854 
    855 	stream->io = g_io_channel_ref(io);
    856 	stream->omtu = omtu;
    857 	stream->imtu = imtu;
    858 
    859 	if (!stream->open_acp && sep->cfm && sep->cfm->open)
    860 		sep->cfm->open(session, sep, stream, NULL, sep->user_data);
    861 
    862 	avdtp_sep_set_state(session, sep, AVDTP_STATE_OPEN);
    863 
    864 	stream->io_id = g_io_add_watch(io, G_IO_ERR | G_IO_HUP | G_IO_NVAL,
    865 					(GIOFunc) transport_cb, stream);
    866 }
    867 
    868 static int pending_req_cmp(gconstpointer a, gconstpointer b)
    869 {
    870 	const struct pending_req *req = a;
    871 	const struct avdtp_stream *stream = b;
    872 
    873 	if (req->stream == stream)
    874 		return 0;
    875 
    876 	return -1;
    877 }
    878 
    879 static void cleanup_queue(struct avdtp *session, struct avdtp_stream *stream)
    880 {
    881 	GSList *l;
    882 	struct pending_req *req;
    883 
    884 	while ((l = g_slist_find_custom(session->prio_queue, stream,
    885 							pending_req_cmp))) {
    886 		req = l->data;
    887 		pending_req_free(req);
    888 		session->prio_queue = g_slist_remove(session->prio_queue, req);
    889 	}
    890 
    891 	while ((l = g_slist_find_custom(session->req_queue, stream,
    892 							pending_req_cmp))) {
    893 		req = l->data;
    894 		pending_req_free(req);
    895 		session->req_queue = g_slist_remove(session->req_queue, req);
    896 	}
    897 }
    898 
    899 static void handle_unanswered_req(struct avdtp *session,
    900 						struct avdtp_stream *stream)
    901 {
    902 	struct pending_req *req;
    903 	struct avdtp_local_sep *lsep;
    904 	struct avdtp_error err;
    905 
    906 	if (session->req->signal_id == AVDTP_ABORT) {
    907 		/* Avoid freeing the Abort request here */
    908 		DBG("handle_unanswered_req: Abort req, returning");
    909 		session->req->stream = NULL;
    910 		return;
    911 	}
    912 
    913 	req = session->req;
    914 	session->req = NULL;
    915 
    916 	avdtp_error_init(&err, AVDTP_ERROR_ERRNO, EIO);
    917 
    918 	lsep = stream->lsep;
    919 
    920 	switch (req->signal_id) {
    921 	case AVDTP_RECONFIGURE:
    922 		error("No reply to Reconfigure request");
    923 		if (lsep && lsep->cfm && lsep->cfm->reconfigure)
    924 			lsep->cfm->reconfigure(session, lsep, stream, &err,
    925 						lsep->user_data);
    926 		break;
    927 	case AVDTP_OPEN:
    928 		error("No reply to Open request");
    929 		if (lsep && lsep->cfm && lsep->cfm->open)
    930 			lsep->cfm->open(session, lsep, stream, &err,
    931 					lsep->user_data);
    932 		break;
    933 	case AVDTP_START:
    934 		error("No reply to Start request");
    935 		if (lsep && lsep->cfm && lsep->cfm->start)
    936 			lsep->cfm->start(session, lsep, stream, &err,
    937 						lsep->user_data);
    938 		break;
    939 	case AVDTP_SUSPEND:
    940 		error("No reply to Suspend request");
    941 		if (lsep && lsep->cfm && lsep->cfm->suspend)
    942 			lsep->cfm->suspend(session, lsep, stream, &err,
    943 						lsep->user_data);
    944 		break;
    945 	case AVDTP_CLOSE:
    946 		error("No reply to Close request");
    947 		if (lsep && lsep->cfm && lsep->cfm->close)
    948 			lsep->cfm->close(session, lsep, stream, &err,
    949 						lsep->user_data);
    950 		break;
    951 	case AVDTP_SET_CONFIGURATION:
    952 		error("No reply to SetConfiguration request");
    953 		if (lsep && lsep->cfm && lsep->cfm->set_configuration)
    954 			lsep->cfm->set_configuration(session, lsep, stream,
    955 							&err, lsep->user_data);
    956 	}
    957 
    958 	pending_req_free(req);
    959 }
    960 
    961 static void avdtp_sep_set_state(struct avdtp *session,
    962 				struct avdtp_local_sep *sep,
    963 				avdtp_state_t state)
    964 {
    965 	struct avdtp_stream *stream = sep->stream;
    966 	avdtp_state_t old_state;
    967 	struct avdtp_error err, *err_ptr = NULL;
    968 	GSList *l;
    969 
    970 	if (!stream) {
    971 		error("Error changing sep state: stream not available");
    972 		return;
    973 	}
    974 
    975 	if (sep->state == state) {
    976 		avdtp_error_init(&err, AVDTP_ERROR_ERRNO, EIO);
    977 		DBG("stream state change failed: %s", avdtp_strerror(&err));
    978 		err_ptr = &err;
    979 	} else {
    980 		err_ptr = NULL;
    981 		DBG("stream state changed: %s -> %s",
    982 				avdtp_statestr(sep->state),
    983 				avdtp_statestr(state));
    984 	}
    985 
    986 	old_state = sep->state;
    987 	sep->state = state;
    988 
    989 	for (l = stream->callbacks; l != NULL; l = g_slist_next(l)) {
    990 		struct stream_callback *cb = l->data;
    991 		cb->cb(stream, old_state, state, err_ptr, cb->user_data);
    992 	}
    993 
    994 	switch (state) {
    995 	case AVDTP_STATE_CONFIGURED:
    996 		if (sep->info.type == AVDTP_SEP_TYPE_SINK)
    997 			avdtp_delay_report(session, stream, stream->delay);
    998 		break;
    999 	case AVDTP_STATE_OPEN:
   1000 		if (old_state > AVDTP_STATE_OPEN && session->auto_dc)
   1001 			stream->idle_timer = g_timeout_add_seconds(STREAM_TIMEOUT,
   1002 								stream_timeout,
   1003 								stream);
   1004 		break;
   1005 	case AVDTP_STATE_STREAMING:
   1006 	case AVDTP_STATE_CLOSING:
   1007 	case AVDTP_STATE_ABORTING:
   1008 		if (stream->idle_timer) {
   1009 			g_source_remove(stream->idle_timer);
   1010 			stream->idle_timer = 0;
   1011 		}
   1012 		break;
   1013 	case AVDTP_STATE_IDLE:
   1014 		if (stream->idle_timer) {
   1015 			g_source_remove(stream->idle_timer);
   1016 			stream->idle_timer = 0;
   1017 		}
   1018 		session->streams = g_slist_remove(session->streams, stream);
   1019 		if (session->pending_open == stream)
   1020 			handle_transport_connect(session, NULL, 0, 0);
   1021 		if (session->req && session->req->stream == stream)
   1022 			handle_unanswered_req(session, stream);
   1023 		/* Remove pending commands for this stream from the queue */
   1024 		cleanup_queue(session, stream);
   1025 		stream_free(stream);
   1026 		if (session->ref == 1 && !session->streams)
   1027 			set_disconnect_timer(session);
   1028 		break;
   1029 	default:
   1030 		break;
   1031 	}
   1032 }
   1033 
   1034 static void finalize_discovery(struct avdtp *session, int err)
   1035 {
   1036 	struct avdtp_error avdtp_err;
   1037 
   1038 	avdtp_error_init(&avdtp_err, AVDTP_ERROR_ERRNO, err);
   1039 
   1040 	if (!session->discov_cb)
   1041 		return;
   1042 
   1043 	session->discov_cb(session, session->seps,
   1044 				err ? &avdtp_err : NULL,
   1045 				session->user_data);
   1046 
   1047 	session->discov_cb = NULL;
   1048 	session->user_data = NULL;
   1049 }
   1050 
   1051 static void release_stream(struct avdtp_stream *stream, struct avdtp *session)
   1052 {
   1053 	struct avdtp_local_sep *sep = stream->lsep;
   1054 
   1055 	if (sep->cfm && sep->cfm->abort &&
   1056 				(sep->state != AVDTP_STATE_ABORTING ||
   1057 							stream->abort_int))
   1058 		sep->cfm->abort(session, sep, stream, NULL, sep->user_data);
   1059 
   1060 	avdtp_sep_set_state(session, sep, AVDTP_STATE_IDLE);
   1061 }
   1062 
   1063 static void connection_lost(struct avdtp *session, int err)
   1064 {
   1065 	char address[18];
   1066 	struct audio_device *dev;
   1067 
   1068 	ba2str(&session->dst, address);
   1069 	DBG("Disconnected from %s", address);
   1070 
   1071 	dev = manager_get_device(&session->server->src, &session->dst, FALSE);
   1072 
   1073 	if (dev != NULL && session->state == AVDTP_SESSION_STATE_CONNECTING &&
   1074 								err != EACCES)
   1075 		audio_device_cancel_authorization(dev, auth_cb, session);
   1076 
   1077 	session->free_lock = 1;
   1078 
   1079 	finalize_discovery(session, err);
   1080 
   1081 	g_slist_foreach(session->streams, (GFunc) release_stream, session);
   1082 	session->streams = NULL;
   1083 
   1084 	session->free_lock = 0;
   1085 
   1086 	if (session->io) {
   1087 		g_io_channel_shutdown(session->io, FALSE, NULL);
   1088 		g_io_channel_unref(session->io);
   1089 		session->io = NULL;
   1090 	}
   1091 
   1092 	avdtp_set_state(session, AVDTP_SESSION_STATE_DISCONNECTED);
   1093 
   1094 	if (session->io_id) {
   1095 		g_source_remove(session->io_id);
   1096 		session->io_id = 0;
   1097 	}
   1098 
   1099 	if (session->dc_timer)
   1100 		remove_disconnect_timer(session);
   1101 
   1102 	session->auto_dc = TRUE;
   1103 
   1104 	if (session->ref != 1)
   1105 		error("connection_lost: ref count not 1 after all callbacks");
   1106 	else
   1107 		avdtp_unref(session);
   1108 }
   1109 
   1110 void avdtp_unref(struct avdtp *session)
   1111 {
   1112 	struct avdtp_server *server;
   1113 
   1114 	if (!session)
   1115 		return;
   1116 
   1117 	session->ref--;
   1118 
   1119 	DBG("%p: ref=%d", session, session->ref);
   1120 
   1121 	if (session->ref == 1) {
   1122 		if (session->state == AVDTP_SESSION_STATE_CONNECTING &&
   1123 								session->io) {
   1124 			struct audio_device *dev;
   1125 			dev = manager_get_device(&session->server->src,
   1126 							&session->dst, FALSE);
   1127 			audio_device_cancel_authorization(dev, auth_cb,
   1128 								session);
   1129 			g_io_channel_shutdown(session->io, TRUE, NULL);
   1130 			g_io_channel_unref(session->io);
   1131 			session->io = NULL;
   1132 		}
   1133 
   1134 		if (session->io)
   1135 			set_disconnect_timer(session);
   1136 		else if (!session->free_lock) /* Drop the local ref if we
   1137 						 aren't connected */
   1138 			session->ref--;
   1139 	}
   1140 
   1141 	if (session->ref > 0)
   1142 		return;
   1143 
   1144 	server = session->server;
   1145 
   1146 	DBG("%p: freeing session and removing from list", session);
   1147 
   1148 	if (session->dc_timer)
   1149 		remove_disconnect_timer(session);
   1150 
   1151 	server->sessions = g_slist_remove(server->sessions, session);
   1152 
   1153 	if (session->req)
   1154 		pending_req_free(session->req);
   1155 
   1156 	g_slist_foreach(session->seps, (GFunc) g_free, NULL);
   1157 	g_slist_free(session->seps);
   1158 
   1159 	g_free(session->buf);
   1160 
   1161 	g_free(session);
   1162 }
   1163 
   1164 struct avdtp *avdtp_ref(struct avdtp *session)
   1165 {
   1166 	session->ref++;
   1167 	DBG("%p: ref=%d", session, session->ref);
   1168 	if (session->dc_timer)
   1169 		remove_disconnect_timer(session);
   1170 	return session;
   1171 }
   1172 
   1173 static struct avdtp_local_sep *find_local_sep_by_seid(struct avdtp_server *server,
   1174 							uint8_t seid)
   1175 {
   1176 	GSList *l;
   1177 
   1178 	for (l = server->seps; l != NULL; l = g_slist_next(l)) {
   1179 		struct avdtp_local_sep *sep = l->data;
   1180 
   1181 		if (sep->info.seid == seid)
   1182 			return sep;
   1183 	}
   1184 
   1185 	return NULL;
   1186 }
   1187 
   1188 static struct avdtp_local_sep *find_local_sep(struct avdtp_server *server,
   1189 						uint8_t type,
   1190 						uint8_t media_type,
   1191 						uint8_t codec)
   1192 {
   1193 	GSList *l;
   1194 
   1195 	for (l = server->seps; l != NULL; l = g_slist_next(l)) {
   1196 		struct avdtp_local_sep *sep = l->data;
   1197 
   1198 		if (sep->info.inuse)
   1199 			continue;
   1200 
   1201 		if (sep->info.type == type &&
   1202 				sep->info.media_type == media_type &&
   1203 				sep->codec == codec)
   1204 			return sep;
   1205 	}
   1206 
   1207 	return NULL;
   1208 }
   1209 
   1210 static GSList *caps_to_list(uint8_t *data, int size,
   1211 				struct avdtp_service_capability **codec,
   1212 				gboolean *delay_reporting)
   1213 {
   1214 	GSList *caps;
   1215 	int processed;
   1216 
   1217 	if (delay_reporting)
   1218 		*delay_reporting = FALSE;
   1219 
   1220 	for (processed = 0, caps = NULL; processed + 2 <= size;) {
   1221 		struct avdtp_service_capability *cap;
   1222 		uint8_t length, category;
   1223 
   1224 		category = data[0];
   1225 		length = data[1];
   1226 
   1227 		if (processed + 2 + length > size) {
   1228 			error("Invalid capability data in getcap resp");
   1229 			break;
   1230 		}
   1231 
   1232 		cap = g_malloc(sizeof(struct avdtp_service_capability) +
   1233 					length);
   1234 		memcpy(cap, data, 2 + length);
   1235 
   1236 		processed += 2 + length;
   1237 		data += 2 + length;
   1238 
   1239 		caps = g_slist_append(caps, cap);
   1240 
   1241 		if (category == AVDTP_MEDIA_CODEC &&
   1242 				length >=
   1243 				sizeof(struct avdtp_media_codec_capability))
   1244 			*codec = cap;
   1245 		else if (category == AVDTP_DELAY_REPORTING && delay_reporting)
   1246 			*delay_reporting = TRUE;
   1247 	}
   1248 
   1249 	return caps;
   1250 }
   1251 
   1252 static gboolean avdtp_unknown_cmd(struct avdtp *session, uint8_t transaction,
   1253 							uint8_t signal_id)
   1254 {
   1255 	return avdtp_send(session, transaction, AVDTP_MSG_TYPE_GEN_REJECT,
   1256 							signal_id, NULL, 0);
   1257 }
   1258 
   1259 static gboolean avdtp_discover_cmd(struct avdtp *session, uint8_t transaction,
   1260 							void *buf, int size)
   1261 {
   1262 	GSList *l;
   1263 	unsigned int rsp_size, sep_count, i;
   1264 	struct seid_info *seps;
   1265 	gboolean ret;
   1266 
   1267 	sep_count = g_slist_length(session->server->seps);
   1268 
   1269 	if (sep_count == 0) {
   1270 		uint8_t err = AVDTP_NOT_SUPPORTED_COMMAND;
   1271 		return avdtp_send(session, transaction, AVDTP_MSG_TYPE_REJECT,
   1272 					AVDTP_DISCOVER, &err, sizeof(err));
   1273 	}
   1274 
   1275 	rsp_size = sep_count * sizeof(struct seid_info);
   1276 
   1277 	seps = g_new0(struct seid_info, sep_count);
   1278 
   1279 	for (l = session->server->seps, i = 0; l != NULL; l = l->next, i++) {
   1280 		struct avdtp_local_sep *sep = l->data;
   1281 
   1282 		memcpy(&seps[i], &sep->info, sizeof(struct seid_info));
   1283 	}
   1284 
   1285 	ret = avdtp_send(session, transaction, AVDTP_MSG_TYPE_ACCEPT,
   1286 				AVDTP_DISCOVER, seps, rsp_size);
   1287 	g_free(seps);
   1288 
   1289 	return ret;
   1290 }
   1291 
   1292 static gboolean avdtp_getcap_cmd(struct avdtp *session, uint8_t transaction,
   1293 					struct seid_req *req, unsigned int size,
   1294 					gboolean get_all)
   1295 {
   1296 	GSList *l, *caps;
   1297 	struct avdtp_local_sep *sep = NULL;
   1298 	unsigned int rsp_size;
   1299 	uint8_t err, buf[1024], *ptr = buf;
   1300 	uint8_t cmd;
   1301 
   1302 	cmd = get_all ? AVDTP_GET_ALL_CAPABILITIES : AVDTP_GET_CAPABILITIES;
   1303 
   1304 	if (size < sizeof(struct seid_req)) {
   1305 		err = AVDTP_BAD_LENGTH;
   1306 		goto failed;
   1307 	}
   1308 
   1309 	sep = find_local_sep_by_seid(session->server, req->acp_seid);
   1310 	if (!sep) {
   1311 		err = AVDTP_BAD_ACP_SEID;
   1312 		goto failed;
   1313 	}
   1314 
   1315 	if (get_all && session->server->version < 0x0103)
   1316 		return avdtp_unknown_cmd(session, transaction, cmd);
   1317 
   1318 	if (!sep->ind->get_capability(session, sep, get_all, &caps,
   1319 							&err, sep->user_data))
   1320 		goto failed;
   1321 
   1322 	for (l = caps, rsp_size = 0; l != NULL; l = g_slist_next(l)) {
   1323 		struct avdtp_service_capability *cap = l->data;
   1324 
   1325 		if (rsp_size + cap->length + 2 > sizeof(buf))
   1326 			break;
   1327 
   1328 		memcpy(ptr, cap, cap->length + 2);
   1329 		rsp_size += cap->length + 2;
   1330 		ptr += cap->length + 2;
   1331 
   1332 		g_free(cap);
   1333 	}
   1334 
   1335 	g_slist_free(caps);
   1336 
   1337 	return avdtp_send(session, transaction, AVDTP_MSG_TYPE_ACCEPT, cmd,
   1338 								buf, rsp_size);
   1339 
   1340 failed:
   1341 	return avdtp_send(session, transaction, AVDTP_MSG_TYPE_REJECT, cmd,
   1342 							&err, sizeof(err));
   1343 }
   1344 
   1345 static gboolean avdtp_setconf_cmd(struct avdtp *session, uint8_t transaction,
   1346 				struct setconf_req *req, unsigned int size)
   1347 {
   1348 	struct conf_rej rej;
   1349 	struct avdtp_local_sep *sep;
   1350 	struct avdtp_stream *stream;
   1351 	uint8_t err, category = 0x00;
   1352 	struct audio_device *dev;
   1353 	bdaddr_t src, dst;
   1354 	GSList *l;
   1355 
   1356 	if (size < sizeof(struct setconf_req)) {
   1357 		error("Too short getcap request");
   1358 		return FALSE;
   1359 	}
   1360 
   1361 	sep = find_local_sep_by_seid(session->server, req->acp_seid);
   1362 	if (!sep) {
   1363 		err = AVDTP_BAD_ACP_SEID;
   1364 		goto failed;
   1365 	}
   1366 
   1367 	if (sep->stream) {
   1368 		err = AVDTP_SEP_IN_USE;
   1369 		goto failed;
   1370 	}
   1371 
   1372 	avdtp_get_peers(session, &src, &dst);
   1373 	dev = manager_get_device(&src, &dst, FALSE);
   1374 	if (!dev) {
   1375 		error("Unable to get a audio device object");
   1376 		err = AVDTP_BAD_STATE;
   1377 		goto failed;
   1378 	}
   1379 
   1380 	switch (sep->info.type) {
   1381 	case AVDTP_SEP_TYPE_SOURCE:
   1382 		if (!dev->sink) {
   1383 			btd_device_add_uuid(dev->btd_dev, A2DP_SINK_UUID);
   1384 			if (!dev->sink) {
   1385 				error("Unable to get a audio sink object");
   1386 				err = AVDTP_BAD_STATE;
   1387 				goto failed;
   1388 			}
   1389 		}
   1390 		break;
   1391 	case AVDTP_SEP_TYPE_SINK:
   1392 		/* Do source_init() here when it's implemented */
   1393 		break;
   1394 	}
   1395 
   1396 	stream = g_new0(struct avdtp_stream, 1);
   1397 	stream->session = session;
   1398 	stream->lsep = sep;
   1399 	stream->rseid = req->int_seid;
   1400 	stream->caps = caps_to_list(req->caps,
   1401 					size - sizeof(struct setconf_req),
   1402 					&stream->codec,
   1403 					&stream->delay_reporting);
   1404 
   1405 	/* Verify that the Media Transport capability's length = 0. Reject otherwise */
   1406 	for (l = stream->caps; l != NULL; l = g_slist_next(l)) {
   1407 		struct avdtp_service_capability *cap = l->data;
   1408 
   1409 		if (cap->category == AVDTP_MEDIA_TRANSPORT && cap->length != 0) {
   1410 			err = AVDTP_BAD_MEDIA_TRANSPORT_FORMAT;
   1411 			goto failed_stream;
   1412 		}
   1413 	}
   1414 
   1415 	if (stream->delay_reporting && session->version < 0x0103)
   1416 		session->version = 0x0103;
   1417 
   1418 	if (sep->ind && sep->ind->set_configuration) {
   1419 		if (!sep->ind->set_configuration(session, sep, stream,
   1420 							stream->caps, &err,
   1421 							&category,
   1422 							sep->user_data))
   1423 			goto failed_stream;
   1424 	}
   1425 
   1426 	if (!avdtp_send(session, transaction, AVDTP_MSG_TYPE_ACCEPT,
   1427 					AVDTP_SET_CONFIGURATION, NULL, 0)) {
   1428 		stream_free(stream);
   1429 		return FALSE;
   1430 	}
   1431 
   1432 	sep->stream = stream;
   1433 	sep->info.inuse = 1;
   1434 	session->streams = g_slist_append(session->streams, stream);
   1435 
   1436 	avdtp_sep_set_state(session, sep, AVDTP_STATE_CONFIGURED);
   1437 
   1438 	return TRUE;
   1439 
   1440 failed_stream:
   1441 	stream_free(stream);
   1442 failed:
   1443 	rej.error = err;
   1444 	rej.category = category;
   1445 	return avdtp_send(session, transaction, AVDTP_MSG_TYPE_REJECT,
   1446 				AVDTP_SET_CONFIGURATION, &rej, sizeof(rej));
   1447 }
   1448 
   1449 static gboolean avdtp_getconf_cmd(struct avdtp *session, uint8_t transaction,
   1450 					struct seid_req *req, int size)
   1451 {
   1452 	GSList *l;
   1453 	struct avdtp_local_sep *sep = NULL;
   1454 	int rsp_size;
   1455 	uint8_t err;
   1456 	uint8_t buf[1024];
   1457 	uint8_t *ptr = buf;
   1458 
   1459 	if (size < (int) sizeof(struct seid_req)) {
   1460 		error("Too short getconf request");
   1461 		return FALSE;
   1462 	}
   1463 
   1464 	memset(buf, 0, sizeof(buf));
   1465 
   1466 	sep = find_local_sep_by_seid(session->server, req->acp_seid);
   1467 	if (!sep) {
   1468 		err = AVDTP_BAD_ACP_SEID;
   1469 		goto failed;
   1470 	}
   1471 	if (!sep->stream || !sep->stream->caps) {
   1472 		err = AVDTP_UNSUPPORTED_CONFIGURATION;
   1473 		goto failed;
   1474 	}
   1475 
   1476 	for (l = sep->stream->caps, rsp_size = 0; l != NULL; l = g_slist_next(l)) {
   1477 		struct avdtp_service_capability *cap = l->data;
   1478 
   1479 		if (rsp_size + cap->length + 2 > (int) sizeof(buf))
   1480 			break;
   1481 
   1482 		memcpy(ptr, cap, cap->length + 2);
   1483 		rsp_size += cap->length + 2;
   1484 		ptr += cap->length + 2;
   1485 	}
   1486 
   1487 	return avdtp_send(session, transaction, AVDTP_MSG_TYPE_ACCEPT,
   1488 				AVDTP_GET_CONFIGURATION, buf, rsp_size);
   1489 
   1490 failed:
   1491 	return avdtp_send(session, transaction, AVDTP_MSG_TYPE_REJECT,
   1492 				AVDTP_GET_CONFIGURATION, &err, sizeof(err));
   1493 }
   1494 
   1495 static gboolean avdtp_reconf_cmd(struct avdtp *session, uint8_t transaction,
   1496 					struct seid_req *req, int size)
   1497 {
   1498 	return avdtp_unknown_cmd(session, transaction, AVDTP_RECONFIGURE);
   1499 }
   1500 
   1501 static gboolean avdtp_open_cmd(struct avdtp *session, uint8_t transaction,
   1502 				struct seid_req *req, unsigned int size)
   1503 {
   1504 	struct avdtp_local_sep *sep;
   1505 	struct avdtp_stream *stream;
   1506 	uint8_t err;
   1507 
   1508 	if (size < sizeof(struct seid_req)) {
   1509 		error("Too short abort request");
   1510 		return FALSE;
   1511 	}
   1512 
   1513 	sep = find_local_sep_by_seid(session->server, req->acp_seid);
   1514 	if (!sep) {
   1515 		err = AVDTP_BAD_ACP_SEID;
   1516 		goto failed;
   1517 	}
   1518 
   1519 	if (sep->state != AVDTP_STATE_CONFIGURED) {
   1520 		err = AVDTP_BAD_STATE;
   1521 		goto failed;
   1522 	}
   1523 
   1524 	stream = sep->stream;
   1525 
   1526 	if (sep->ind && sep->ind->open) {
   1527 		if (!sep->ind->open(session, sep, stream, &err,
   1528 					sep->user_data))
   1529 			goto failed;
   1530 	}
   1531 
   1532 	if (!avdtp_send(session, transaction, AVDTP_MSG_TYPE_ACCEPT,
   1533 						AVDTP_OPEN, NULL, 0))
   1534 		return FALSE;
   1535 
   1536 	stream->open_acp = TRUE;
   1537 	session->pending_open = stream;
   1538 	stream->timer = g_timeout_add_seconds(REQ_TIMEOUT,
   1539 						stream_open_timeout,
   1540 						stream);
   1541 
   1542 	return TRUE;
   1543 
   1544 failed:
   1545 	return avdtp_send(session, transaction, AVDTP_MSG_TYPE_REJECT,
   1546 				AVDTP_OPEN, &err, sizeof(err));
   1547 }
   1548 
   1549 static gboolean avdtp_start_cmd(struct avdtp *session, uint8_t transaction,
   1550 				struct start_req *req, unsigned int size)
   1551 {
   1552 	struct avdtp_local_sep *sep;
   1553 	struct avdtp_stream *stream;
   1554 	struct stream_rej rej;
   1555 	struct seid *seid;
   1556 	uint8_t err, failed_seid;
   1557 	int seid_count, i;
   1558 
   1559 	if (size < sizeof(struct start_req)) {
   1560 		error("Too short start request");
   1561 		return FALSE;
   1562 	}
   1563 
   1564 	seid_count = 1 + size - sizeof(struct start_req);
   1565 
   1566 	seid = &req->first_seid;
   1567 
   1568 	for (i = 0; i < seid_count; i++, seid++) {
   1569 		failed_seid = seid->seid;
   1570 
   1571 		sep = find_local_sep_by_seid(session->server,
   1572 					req->first_seid.seid);
   1573 		if (!sep || !sep->stream) {
   1574 			err = AVDTP_BAD_ACP_SEID;
   1575 			goto failed;
   1576 		}
   1577 
   1578 		stream = sep->stream;
   1579 
   1580 		if (sep->state != AVDTP_STATE_OPEN) {
   1581 			err = AVDTP_BAD_STATE;
   1582 			goto failed;
   1583 		}
   1584 
   1585 		if (sep->ind && sep->ind->start) {
   1586 			if (!sep->ind->start(session, sep, stream, &err,
   1587 						sep->user_data))
   1588 				goto failed;
   1589 		}
   1590 
   1591 		avdtp_sep_set_state(session, sep, AVDTP_STATE_STREAMING);
   1592 	}
   1593 
   1594 	return avdtp_send(session, transaction, AVDTP_MSG_TYPE_ACCEPT,
   1595 						AVDTP_START, NULL, 0);
   1596 
   1597 failed:
   1598 	memset(&rej, 0, sizeof(rej));
   1599 	rej.acp_seid = failed_seid;
   1600 	rej.error = err;
   1601 	return avdtp_send(session, transaction, AVDTP_MSG_TYPE_REJECT,
   1602 				AVDTP_START, &rej, sizeof(rej));
   1603 }
   1604 
   1605 static gboolean avdtp_close_cmd(struct avdtp *session, uint8_t transaction,
   1606 				struct seid_req *req, unsigned int size)
   1607 {
   1608 	struct avdtp_local_sep *sep;
   1609 	struct avdtp_stream *stream;
   1610 	uint8_t err;
   1611 
   1612 	if (size < sizeof(struct seid_req)) {
   1613 		error("Too short close request");
   1614 		return FALSE;
   1615 	}
   1616 
   1617 	sep = find_local_sep_by_seid(session->server, req->acp_seid);
   1618 	if (!sep || !sep->stream) {
   1619 		err = AVDTP_BAD_ACP_SEID;
   1620 		goto failed;
   1621 	}
   1622 
   1623 	if (sep->state != AVDTP_STATE_OPEN &&
   1624 			sep->state != AVDTP_STATE_STREAMING) {
   1625 		err = AVDTP_BAD_STATE;
   1626 		goto failed;
   1627 	}
   1628 
   1629 	stream = sep->stream;
   1630 
   1631 	if (sep->ind && sep->ind->close) {
   1632 		if (!sep->ind->close(session, sep, stream, &err,
   1633 					sep->user_data))
   1634 			goto failed;
   1635 	}
   1636 
   1637 	avdtp_sep_set_state(session, sep, AVDTP_STATE_CLOSING);
   1638 
   1639 	if (!avdtp_send(session, transaction, AVDTP_MSG_TYPE_ACCEPT,
   1640 						AVDTP_CLOSE, NULL, 0))
   1641 		return FALSE;
   1642 
   1643 	stream->timer = g_timeout_add_seconds(REQ_TIMEOUT,
   1644 					stream_close_timeout,
   1645 					stream);
   1646 
   1647 	return TRUE;
   1648 
   1649 failed:
   1650 	return avdtp_send(session, transaction, AVDTP_MSG_TYPE_REJECT,
   1651 					AVDTP_CLOSE, &err, sizeof(err));
   1652 }
   1653 
   1654 static gboolean avdtp_suspend_cmd(struct avdtp *session, uint8_t transaction,
   1655 				struct suspend_req *req, unsigned int size)
   1656 {
   1657 	struct avdtp_local_sep *sep;
   1658 	struct avdtp_stream *stream;
   1659 	struct stream_rej rej;
   1660 	struct seid *seid;
   1661 	uint8_t err, failed_seid;
   1662 	int seid_count, i;
   1663 
   1664 	if (size < sizeof(struct suspend_req)) {
   1665 		error("Too short suspend request");
   1666 		return FALSE;
   1667 	}
   1668 
   1669 	seid_count = 1 + size - sizeof(struct suspend_req);
   1670 
   1671 	seid = &req->first_seid;
   1672 
   1673 	for (i = 0; i < seid_count; i++, seid++) {
   1674 		failed_seid = seid->seid;
   1675 
   1676 		sep = find_local_sep_by_seid(session->server,
   1677 					req->first_seid.seid);
   1678 		if (!sep || !sep->stream) {
   1679 			err = AVDTP_BAD_ACP_SEID;
   1680 			goto failed;
   1681 		}
   1682 
   1683 		stream = sep->stream;
   1684 
   1685 		if (sep->state != AVDTP_STATE_STREAMING) {
   1686 			err = AVDTP_BAD_STATE;
   1687 			goto failed;
   1688 		}
   1689 
   1690 		if (sep->ind && sep->ind->suspend) {
   1691 			if (!sep->ind->suspend(session, sep, stream, &err,
   1692 						sep->user_data))
   1693 				goto failed;
   1694 		}
   1695 
   1696 		avdtp_sep_set_state(session, sep, AVDTP_STATE_OPEN);
   1697 	}
   1698 
   1699 	return avdtp_send(session, transaction, AVDTP_MSG_TYPE_ACCEPT,
   1700 						AVDTP_SUSPEND, NULL, 0);
   1701 
   1702 failed:
   1703 	memset(&rej, 0, sizeof(rej));
   1704 	rej.acp_seid = failed_seid;
   1705 	rej.error = err;
   1706 	return avdtp_send(session, transaction, AVDTP_MSG_TYPE_REJECT,
   1707 				AVDTP_SUSPEND, &rej, sizeof(rej));
   1708 }
   1709 
   1710 static gboolean avdtp_abort_cmd(struct avdtp *session, uint8_t transaction,
   1711 				struct seid_req *req, unsigned int size)
   1712 {
   1713 	struct avdtp_local_sep *sep;
   1714 	uint8_t err;
   1715 	gboolean ret;
   1716 
   1717 	if (size < sizeof(struct seid_req)) {
   1718 		error("Too short abort request");
   1719 		return FALSE;
   1720 	}
   1721 
   1722 	sep = find_local_sep_by_seid(session->server, req->acp_seid);
   1723 	if (!sep || !sep->stream) {
   1724 		err = AVDTP_BAD_ACP_SEID;
   1725 		goto failed;
   1726 	}
   1727 
   1728 	if (sep->ind && sep->ind->abort) {
   1729 		if (!sep->ind->abort(session, sep, sep->stream, &err,
   1730 					sep->user_data))
   1731 			goto failed;
   1732 	}
   1733 
   1734 	ret = avdtp_send(session, transaction, AVDTP_MSG_TYPE_ACCEPT,
   1735 						AVDTP_ABORT, NULL, 0);
   1736 	if (ret)
   1737 		avdtp_sep_set_state(session, sep, AVDTP_STATE_ABORTING);
   1738 
   1739 	return ret;
   1740 
   1741 failed:
   1742 	return avdtp_send(session, transaction, AVDTP_MSG_TYPE_REJECT,
   1743 					AVDTP_ABORT, &err, sizeof(err));
   1744 }
   1745 
   1746 static gboolean avdtp_secctl_cmd(struct avdtp *session, uint8_t transaction,
   1747 					struct seid_req *req, int size)
   1748 {
   1749 	return avdtp_unknown_cmd(session, transaction, AVDTP_SECURITY_CONTROL);
   1750 }
   1751 
   1752 static gboolean avdtp_delayreport_cmd(struct avdtp *session,
   1753 					uint8_t transaction,
   1754 					struct delay_req *req,
   1755 					unsigned int size)
   1756 {
   1757 	struct avdtp_local_sep *sep;
   1758 	struct avdtp_stream *stream;
   1759 	uint8_t err;
   1760 
   1761 	if (size < sizeof(struct delay_req)) {
   1762 		error("Too short delay report request");
   1763 		return FALSE;
   1764 	}
   1765 
   1766 	sep = find_local_sep_by_seid(session->server, req->acp_seid);
   1767 	if (!sep || !sep->stream) {
   1768 		err = AVDTP_BAD_ACP_SEID;
   1769 		goto failed;
   1770 	}
   1771 
   1772 	stream = sep->stream;
   1773 
   1774 	if (sep->state != AVDTP_STATE_CONFIGURED &&
   1775 					sep->state != AVDTP_STATE_STREAMING) {
   1776 		err = AVDTP_BAD_STATE;
   1777 		goto failed;
   1778 	}
   1779 
   1780 	stream->delay = ntohs(req->delay);
   1781 
   1782 	if (sep->ind && sep->ind->delayreport) {
   1783 		if (!sep->ind->delayreport(session, sep, stream->rseid,
   1784 						stream->delay, &err,
   1785 						sep->user_data))
   1786 			goto failed;
   1787 	}
   1788 
   1789 	return avdtp_send(session, transaction, AVDTP_MSG_TYPE_ACCEPT,
   1790 						AVDTP_DELAY_REPORT, NULL, 0);
   1791 
   1792 failed:
   1793 	return avdtp_send(session, transaction, AVDTP_MSG_TYPE_REJECT,
   1794 					AVDTP_DELAY_REPORT, &err, sizeof(err));
   1795 }
   1796 
   1797 static gboolean avdtp_parse_cmd(struct avdtp *session, uint8_t transaction,
   1798 				uint8_t signal_id, void *buf, int size)
   1799 {
   1800 	switch (signal_id) {
   1801 	case AVDTP_DISCOVER:
   1802 		DBG("Received DISCOVER_CMD");
   1803 		return avdtp_discover_cmd(session, transaction, buf, size);
   1804 	case AVDTP_GET_CAPABILITIES:
   1805 		DBG("Received  GET_CAPABILITIES_CMD");
   1806 		return avdtp_getcap_cmd(session, transaction, buf, size,
   1807 									FALSE);
   1808 	case AVDTP_GET_ALL_CAPABILITIES:
   1809 		DBG("Received  GET_ALL_CAPABILITIES_CMD");
   1810 		return avdtp_getcap_cmd(session, transaction, buf, size, TRUE);
   1811 	case AVDTP_SET_CONFIGURATION:
   1812 		DBG("Received SET_CONFIGURATION_CMD");
   1813 		return avdtp_setconf_cmd(session, transaction, buf, size);
   1814 	case AVDTP_GET_CONFIGURATION:
   1815 		DBG("Received GET_CONFIGURATION_CMD");
   1816 		return avdtp_getconf_cmd(session, transaction, buf, size);
   1817 	case AVDTP_RECONFIGURE:
   1818 		DBG("Received RECONFIGURE_CMD");
   1819 		return avdtp_reconf_cmd(session, transaction, buf, size);
   1820 	case AVDTP_OPEN:
   1821 		DBG("Received OPEN_CMD");
   1822 		return avdtp_open_cmd(session, transaction, buf, size);
   1823 	case AVDTP_START:
   1824 		DBG("Received START_CMD");
   1825 		return avdtp_start_cmd(session, transaction, buf, size);
   1826 	case AVDTP_CLOSE:
   1827 		DBG("Received CLOSE_CMD");
   1828 		return avdtp_close_cmd(session, transaction, buf, size);
   1829 	case AVDTP_SUSPEND:
   1830 		DBG("Received SUSPEND_CMD");
   1831 		return avdtp_suspend_cmd(session, transaction, buf, size);
   1832 	case AVDTP_ABORT:
   1833 		DBG("Received ABORT_CMD");
   1834 		return avdtp_abort_cmd(session, transaction, buf, size);
   1835 	case AVDTP_SECURITY_CONTROL:
   1836 		DBG("Received SECURITY_CONTROL_CMD");
   1837 		return avdtp_secctl_cmd(session, transaction, buf, size);
   1838 	case AVDTP_DELAY_REPORT:
   1839 		DBG("Received DELAY_REPORT_CMD");
   1840 		return avdtp_delayreport_cmd(session, transaction, buf, size);
   1841 	default:
   1842 		DBG("Received unknown request id %u", signal_id);
   1843 		return avdtp_unknown_cmd(session, transaction, signal_id);
   1844 	}
   1845 }
   1846 
   1847 enum avdtp_parse_result { PARSE_ERROR, PARSE_FRAGMENT, PARSE_SUCCESS };
   1848 
   1849 static enum avdtp_parse_result avdtp_parse_data(struct avdtp *session,
   1850 							void *buf, size_t size)
   1851 {
   1852 	struct avdtp_common_header *header = buf;
   1853 	struct avdtp_single_header *single = (void *) session->buf;
   1854 	struct avdtp_start_header *start = (void *) session->buf;
   1855 	void *payload;
   1856 	gsize payload_size;
   1857 
   1858 	switch (header->packet_type) {
   1859 	case AVDTP_PKT_TYPE_SINGLE:
   1860 		if (size < sizeof(*single)) {
   1861 			error("Received too small single packet (%zu bytes)", size);
   1862 			return PARSE_ERROR;
   1863 		}
   1864 		if (session->in.active) {
   1865 			error("SINGLE: Invalid AVDTP packet fragmentation");
   1866 			return PARSE_ERROR;
   1867 		}
   1868 
   1869 		payload = session->buf + sizeof(*single);
   1870 		payload_size = size - sizeof(*single);
   1871 
   1872 		session->in.active = TRUE;
   1873 		session->in.data_size = 0;
   1874 		session->in.no_of_packets = 1;
   1875 		session->in.transaction = header->transaction;
   1876 		session->in.message_type = header->message_type;
   1877 		session->in.signal_id = single->signal_id;
   1878 
   1879 		break;
   1880 	case AVDTP_PKT_TYPE_START:
   1881 		if (size < sizeof(*start)) {
   1882 			error("Received too small start packet (%zu bytes)", size);
   1883 			return PARSE_ERROR;
   1884 		}
   1885 		if (session->in.active) {
   1886 			error("START: Invalid AVDTP packet fragmentation");
   1887 			return PARSE_ERROR;
   1888 		}
   1889 
   1890 		session->in.active = TRUE;
   1891 		session->in.data_size = 0;
   1892 		session->in.transaction = header->transaction;
   1893 		session->in.message_type = header->message_type;
   1894 		session->in.no_of_packets = start->no_of_packets;
   1895 		session->in.signal_id = start->signal_id;
   1896 
   1897 		payload = session->buf + sizeof(*start);
   1898 		payload_size = size - sizeof(*start);
   1899 
   1900 		break;
   1901 	case AVDTP_PKT_TYPE_CONTINUE:
   1902 		if (size < sizeof(struct avdtp_continue_header)) {
   1903 			error("Received too small continue packet (%zu bytes)",
   1904 									size);
   1905 			return PARSE_ERROR;
   1906 		}
   1907 		if (!session->in.active) {
   1908 			error("CONTINUE: Invalid AVDTP packet fragmentation");
   1909 			return PARSE_ERROR;
   1910 		}
   1911 		if (session->in.transaction != header->transaction) {
   1912 			error("Continue transaction id doesn't match");
   1913 			return PARSE_ERROR;
   1914 		}
   1915 		if (session->in.no_of_packets <= 1) {
   1916 			error("Too few continue packets");
   1917 			return PARSE_ERROR;
   1918 		}
   1919 
   1920 		payload = session->buf + sizeof(struct avdtp_continue_header);
   1921 		payload_size = size - sizeof(struct avdtp_continue_header);
   1922 
   1923 		break;
   1924 	case AVDTP_PKT_TYPE_END:
   1925 		if (size < sizeof(struct avdtp_continue_header)) {
   1926 			error("Received too small end packet (%zu bytes)", size);
   1927 			return PARSE_ERROR;
   1928 		}
   1929 		if (!session->in.active) {
   1930 			error("END: Invalid AVDTP packet fragmentation");
   1931 			return PARSE_ERROR;
   1932 		}
   1933 		if (session->in.transaction != header->transaction) {
   1934 			error("End transaction id doesn't match");
   1935 			return PARSE_ERROR;
   1936 		}
   1937 		if (session->in.no_of_packets > 1) {
   1938 			error("Got an end packet too early");
   1939 			return PARSE_ERROR;
   1940 		}
   1941 
   1942 		payload = session->buf + sizeof(struct avdtp_continue_header);
   1943 		payload_size = size - sizeof(struct avdtp_continue_header);
   1944 
   1945 		break;
   1946 	default:
   1947 		error("Invalid AVDTP packet type 0x%02X", header->packet_type);
   1948 		return PARSE_ERROR;
   1949 	}
   1950 
   1951 	if (session->in.data_size + payload_size >
   1952 					sizeof(session->in.buf)) {
   1953 		error("Not enough incoming buffer space!");
   1954 		return PARSE_ERROR;
   1955 	}
   1956 
   1957 	memcpy(session->in.buf + session->in.data_size, payload, payload_size);
   1958 	session->in.data_size += payload_size;
   1959 
   1960 	if (session->in.no_of_packets > 1) {
   1961 		session->in.no_of_packets--;
   1962 		DBG("Received AVDTP fragment. %d to go",
   1963 						session->in.no_of_packets);
   1964 		return PARSE_FRAGMENT;
   1965 	}
   1966 
   1967 	session->in.active = FALSE;
   1968 
   1969 	return PARSE_SUCCESS;
   1970 }
   1971 
   1972 static gboolean session_cb(GIOChannel *chan, GIOCondition cond,
   1973 				gpointer data)
   1974 {
   1975 	struct avdtp *session = data;
   1976 	struct avdtp_common_header *header;
   1977 	gsize size;
   1978 
   1979 	DBG("");
   1980 
   1981 	if (cond & G_IO_NVAL)
   1982 		return FALSE;
   1983 
   1984 	header = (void *) session->buf;
   1985 
   1986 	if (cond & (G_IO_HUP | G_IO_ERR))
   1987 		goto failed;
   1988 
   1989 	if (g_io_channel_read(chan, session->buf, session->imtu, &size)
   1990 							!= G_IO_ERROR_NONE) {
   1991 		error("IO Channel read error");
   1992 		goto failed;
   1993 	}
   1994 
   1995 	if (size < sizeof(struct avdtp_common_header)) {
   1996 		error("Received too small packet (%zu bytes)", size);
   1997 		goto failed;
   1998 	}
   1999 
   2000 	switch (avdtp_parse_data(session, session->buf, size)) {
   2001 	case PARSE_ERROR:
   2002 		goto failed;
   2003 	case PARSE_FRAGMENT:
   2004 		return TRUE;
   2005 	case PARSE_SUCCESS:
   2006 		break;
   2007 	}
   2008 
   2009 	if (session->in.message_type == AVDTP_MSG_TYPE_COMMAND) {
   2010 		if (!avdtp_parse_cmd(session, session->in.transaction,
   2011 					session->in.signal_id,
   2012 					session->in.buf,
   2013 					session->in.data_size)) {
   2014 			error("Unable to handle command. Disconnecting");
   2015 			goto failed;
   2016 		}
   2017 
   2018 		if (session->ref == 1 && !session->streams && !session->req)
   2019 			set_disconnect_timer(session);
   2020 
   2021 		if (session->streams && session->dc_timer)
   2022 			remove_disconnect_timer(session);
   2023 
   2024 		return TRUE;
   2025 	}
   2026 
   2027 	if (session->req == NULL) {
   2028 		error("No pending request, ignoring message");
   2029 		return TRUE;
   2030 	}
   2031 
   2032 	if (header->transaction != session->req->transaction) {
   2033 		error("Transaction label doesn't match");
   2034 		return TRUE;
   2035 	}
   2036 
   2037 	if (session->in.signal_id != session->req->signal_id) {
   2038 		error("Reponse signal doesn't match");
   2039 		return TRUE;
   2040 	}
   2041 
   2042 	g_source_remove(session->req->timeout);
   2043 	session->req->timeout = 0;
   2044 
   2045 	switch (header->message_type) {
   2046 	case AVDTP_MSG_TYPE_ACCEPT:
   2047 		if (!avdtp_parse_resp(session, session->req->stream,
   2048 						session->in.transaction,
   2049 						session->in.signal_id,
   2050 						session->in.buf,
   2051 						session->in.data_size)) {
   2052 			error("Unable to parse accept response");
   2053 			goto failed;
   2054 		}
   2055 		break;
   2056 	case AVDTP_MSG_TYPE_REJECT:
   2057 		if (!avdtp_parse_rej(session, session->req->stream,
   2058 						session->in.transaction,
   2059 						session->in.signal_id,
   2060 						session->in.buf,
   2061 						session->in.data_size)) {
   2062 			error("Unable to parse reject response");
   2063 			goto failed;
   2064 		}
   2065 		break;
   2066 	case AVDTP_MSG_TYPE_GEN_REJECT:
   2067 		error("Received a General Reject message");
   2068 		break;
   2069 	default:
   2070 		error("Unknown message type 0x%02X", header->message_type);
   2071 		break;
   2072 	}
   2073 
   2074 	pending_req_free(session->req);
   2075 	session->req = NULL;
   2076 
   2077 	process_queue(session);
   2078 
   2079 	return TRUE;
   2080 
   2081 failed:
   2082 	connection_lost(session, EIO);
   2083 
   2084 	return FALSE;
   2085 }
   2086 
   2087 static struct avdtp *find_session(GSList *list, const bdaddr_t *dst)
   2088 {
   2089 	GSList *l;
   2090 
   2091 	for (l = list; l != NULL; l = g_slist_next(l)) {
   2092 		struct avdtp *s = l->data;
   2093 
   2094 		if (bacmp(dst, &s->dst))
   2095 			continue;
   2096 
   2097 		return s;
   2098 	}
   2099 
   2100 	return NULL;
   2101 }
   2102 
   2103 static uint16_t get_version(struct avdtp *session)
   2104 {
   2105 	struct btd_adapter *adapter;
   2106 	struct btd_device *device;
   2107 	const sdp_record_t *rec;
   2108 	sdp_list_t *protos;
   2109 	sdp_data_t *proto_desc;
   2110 	char addr[18];
   2111 	uint16_t ver = 0x0100;
   2112 
   2113 	adapter = manager_find_adapter(&session->server->src);
   2114 	if (!adapter)
   2115 		goto done;
   2116 
   2117 	ba2str(&session->dst, addr);
   2118 	device = adapter_find_device(adapter, addr);
   2119 	if (!device)
   2120 		goto done;
   2121 
   2122 	rec = btd_device_get_record(device, A2DP_SINK_UUID);
   2123 	if (!rec)
   2124 		rec = btd_device_get_record(device, A2DP_SOURCE_UUID);
   2125 
   2126 	if (!rec)
   2127 		goto done;
   2128 
   2129 	if (sdp_get_access_protos(rec, &protos) < 0)
   2130 		goto done;
   2131 
   2132 	proto_desc = sdp_get_proto_desc(protos, AVDTP_UUID);
   2133 	if (proto_desc && proto_desc->dtd == SDP_UINT16)
   2134 		ver = proto_desc->val.uint16;
   2135 
   2136 	sdp_list_foreach(protos, (sdp_list_func_t) sdp_list_free, NULL);
   2137 	sdp_list_free(protos, NULL);
   2138 
   2139 done:
   2140 	return ver;
   2141 }
   2142 
   2143 static struct avdtp *avdtp_get_internal(const bdaddr_t *src, const bdaddr_t *dst)
   2144 {
   2145 	struct avdtp_server *server;
   2146 	struct avdtp *session;
   2147 
   2148 	assert(src != NULL);
   2149 	assert(dst != NULL);
   2150 
   2151 	server = find_server(servers, src);
   2152 	if (server == NULL)
   2153 		return NULL;
   2154 
   2155 	session = find_session(server->sessions, dst);
   2156 	if (session) {
   2157 		if (session->pending_auth)
   2158 			return NULL;
   2159 		else
   2160 			return session;
   2161 	}
   2162 
   2163 	session = g_new0(struct avdtp, 1);
   2164 
   2165 	session->server = server;
   2166 	bacpy(&session->dst, dst);
   2167 	session->ref = 1;
   2168 	/* We don't use avdtp_set_state() here since this isn't a state change
   2169 	 * but just setting of the initial state */
   2170 	session->state = AVDTP_SESSION_STATE_DISCONNECTED;
   2171 	session->auto_dc = TRUE;
   2172 
   2173 	session->version = get_version(session);
   2174 
   2175 	server->sessions = g_slist_append(server->sessions, session);
   2176 
   2177 	return session;
   2178 }
   2179 
   2180 struct avdtp *avdtp_get(bdaddr_t *src, bdaddr_t *dst)
   2181 {
   2182 	struct avdtp *session;
   2183 
   2184 	session = avdtp_get_internal(src, dst);
   2185 
   2186 	if (!session)
   2187 		return NULL;
   2188 
   2189 	return avdtp_ref(session);
   2190 }
   2191 
   2192 static void avdtp_connect_cb(GIOChannel *chan, GError *err, gpointer user_data)
   2193 {
   2194 	struct avdtp *session = user_data;
   2195 	char address[18];
   2196 	GError *gerr = NULL;
   2197 
   2198 	if (err) {
   2199 		error("%s", err->message);
   2200 		goto failed;
   2201 	}
   2202 
   2203 	if (!session->io)
   2204 		session->io = g_io_channel_ref(chan);
   2205 
   2206 	bt_io_get(chan, BT_IO_L2CAP, &gerr,
   2207 			BT_IO_OPT_OMTU, &session->omtu,
   2208 			BT_IO_OPT_IMTU, &session->imtu,
   2209 			BT_IO_OPT_INVALID);
   2210 	if (gerr) {
   2211 		error("%s", gerr->message);
   2212 		g_error_free(gerr);
   2213 		goto failed;
   2214 	}
   2215 
   2216 	ba2str(&session->dst, address);
   2217 	DBG("AVDTP: connected %s channel to %s",
   2218 			session->pending_open ? "transport" : "signaling",
   2219 			address);
   2220 
   2221 	if (session->state == AVDTP_SESSION_STATE_CONNECTING) {
   2222 		DBG("AVDTP imtu=%u, omtu=%u", session->imtu, session->omtu);
   2223 
   2224 		session->buf = g_malloc0(session->imtu);
   2225 		avdtp_set_state(session, AVDTP_SESSION_STATE_CONNECTED);
   2226 
   2227 		if (session->io_id)
   2228 			g_source_remove(session->io_id);
   2229 
   2230 		/* This watch should be low priority since otherwise the
   2231 		 * connect callback might be dispatched before the session
   2232 		 * callback if the kernel wakes us up at the same time for
   2233 		 * them. This could happen if a headset is very quick in
   2234 		 * sending the Start command after connecting the stream
   2235 		 * transport channel.
   2236 		 */
   2237 		session->io_id = g_io_add_watch_full(chan,
   2238 						G_PRIORITY_LOW,
   2239 						G_IO_IN | G_IO_ERR | G_IO_HUP
   2240 						| G_IO_NVAL,
   2241 						(GIOFunc) session_cb, session,
   2242 						NULL);
   2243 
   2244 		if (session->stream_setup) {
   2245 			set_disconnect_timer(session);
   2246 			avdtp_set_auto_disconnect(session, FALSE);
   2247 		}
   2248 	} else if (session->pending_open)
   2249 		handle_transport_connect(session, chan, session->imtu,
   2250 								session->omtu);
   2251 	else
   2252 		goto failed;
   2253 
   2254 	process_queue(session);
   2255 
   2256 	return;
   2257 
   2258 failed:
   2259 	if (session->pending_open) {
   2260 		struct avdtp_stream *stream = session->pending_open;
   2261 
   2262 		handle_transport_connect(session, NULL, 0, 0);
   2263 
   2264 		if (avdtp_abort(session, stream) < 0)
   2265 			avdtp_sep_set_state(session, stream->lsep,
   2266 						AVDTP_STATE_IDLE);
   2267 	} else
   2268 		connection_lost(session, EIO);
   2269 }
   2270 
   2271 static void auth_cb(DBusError *derr, void *user_data)
   2272 {
   2273 	struct avdtp *session = user_data;
   2274 	GError *err = NULL;
   2275 
   2276 	if (derr && dbus_error_is_set(derr)) {
   2277 		error("Access denied: %s", derr->message);
   2278 		connection_lost(session, EACCES);
   2279 		return;
   2280 	}
   2281 
   2282 	if (!bt_io_accept(session->io, avdtp_connect_cb, session, NULL,
   2283 								&err)) {
   2284 		error("bt_io_accept: %s", err->message);
   2285 		connection_lost(session, EACCES);
   2286 		g_error_free(err);
   2287 		return;
   2288 	}
   2289 
   2290 	/* This is so that avdtp_connect_cb will know to do the right thing
   2291 	 * with respect to the disconnect timer */
   2292 	session->stream_setup = TRUE;
   2293 }
   2294 
   2295 static void avdtp_confirm_cb(GIOChannel *chan, gpointer data)
   2296 {
   2297 	struct avdtp *session;
   2298 	struct audio_device *dev;
   2299 	char address[18];
   2300 	bdaddr_t src, dst;
   2301 	int perr;
   2302 	GError *err = NULL;
   2303 
   2304 	bt_io_get(chan, BT_IO_L2CAP, &err,
   2305 			BT_IO_OPT_SOURCE_BDADDR, &src,
   2306 			BT_IO_OPT_DEST_BDADDR, &dst,
   2307 			BT_IO_OPT_DEST, address,
   2308 			BT_IO_OPT_INVALID);
   2309 	if (err) {
   2310 		error("%s", err->message);
   2311 		g_error_free(err);
   2312 		goto drop;
   2313 	}
   2314 
   2315 	DBG("AVDTP: incoming connect from %s", address);
   2316 
   2317 	session = avdtp_get_internal(&src, &dst);
   2318 	if (!session)
   2319 		goto drop;
   2320 
   2321 	/* This state (ie, session is already *connecting*) happens when the
   2322 	 * device initiates a connect (really a config'd L2CAP channel) even
   2323 	 * though there is a connect we initiated in progress. In sink.c &
   2324 	 * source.c, this state is referred to as XCASE connect:connect.
   2325 	 * Abort the device's channel in favor of our own.
   2326 	 */
   2327 	if (session->state == AVDTP_SESSION_STATE_CONNECTING) {
   2328 		DBG("connect already in progress (XCASE connect:connect)");
   2329 		goto drop;
   2330 	}
   2331 
   2332 	if (session->pending_open && session->pending_open->open_acp) {
   2333 		if (!bt_io_accept(chan, avdtp_connect_cb, session, NULL, NULL))
   2334 			goto drop;
   2335 		return;
   2336 	}
   2337 
   2338 	if (session->io) {
   2339 		error("Refusing unexpected connect from %s", address);
   2340 		goto drop;
   2341 	}
   2342 
   2343 	dev = manager_get_device(&src, &dst, FALSE);
   2344 	if (!dev) {
   2345 		dev = manager_get_device(&src, &dst, TRUE);
   2346 		if (!dev) {
   2347 			error("Unable to get audio device object for %s",
   2348 					address);
   2349 			goto drop;
   2350 		}
   2351 		btd_device_add_uuid(dev->btd_dev, ADVANCED_AUDIO_UUID);
   2352 	}
   2353 
   2354 	session->io = g_io_channel_ref(chan);
   2355 	avdtp_set_state(session, AVDTP_SESSION_STATE_CONNECTING);
   2356 
   2357 	session->io_id = g_io_add_watch(chan, G_IO_ERR | G_IO_HUP | G_IO_NVAL,
   2358 					(GIOFunc) session_cb, session);
   2359 
   2360 	perr = audio_device_request_authorization(dev, ADVANCED_AUDIO_UUID,
   2361 							auth_cb, session);
   2362 	if (perr < 0) {
   2363 		avdtp_unref(session);
   2364 		goto drop;
   2365 	}
   2366 
   2367 	dev->auto_connect = auto_connect;
   2368 
   2369 	return;
   2370 
   2371 drop:
   2372 	g_io_channel_shutdown(chan, TRUE, NULL);
   2373 }
   2374 
   2375 static int l2cap_connect(struct avdtp *session)
   2376 {
   2377 	GError *err = NULL;
   2378 	GIOChannel *io;
   2379 
   2380 	io = bt_io_connect(BT_IO_L2CAP, avdtp_connect_cb, session,
   2381 				NULL, &err,
   2382 				BT_IO_OPT_SOURCE_BDADDR, &session->server->src,
   2383 				BT_IO_OPT_DEST_BDADDR, &session->dst,
   2384 				BT_IO_OPT_PSM, AVDTP_PSM,
   2385 				BT_IO_OPT_INVALID);
   2386 	if (!io) {
   2387 		error("%s", err->message);
   2388 		g_error_free(err);
   2389 		return -EIO;
   2390 	}
   2391 
   2392 	g_io_channel_unref(io);
   2393 
   2394 	return 0;
   2395 }
   2396 
   2397 static void queue_request(struct avdtp *session, struct pending_req *req,
   2398 			gboolean priority)
   2399 {
   2400 	if (priority)
   2401 		session->prio_queue = g_slist_append(session->prio_queue, req);
   2402 	else
   2403 		session->req_queue = g_slist_append(session->req_queue, req);
   2404 }
   2405 
   2406 static uint8_t req_get_seid(struct pending_req *req)
   2407 {
   2408 	if (req->signal_id == AVDTP_DISCOVER)
   2409 		return 0;
   2410 
   2411 	return ((struct seid_req *) (req->data))->acp_seid;
   2412 }
   2413 
   2414 static int cancel_request(struct avdtp *session, int err)
   2415 {
   2416 	struct pending_req *req;
   2417 	struct seid_req sreq;
   2418 	struct avdtp_local_sep *lsep;
   2419 	struct avdtp_stream *stream;
   2420 	uint8_t seid;
   2421 	struct avdtp_error averr;
   2422 
   2423 	req = session->req;
   2424 	session->req = NULL;
   2425 
   2426 	avdtp_error_init(&averr, AVDTP_ERROR_ERRNO, err);
   2427 
   2428 	seid = req_get_seid(req);
   2429 	if (seid)
   2430 		stream = find_stream_by_rseid(session, seid);
   2431 	else
   2432 		stream = NULL;
   2433 
   2434 	if (stream) {
   2435 		stream->abort_int = TRUE;
   2436 		lsep = stream->lsep;
   2437 	} else
   2438 		lsep = NULL;
   2439 
   2440 	switch (req->signal_id) {
   2441 	case AVDTP_RECONFIGURE:
   2442 		error("Reconfigure: %s (%d)", strerror(err), err);
   2443 		if (lsep && lsep->cfm && lsep->cfm->reconfigure)
   2444 			lsep->cfm->reconfigure(session, lsep, stream, &averr,
   2445 						lsep->user_data);
   2446 		break;
   2447 	case AVDTP_OPEN:
   2448 		error("Open: %s (%d)", strerror(err), err);
   2449 		if (lsep && lsep->cfm && lsep->cfm->open)
   2450 			lsep->cfm->open(session, lsep, stream, &averr,
   2451 					lsep->user_data);
   2452 		break;
   2453 	case AVDTP_START:
   2454 		error("Start: %s (%d)", strerror(err), err);
   2455 		if (lsep && lsep->cfm && lsep->cfm->start)
   2456 			lsep->cfm->start(session, lsep, stream, &averr,
   2457 						lsep->user_data);
   2458 		break;
   2459 	case AVDTP_SUSPEND:
   2460 		error("Suspend: %s (%d)", strerror(err), err);
   2461 		if (lsep && lsep->cfm && lsep->cfm->suspend)
   2462 			lsep->cfm->suspend(session, lsep, stream, &averr,
   2463 						lsep->user_data);
   2464 		break;
   2465 	case AVDTP_CLOSE:
   2466 		error("Close: %s (%d)", strerror(err), err);
   2467 		if (lsep && lsep->cfm && lsep->cfm->close) {
   2468 			lsep->cfm->close(session, lsep, stream, &averr,
   2469 						lsep->user_data);
   2470 			if (stream)
   2471 				stream->close_int = FALSE;
   2472 		}
   2473 		break;
   2474 	case AVDTP_SET_CONFIGURATION:
   2475 		error("SetConfiguration: %s (%d)", strerror(err), err);
   2476 		if (lsep && lsep->cfm && lsep->cfm->set_configuration)
   2477 			lsep->cfm->set_configuration(session, lsep, stream,
   2478 							&averr, lsep->user_data);
   2479 		goto failed;
   2480 	case AVDTP_DISCOVER:
   2481 		error("Discover: %s (%d)", strerror(err), err);
   2482 		goto failed;
   2483 	case AVDTP_GET_CAPABILITIES:
   2484 		error("GetCapabilities: %s (%d)", strerror(err), err);
   2485 		goto failed;
   2486 	case AVDTP_ABORT:
   2487 		error("Abort: %s (%d)", strerror(err), err);
   2488 		goto failed;
   2489 	}
   2490 
   2491 	if (!stream)
   2492 		goto failed;
   2493 
   2494 	memset(&sreq, 0, sizeof(sreq));
   2495 	sreq.acp_seid = seid;
   2496 
   2497 	err = send_request(session, TRUE, stream, AVDTP_ABORT, &sreq,
   2498 				sizeof(sreq));
   2499 	if (err < 0) {
   2500 		error("Unable to send abort request");
   2501 		goto failed;
   2502 	}
   2503 
   2504 	goto done;
   2505 
   2506 failed:
   2507 	connection_lost(session, err);
   2508 done:
   2509 	pending_req_free(req);
   2510 	return err;
   2511 }
   2512 
   2513 static gboolean request_timeout(gpointer user_data)
   2514 {
   2515 	struct avdtp *session = user_data;
   2516 
   2517 	cancel_request(session, ETIMEDOUT);
   2518 
   2519 	return FALSE;
   2520 }
   2521 
   2522 static int send_req(struct avdtp *session, gboolean priority,
   2523 			struct pending_req *req)
   2524 {
   2525 	static int transaction = 0;
   2526 	int err;
   2527 
   2528 	if (session->state == AVDTP_SESSION_STATE_DISCONNECTED) {
   2529 		err = l2cap_connect(session);
   2530 		if (err < 0)
   2531 			goto failed;
   2532 		avdtp_set_state(session, AVDTP_SESSION_STATE_CONNECTING);
   2533 	}
   2534 
   2535 	if (session->state < AVDTP_SESSION_STATE_CONNECTED ||
   2536 			session->req != NULL) {
   2537 		queue_request(session, req, priority);
   2538 		return 0;
   2539 	}
   2540 
   2541 	req->transaction = transaction++;
   2542 	transaction %= 16;
   2543 
   2544 	/* FIXME: Should we retry to send if the buffer
   2545 	was not totally sent or in case of EINTR? */
   2546 	if (!avdtp_send(session, req->transaction, AVDTP_MSG_TYPE_COMMAND,
   2547 				req->signal_id, req->data, req->data_size)) {
   2548 		err = -EIO;
   2549 		goto failed;
   2550 	}
   2551 
   2552 
   2553 	session->req = req;
   2554 
   2555 	req->timeout = g_timeout_add_seconds(req->signal_id == AVDTP_ABORT ?
   2556 					ABORT_TIMEOUT : REQ_TIMEOUT,
   2557 					request_timeout,
   2558 					session);
   2559 	return 0;
   2560 
   2561 failed:
   2562 	g_free(req->data);
   2563 	g_free(req);
   2564 	return err;
   2565 }
   2566 
   2567 static int send_request(struct avdtp *session, gboolean priority,
   2568 			struct avdtp_stream *stream, uint8_t signal_id,
   2569 			void *buffer, size_t size)
   2570 {
   2571 	struct pending_req *req;
   2572 
   2573 	if (stream && stream->abort_int && signal_id != AVDTP_ABORT)
   2574 		return -EINVAL;
   2575 
   2576 	req = g_new0(struct pending_req, 1);
   2577 	req->signal_id = signal_id;
   2578 	req->data = g_malloc(size);
   2579 	memcpy(req->data, buffer, size);
   2580 	req->data_size = size;
   2581 	req->stream = stream;
   2582 
   2583 	return send_req(session, priority, req);
   2584 }
   2585 
   2586 static gboolean avdtp_discover_resp(struct avdtp *session,
   2587 					struct discover_resp *resp, int size)
   2588 {
   2589 	int sep_count, i;
   2590 	uint8_t getcap_cmd;
   2591 
   2592 	if (session->version >= 0x0103 && session->server->version >= 0x0103)
   2593 		getcap_cmd = AVDTP_GET_ALL_CAPABILITIES;
   2594 	else
   2595 		getcap_cmd = AVDTP_GET_CAPABILITIES;
   2596 
   2597 	sep_count = size / sizeof(struct seid_info);
   2598 
   2599 	for (i = 0; i < sep_count; i++) {
   2600 		struct avdtp_remote_sep *sep;
   2601 		struct avdtp_stream *stream;
   2602 		struct seid_req req;
   2603 		int ret;
   2604 
   2605 		DBG("seid %d type %d media %d in use %d",
   2606 				resp->seps[i].seid, resp->seps[i].type,
   2607 				resp->seps[i].media_type, resp->seps[i].inuse);
   2608 
   2609 		stream = find_stream_by_rseid(session, resp->seps[i].seid);
   2610 
   2611 		sep = find_remote_sep(session->seps, resp->seps[i].seid);
   2612 		if (!sep) {
   2613 			if (resp->seps[i].inuse && !stream)
   2614 				continue;
   2615 			sep = g_new0(struct avdtp_remote_sep, 1);
   2616 			session->seps = g_slist_append(session->seps, sep);
   2617 		}
   2618 
   2619 		sep->stream = stream;
   2620 		sep->seid = resp->seps[i].seid;
   2621 		sep->type = resp->seps[i].type;
   2622 		sep->media_type = resp->seps[i].media_type;
   2623 
   2624 		memset(&req, 0, sizeof(req));
   2625 		req.acp_seid = sep->seid;
   2626 
   2627 		ret = send_request(session, TRUE, NULL, getcap_cmd,
   2628 							&req, sizeof(req));
   2629 		if (ret < 0) {
   2630 			finalize_discovery(session, -ret);
   2631 			break;
   2632 		}
   2633 	}
   2634 
   2635 	return TRUE;
   2636 }
   2637 
   2638 static gboolean avdtp_get_capabilities_resp(struct avdtp *session,
   2639 						struct getcap_resp *resp,
   2640 						unsigned int size)
   2641 {
   2642 	struct avdtp_remote_sep *sep;
   2643 	uint8_t seid;
   2644 
   2645 	/* Check for minimum required packet size includes:
   2646 	 *   1. getcap resp header
   2647 	 *   2. media transport capability (2 bytes)
   2648 	 *   3. media codec capability type + length (2 bytes)
   2649 	 *   4. the actual media codec elements
   2650 	 * */
   2651 	if (size < (sizeof(struct getcap_resp) + 4 +
   2652 				sizeof(struct avdtp_media_codec_capability))) {
   2653 		error("Too short getcap resp packet");
   2654 		return FALSE;
   2655 	}
   2656 
   2657 	seid = ((struct seid_req *) session->req->data)->acp_seid;
   2658 
   2659 	sep = find_remote_sep(session->seps, seid);
   2660 
   2661 	DBG("seid %d type %d media %d", sep->seid,
   2662 					sep->type, sep->media_type);
   2663 
   2664 	if (sep->caps) {
   2665 		g_slist_foreach(sep->caps, (GFunc) g_free, NULL);
   2666 		g_slist_free(sep->caps);
   2667 		sep->caps = NULL;
   2668 		sep->codec = NULL;
   2669 		sep->delay_reporting = FALSE;
   2670 	}
   2671 
   2672 	sep->caps = caps_to_list(resp->caps, size - sizeof(struct getcap_resp),
   2673 					&sep->codec, &sep->delay_reporting);
   2674 
   2675 	return TRUE;
   2676 }
   2677 
   2678 static gboolean avdtp_set_configuration_resp(struct avdtp *session,
   2679 						struct avdtp_stream *stream,
   2680 						struct avdtp_single_header *resp,
   2681 						int size)
   2682 {
   2683 	struct avdtp_local_sep *sep = stream->lsep;
   2684 
   2685 	if (sep->cfm && sep->cfm->set_configuration)
   2686 		sep->cfm->set_configuration(session, sep, stream, NULL,
   2687 						sep->user_data);
   2688 
   2689 	avdtp_sep_set_state(session, sep, AVDTP_STATE_CONFIGURED);
   2690 
   2691 	return TRUE;
   2692 }
   2693 
   2694 static gboolean avdtp_reconfigure_resp(struct avdtp *session,
   2695 					struct avdtp_stream *stream,
   2696 					struct avdtp_single_header *resp, int size)
   2697 {
   2698 	return TRUE;
   2699 }
   2700 
   2701 static gboolean avdtp_open_resp(struct avdtp *session, struct avdtp_stream *stream,
   2702 				struct seid_rej *resp, int size)
   2703 {
   2704 	struct avdtp_local_sep *sep = stream->lsep;
   2705 
   2706 	if (l2cap_connect(session) < 0) {
   2707 		avdtp_sep_set_state(session, sep, AVDTP_STATE_IDLE);
   2708 		return FALSE;
   2709 	}
   2710 
   2711 	session->pending_open = stream;
   2712 
   2713 	return TRUE;
   2714 }
   2715 
   2716 static gboolean avdtp_start_resp(struct avdtp *session,
   2717 					struct avdtp_stream *stream,
   2718 					struct seid_rej *resp, int size)
   2719 {
   2720 	struct avdtp_local_sep *sep = stream->lsep;
   2721 
   2722 	if (sep->cfm && sep->cfm->start)
   2723 		sep->cfm->start(session, sep, stream, NULL, sep->user_data);
   2724 
   2725 	/* We might be in STREAMING already if both sides send START_CMD at the
   2726 	 * same time and the one in SNK role doesn't reject it as it should */
   2727 	if (sep->state != AVDTP_STATE_STREAMING)
   2728 		avdtp_sep_set_state(session, sep, AVDTP_STATE_STREAMING);
   2729 
   2730 	return TRUE;
   2731 }
   2732 
   2733 static gboolean avdtp_close_resp(struct avdtp *session,
   2734 					struct avdtp_stream *stream,
   2735 					struct seid_rej *resp, int size)
   2736 {
   2737 	struct avdtp_local_sep *sep = stream->lsep;
   2738 
   2739 	avdtp_sep_set_state(session, sep, AVDTP_STATE_CLOSING);
   2740 
   2741 	close_stream(stream);
   2742 
   2743 	return TRUE;
   2744 }
   2745 
   2746 static gboolean avdtp_suspend_resp(struct avdtp *session,
   2747 					struct avdtp_stream *stream,
   2748 					void *data, int size)
   2749 {
   2750 	struct avdtp_local_sep *sep = stream->lsep;
   2751 
   2752 	avdtp_sep_set_state(session, sep, AVDTP_STATE_OPEN);
   2753 
   2754 	if (sep->cfm && sep->cfm->suspend)
   2755 		sep->cfm->suspend(session, sep, stream, NULL, sep->user_data);
   2756 
   2757 	return TRUE;
   2758 }
   2759 
   2760 static gboolean avdtp_abort_resp(struct avdtp *session,
   2761 					struct avdtp_stream *stream,
   2762 					struct seid_rej *resp, int size)
   2763 {
   2764 	struct avdtp_local_sep *sep = stream->lsep;
   2765 
   2766 	avdtp_sep_set_state(session, sep, AVDTP_STATE_ABORTING);
   2767 
   2768 	if (sep->cfm && sep->cfm->abort)
   2769 		sep->cfm->abort(session, sep, stream, NULL, sep->user_data);
   2770 
   2771 	avdtp_sep_set_state(session, sep, AVDTP_STATE_IDLE);
   2772 
   2773 	return TRUE;
   2774 }
   2775 
   2776 static gboolean avdtp_delay_report_resp(struct avdtp *session,
   2777 					struct avdtp_stream *stream,
   2778 					void *data, int size)
   2779 {
   2780 	struct avdtp_local_sep *sep = stream->lsep;
   2781 
   2782 	if (sep->cfm && sep->cfm->delay_report)
   2783 		sep->cfm->delay_report(session, sep, stream, NULL, sep->user_data);
   2784 
   2785 	return TRUE;
   2786 }
   2787 
   2788 static gboolean avdtp_parse_resp(struct avdtp *session,
   2789 					struct avdtp_stream *stream,
   2790 					uint8_t transaction, uint8_t signal_id,
   2791 					void *buf, int size)
   2792 {
   2793 	struct pending_req *next;
   2794 	const char *get_all = "";
   2795 
   2796 	if (session->prio_queue)
   2797 		next = session->prio_queue->data;
   2798 	else if (session->req_queue)
   2799 		next = session->req_queue->data;
   2800 	else
   2801 		next = NULL;
   2802 
   2803 	switch (signal_id) {
   2804 	case AVDTP_DISCOVER:
   2805 		DBG("DISCOVER request succeeded");
   2806 		return avdtp_discover_resp(session, buf, size);
   2807 	case AVDTP_GET_ALL_CAPABILITIES:
   2808 		get_all = "ALL_";
   2809 	case AVDTP_GET_CAPABILITIES:
   2810 		DBG("GET_%sCAPABILITIES request succeeded", get_all);
   2811 		if (!avdtp_get_capabilities_resp(session, buf, size))
   2812 			return FALSE;
   2813 		if (!(next && (next->signal_id == AVDTP_GET_CAPABILITIES ||
   2814 				next->signal_id == AVDTP_GET_ALL_CAPABILITIES)))
   2815 			finalize_discovery(session, 0);
   2816 		return TRUE;
   2817 	}
   2818 
   2819 	/* The remaining commands require an existing stream so bail out
   2820 	 * here if the stream got unexpectedly disconnected */
   2821 	if (!stream) {
   2822 		DBG("AVDTP: stream was closed while waiting for reply");
   2823 		return TRUE;
   2824 	}
   2825 
   2826 	switch (signal_id) {
   2827 	case AVDTP_SET_CONFIGURATION:
   2828 		DBG("SET_CONFIGURATION request succeeded");
   2829 		return avdtp_set_configuration_resp(session, stream,
   2830 								buf, size);
   2831 	case AVDTP_RECONFIGURE:
   2832 		DBG("RECONFIGURE request succeeded");
   2833 		return avdtp_reconfigure_resp(session, stream, buf, size);
   2834 	case AVDTP_OPEN:
   2835 		DBG("OPEN request succeeded");
   2836 		return avdtp_open_resp(session, stream, buf, size);
   2837 	case AVDTP_SUSPEND:
   2838 		DBG("SUSPEND request succeeded");
   2839 		return avdtp_suspend_resp(session, stream, buf, size);
   2840 	case AVDTP_START:
   2841 		DBG("START request succeeded");
   2842 		return avdtp_start_resp(session, stream, buf, size);
   2843 	case AVDTP_CLOSE:
   2844 		DBG("CLOSE request succeeded");
   2845 		return avdtp_close_resp(session, stream, buf, size);
   2846 	case AVDTP_ABORT:
   2847 		DBG("ABORT request succeeded");
   2848 		return avdtp_abort_resp(session, stream, buf, size);
   2849 	case AVDTP_DELAY_REPORT:
   2850 		DBG("DELAY_REPORT request succeeded");
   2851 		return avdtp_delay_report_resp(session, stream, buf, size);
   2852 	}
   2853 
   2854 	error("Unknown signal id in accept response: %u", signal_id);
   2855 	return TRUE;
   2856 }
   2857 
   2858 static gboolean seid_rej_to_err(struct seid_rej *rej, unsigned int size,
   2859 					struct avdtp_error *err)
   2860 {
   2861 	if (size < sizeof(struct seid_rej)) {
   2862 		error("Too small packet for seid_rej");
   2863 		return FALSE;
   2864 	}
   2865 
   2866 	avdtp_error_init(err, AVDTP_ERROR_ERROR_CODE, rej->error);
   2867 
   2868 	return TRUE;
   2869 }
   2870 
   2871 static gboolean conf_rej_to_err(struct conf_rej *rej, unsigned int size,
   2872 				struct avdtp_error *err, uint8_t *category)
   2873 {
   2874 	if (size < sizeof(struct conf_rej)) {
   2875 		error("Too small packet for conf_rej");
   2876 		return FALSE;
   2877 	}
   2878 
   2879 	avdtp_error_init(err, AVDTP_ERROR_ERROR_CODE, rej->error);
   2880 
   2881 	if (category)
   2882 		*category = rej->category;
   2883 
   2884 	return TRUE;
   2885 }
   2886 
   2887 static gboolean stream_rej_to_err(struct stream_rej *rej, unsigned int size,
   2888 					struct avdtp_error *err,
   2889 					uint8_t *acp_seid)
   2890 {
   2891 	if (size < sizeof(struct stream_rej)) {
   2892 		error("Too small packet for stream_rej");
   2893 		return FALSE;
   2894 	}
   2895 
   2896 	avdtp_error_init(err, AVDTP_ERROR_ERROR_CODE, rej->error);
   2897 
   2898 	if (acp_seid)
   2899 		*acp_seid = rej->acp_seid;
   2900 
   2901 	return TRUE;
   2902 }
   2903 
   2904 static gboolean avdtp_parse_rej(struct avdtp *session,
   2905 					struct avdtp_stream *stream,
   2906 					uint8_t transaction, uint8_t signal_id,
   2907 					void *buf, int size)
   2908 {
   2909 	struct avdtp_error err;
   2910 	uint8_t acp_seid, category;
   2911 	struct avdtp_local_sep *sep = stream ? stream->lsep : NULL;
   2912 
   2913 	switch (signal_id) {
   2914 	case AVDTP_DISCOVER:
   2915 		if (!seid_rej_to_err(buf, size, &err))
   2916 			return FALSE;
   2917 		error("DISCOVER request rejected: %s (%d)",
   2918 				avdtp_strerror(&err), err.err.error_code);
   2919 		return TRUE;
   2920 	case AVDTP_GET_CAPABILITIES:
   2921 	case AVDTP_GET_ALL_CAPABILITIES:
   2922 		if (!seid_rej_to_err(buf, size, &err))
   2923 			return FALSE;
   2924 		error("GET_CAPABILITIES request rejected: %s (%d)",
   2925 				avdtp_strerror(&err), err.err.error_code);
   2926 		return TRUE;
   2927 	case AVDTP_OPEN:
   2928 		if (!seid_rej_to_err(buf, size, &err))
   2929 			return FALSE;
   2930 		error("OPEN request rejected: %s (%d)",
   2931 				avdtp_strerror(&err), err.err.error_code);
   2932 		if (sep && sep->cfm && sep->cfm->open)
   2933 			sep->cfm->open(session, sep, stream, &err,
   2934 					sep->user_data);
   2935 		return TRUE;
   2936 	case AVDTP_SET_CONFIGURATION:
   2937 		if (!conf_rej_to_err(buf, size, &err, &category))
   2938 			return FALSE;
   2939 		error("SET_CONFIGURATION request rejected: %s (%d)",
   2940 				avdtp_strerror(&err), err.err.error_code);
   2941 		if (sep && sep->cfm && sep->cfm->set_configuration)
   2942 			sep->cfm->set_configuration(session, sep, stream,
   2943 							&err, sep->user_data);
   2944 		return TRUE;
   2945 	case AVDTP_RECONFIGURE:
   2946 		if (!conf_rej_to_err(buf, size, &err, &category))
   2947 			return FALSE;
   2948 		error("RECONFIGURE request rejected: %s (%d)",
   2949 				avdtp_strerror(&err), err.err.error_code);
   2950 		if (sep && sep->cfm && sep->cfm->reconfigure)
   2951 			sep->cfm->reconfigure(session, sep, stream, &err,
   2952 						sep->user_data);
   2953 		return TRUE;
   2954 	case AVDTP_START:
   2955 		if (!stream_rej_to_err(buf, size, &err, &acp_seid))
   2956 			return FALSE;
   2957 		error("START request rejected: %s (%d)",
   2958 				avdtp_strerror(&err), err.err.error_code);
   2959 		if (sep && sep->cfm && sep->cfm->start)
   2960 			sep->cfm->start(session, sep, stream, &err,
   2961 					sep->user_data);
   2962 		return TRUE;
   2963 	case AVDTP_SUSPEND:
   2964 		if (!stream_rej_to_err(buf, size, &err, &acp_seid))
   2965 			return FALSE;
   2966 		error("SUSPEND request rejected: %s (%d)",
   2967 				avdtp_strerror(&err), err.err.error_code);
   2968 		if (sep && sep->cfm && sep->cfm->suspend)
   2969 			sep->cfm->suspend(session, sep, stream, &err,
   2970 						sep->user_data);
   2971 		return TRUE;
   2972 	case AVDTP_CLOSE:
   2973 		if (!stream_rej_to_err(buf, size, &err, &acp_seid))
   2974 			return FALSE;
   2975 		error("CLOSE request rejected: %s (%d)",
   2976 				avdtp_strerror(&err), err.err.error_code);
   2977 		if (sep && sep->cfm && sep->cfm->close) {
   2978 			sep->cfm->close(session, sep, stream, &err,
   2979 					sep->user_data);
   2980 			stream->close_int = FALSE;
   2981 		}
   2982 		return TRUE;
   2983 	case AVDTP_ABORT:
   2984 		if (!stream_rej_to_err(buf, size, &err, &acp_seid))
   2985 			return FALSE;
   2986 		error("ABORT request rejected: %s (%d)",
   2987 				avdtp_strerror(&err), err.err.error_code);
   2988 		if (sep && sep->cfm && sep->cfm->abort)
   2989 			sep->cfm->abort(session, sep, stream, &err,
   2990 					sep->user_data);
   2991 		return FALSE;
   2992 	case AVDTP_DELAY_REPORT:
   2993 		if (!stream_rej_to_err(buf, size, &err, &acp_seid))
   2994 			return FALSE;
   2995 		error("DELAY_REPORT request rejected: %s (%d)",
   2996 				avdtp_strerror(&err), err.err.error_code);
   2997 		if (sep && sep->cfm && sep->cfm->delay_report)
   2998 			sep->cfm->delay_report(session, sep, stream, &err,
   2999 							sep->user_data);
   3000 		return TRUE;
   3001 	default:
   3002 		error("Unknown reject response signal id: %u", signal_id);
   3003 		return TRUE;
   3004 	}
   3005 }
   3006 
   3007 gboolean avdtp_is_connected(const bdaddr_t *src, const bdaddr_t *dst)
   3008 {
   3009 	struct avdtp_server *server;
   3010 	struct avdtp *session;
   3011 
   3012 	server = find_server(servers, src);
   3013 	if (!server)
   3014 		return FALSE;
   3015 
   3016 	session = find_session(server->sessions, dst);
   3017 	if (!session)
   3018 		return FALSE;
   3019 
   3020 	if (session->state != AVDTP_SESSION_STATE_DISCONNECTED)
   3021 		return TRUE;
   3022 
   3023 	return FALSE;
   3024 }
   3025 
   3026 struct avdtp_service_capability *avdtp_stream_get_codec(
   3027 						struct avdtp_stream *stream)
   3028 {
   3029 	GSList *l;
   3030 
   3031 	for (l = stream->caps; l; l = l->next) {
   3032 		struct avdtp_service_capability *cap = l->data;
   3033 
   3034 		if (cap->category == AVDTP_MEDIA_CODEC)
   3035 			return cap;
   3036 	}
   3037 
   3038 	return NULL;
   3039 }
   3040 
   3041 gboolean avdtp_stream_has_capability(struct avdtp_stream *stream,
   3042 				struct avdtp_service_capability *cap)
   3043 {
   3044 	GSList *l;
   3045 	struct avdtp_service_capability *stream_cap;
   3046 
   3047 	for (l = stream->caps; l; l = g_slist_next(l)) {
   3048 		stream_cap = l->data;
   3049 
   3050 		if (stream_cap->category != cap->category ||
   3051 			stream_cap->length != cap->length)
   3052 			continue;
   3053 
   3054 		if (memcmp(stream_cap->data, cap->data, cap->length) == 0)
   3055 			return TRUE;
   3056 	}
   3057 
   3058 	return FALSE;
   3059 }
   3060 
   3061 gboolean avdtp_stream_has_capabilities(struct avdtp_stream *stream,
   3062 					GSList *caps)
   3063 {
   3064 	GSList *l;
   3065 
   3066 	for (l = caps; l; l = g_slist_next(l)) {
   3067 		struct avdtp_service_capability *cap = l->data;
   3068 
   3069 		if (!avdtp_stream_has_capability(stream, cap))
   3070 			return FALSE;
   3071 	}
   3072 
   3073 	return TRUE;
   3074 }
   3075 
   3076 gboolean avdtp_stream_get_transport(struct avdtp_stream *stream, int *sock,
   3077 					uint16_t *imtu, uint16_t *omtu,
   3078 					GSList **caps)
   3079 {
   3080 	if (stream->io == NULL)
   3081 		return FALSE;
   3082 
   3083 	if (sock)
   3084 		*sock = g_io_channel_unix_get_fd(stream->io);
   3085 
   3086 	if (omtu)
   3087 		*omtu = stream->omtu;
   3088 
   3089 	if (imtu)
   3090 		*imtu = stream->imtu;
   3091 
   3092 	if (caps)
   3093 		*caps = stream->caps;
   3094 
   3095 	return TRUE;
   3096 }
   3097 
   3098 static int process_queue(struct avdtp *session)
   3099 {
   3100 	GSList **queue, *l;
   3101 	struct pending_req *req;
   3102 
   3103 	if (session->req)
   3104 		return 0;
   3105 
   3106 	if (session->prio_queue)
   3107 		queue = &session->prio_queue;
   3108 	else
   3109 		queue = &session->req_queue;
   3110 
   3111 	if (!*queue)
   3112 		return 0;
   3113 
   3114 	l = *queue;
   3115 	req = l->data;
   3116 
   3117 	*queue = g_slist_remove(*queue, req);
   3118 
   3119 	return send_req(session, FALSE, req);
   3120 }
   3121 
   3122 struct avdtp_remote_sep *avdtp_get_remote_sep(struct avdtp *session,
   3123 						uint8_t seid)
   3124 {
   3125 	GSList *l;
   3126 
   3127 	for (l = session->seps; l; l = l->next) {
   3128 		struct avdtp_remote_sep *sep = l->data;
   3129 
   3130 		if (sep->seid == seid)
   3131 			return sep;
   3132 	}
   3133 
   3134 	return NULL;
   3135 }
   3136 
   3137 uint8_t avdtp_get_seid(struct avdtp_remote_sep *sep)
   3138 {
   3139 	return sep->seid;
   3140 }
   3141 
   3142 uint8_t avdtp_get_type(struct avdtp_remote_sep *sep)
   3143 {
   3144 	return sep->type;
   3145 }
   3146 
   3147 struct avdtp_service_capability *avdtp_get_codec(struct avdtp_remote_sep *sep)
   3148 {
   3149 	return sep->codec;
   3150 }
   3151 
   3152 gboolean avdtp_get_delay_reporting(struct avdtp_remote_sep *sep)
   3153 {
   3154 	return sep->delay_reporting;
   3155 }
   3156 
   3157 struct avdtp_stream *avdtp_get_stream(struct avdtp_remote_sep *sep)
   3158 {
   3159 	return sep->stream;
   3160 }
   3161 
   3162 struct avdtp_service_capability *avdtp_service_cap_new(uint8_t category,
   3163 							void *data, int length)
   3164 {
   3165 	struct avdtp_service_capability *cap;
   3166 
   3167 	if (category < AVDTP_MEDIA_TRANSPORT || category > AVDTP_DELAY_REPORTING)
   3168 		return NULL;
   3169 
   3170 	cap = g_malloc(sizeof(struct avdtp_service_capability) + length);
   3171 	cap->category = category;
   3172 	cap->length = length;
   3173 	memcpy(cap->data, data, length);
   3174 
   3175 	return cap;
   3176 }
   3177 
   3178 static gboolean process_discover(gpointer data)
   3179 {
   3180 	struct avdtp *session = data;
   3181 
   3182 	finalize_discovery(session, 0);
   3183 
   3184 	return FALSE;
   3185 }
   3186 
   3187 int avdtp_discover(struct avdtp *session, avdtp_discover_cb_t cb,
   3188 			void *user_data)
   3189 {
   3190 	int err;
   3191 
   3192 	if (session->discov_cb)
   3193 		return -EBUSY;
   3194 
   3195 	if (session->seps) {
   3196 		session->discov_cb = cb;
   3197 		session->user_data = user_data;
   3198 		g_idle_add(process_discover, session);
   3199 		return 0;
   3200 	}
   3201 
   3202 	err = send_request(session, FALSE, NULL, AVDTP_DISCOVER, NULL, 0);
   3203 	if (err == 0) {
   3204 		session->discov_cb = cb;
   3205 		session->user_data = user_data;
   3206 	}
   3207 
   3208 	return err;
   3209 }
   3210 
   3211 int avdtp_get_seps(struct avdtp *session, uint8_t acp_type, uint8_t media_type,
   3212 			uint8_t codec, struct avdtp_local_sep **lsep,
   3213 			struct avdtp_remote_sep **rsep)
   3214 {
   3215 	GSList *l;
   3216 	uint8_t int_type;
   3217 
   3218 	int_type = acp_type == AVDTP_SEP_TYPE_SINK ?
   3219 				AVDTP_SEP_TYPE_SOURCE : AVDTP_SEP_TYPE_SINK;
   3220 
   3221 	*lsep = find_local_sep(session->server, int_type, media_type, codec);
   3222 	if (!*lsep)
   3223 		return -EINVAL;
   3224 
   3225 	for (l = session->seps; l != NULL; l = g_slist_next(l)) {
   3226 		struct avdtp_remote_sep *sep = l->data;
   3227 		struct avdtp_service_capability *cap;
   3228 		struct avdtp_media_codec_capability *codec_data;
   3229 
   3230 		if (sep->type != acp_type)
   3231 			continue;
   3232 
   3233 		if (sep->media_type != media_type)
   3234 			continue;
   3235 
   3236 		if (!sep->codec)
   3237 			continue;
   3238 
   3239 		cap = sep->codec;
   3240 		codec_data = (void *) cap->data;
   3241 
   3242 		if (codec_data->media_codec_type != codec)
   3243 			continue;
   3244 
   3245 		if (!sep->stream) {
   3246 			*rsep = sep;
   3247 			return 0;
   3248 		}
   3249 	}
   3250 
   3251 	return -EINVAL;
   3252 }
   3253 
   3254 gboolean avdtp_stream_remove_cb(struct avdtp *session,
   3255 				struct avdtp_stream *stream,
   3256 				unsigned int id)
   3257 {
   3258 	GSList *l;
   3259 	struct stream_callback *cb;
   3260 
   3261 	if (!stream)
   3262 		return FALSE;
   3263 
   3264 	for (cb = NULL, l = stream->callbacks; l != NULL; l = l->next) {
   3265 		struct stream_callback *tmp = l->data;
   3266 		if (tmp && tmp->id == id) {
   3267 			cb = tmp;
   3268 			break;
   3269 		}
   3270 	}
   3271 
   3272 	if (!cb)
   3273 		return FALSE;
   3274 
   3275 	stream->callbacks = g_slist_remove(stream->callbacks, cb);
   3276 	g_free(cb);
   3277 
   3278 	return TRUE;
   3279 }
   3280 
   3281 unsigned int avdtp_stream_add_cb(struct avdtp *session,
   3282 					struct avdtp_stream *stream,
   3283 					avdtp_stream_state_cb cb, void *data)
   3284 {
   3285 	struct stream_callback *stream_cb;
   3286 	static unsigned int id = 0;
   3287 
   3288 	stream_cb = g_new(struct stream_callback, 1);
   3289 	stream_cb->cb = cb;
   3290 	stream_cb->user_data = data;
   3291 	stream_cb->id = ++id;
   3292 
   3293 	stream->callbacks = g_slist_append(stream->callbacks, stream_cb);;
   3294 
   3295 	return stream_cb->id;
   3296 }
   3297 
   3298 int avdtp_get_configuration(struct avdtp *session, struct avdtp_stream *stream)
   3299 {
   3300 	struct seid_req req;
   3301 
   3302 	if (session->state < AVDTP_SESSION_STATE_CONNECTED)
   3303 		return -EINVAL;
   3304 
   3305 	memset(&req, 0, sizeof(req));
   3306 	req.acp_seid = stream->rseid;
   3307 
   3308 	return send_request(session, FALSE, stream, AVDTP_GET_CONFIGURATION,
   3309 							&req, sizeof(req));
   3310 }
   3311 
   3312 static void copy_capabilities(gpointer data, gpointer user_data)
   3313 {
   3314 	struct avdtp_service_capability *src_cap = data;
   3315 	struct avdtp_service_capability *dst_cap;
   3316 	GSList **l = user_data;
   3317 
   3318 	dst_cap = avdtp_service_cap_new(src_cap->category, src_cap->data,
   3319 					src_cap->length);
   3320 
   3321 	*l = g_slist_append(*l, dst_cap);
   3322 }
   3323 
   3324 int avdtp_set_configuration(struct avdtp *session,
   3325 				struct avdtp_remote_sep *rsep,
   3326 				struct avdtp_local_sep *lsep,
   3327 				GSList *caps,
   3328 				struct avdtp_stream **stream)
   3329 {
   3330 	struct setconf_req *req;
   3331 	struct avdtp_stream *new_stream;
   3332 	unsigned char *ptr;
   3333 	int err, caps_len;
   3334 	struct avdtp_service_capability *cap;
   3335 	GSList *l;
   3336 
   3337 	if (session->state != AVDTP_SESSION_STATE_CONNECTED)
   3338 		return -ENOTCONN;
   3339 
   3340 	if (!(lsep && rsep))
   3341 		return -EINVAL;
   3342 
   3343 	DBG("%p: int_seid=%u, acp_seid=%u", session,
   3344 			lsep->info.seid, rsep->seid);
   3345 
   3346 	new_stream = g_new0(struct avdtp_stream, 1);
   3347 	new_stream->session = session;
   3348 	new_stream->lsep = lsep;
   3349 	new_stream->rseid = rsep->seid;
   3350 
   3351 	if (rsep->delay_reporting && lsep->delay_reporting)
   3352 		new_stream->delay_reporting = TRUE;
   3353 
   3354 	g_slist_foreach(caps, copy_capabilities, &new_stream->caps);
   3355 
   3356 	/* Calculate total size of request */
   3357 	for (l = caps, caps_len = 0; l != NULL; l = g_slist_next(l)) {
   3358 		cap = l->data;
   3359 		caps_len += cap->length + 2;
   3360 	}
   3361 
   3362 	req = g_malloc0(sizeof(struct setconf_req) + caps_len);
   3363 
   3364 	req->int_seid = lsep->info.seid;
   3365 	req->acp_seid = rsep->seid;
   3366 
   3367 	/* Copy the capabilities into the request */
   3368 	for (l = caps, ptr = req->caps; l != NULL; l = g_slist_next(l)) {
   3369 		cap = l->data;
   3370 		memcpy(ptr, cap, cap->length + 2);
   3371 		ptr += cap->length + 2;
   3372 	}
   3373 
   3374 	err = send_request(session, FALSE, new_stream,
   3375 				AVDTP_SET_CONFIGURATION, req,
   3376 				sizeof(struct setconf_req) + caps_len);
   3377 	if (err < 0)
   3378 		stream_free(new_stream);
   3379 	else {
   3380 		lsep->info.inuse = 1;
   3381 		lsep->stream = new_stream;
   3382 		rsep->stream = new_stream;
   3383 		session->streams = g_slist_append(session->streams, new_stream);
   3384 		if (stream)
   3385 			*stream = new_stream;
   3386 	}
   3387 
   3388 	g_free(req);
   3389 
   3390 	return err;
   3391 }
   3392 
   3393 int avdtp_reconfigure(struct avdtp *session, GSList *caps,
   3394 			struct avdtp_stream *stream)
   3395 {
   3396 	struct reconf_req *req;
   3397 	unsigned char *ptr;
   3398 	int caps_len, err;
   3399 	GSList *l;
   3400 	struct avdtp_service_capability *cap;
   3401 
   3402 	if (!g_slist_find(session->streams, stream))
   3403 		return -EINVAL;
   3404 
   3405 	if (stream->lsep->state != AVDTP_STATE_OPEN)
   3406 		return -EINVAL;
   3407 
   3408 	/* Calculate total size of request */
   3409 	for (l = caps, caps_len = 0; l != NULL; l = g_slist_next(l)) {
   3410 		cap = l->data;
   3411 		caps_len += cap->length + 2;
   3412 	}
   3413 
   3414 	req = g_malloc0(sizeof(struct reconf_req) + caps_len);
   3415 
   3416 	req->acp_seid = stream->rseid;
   3417 
   3418 	/* Copy the capabilities into the request */
   3419 	for (l = caps, ptr = req->caps; l != NULL; l = g_slist_next(l)) {
   3420 		cap = l->data;
   3421 		memcpy(ptr, cap, cap->length + 2);
   3422 		ptr += cap->length + 2;
   3423 	}
   3424 
   3425 	err = send_request(session, FALSE, stream, AVDTP_RECONFIGURE, req,
   3426 						sizeof(*req) + caps_len);
   3427 	g_free(req);
   3428 
   3429 	return err;
   3430 }
   3431 
   3432 int avdtp_open(struct avdtp *session, struct avdtp_stream *stream)
   3433 {
   3434 	struct seid_req req;
   3435 
   3436 	if (!g_slist_find(session->streams, stream))
   3437 		return -EINVAL;
   3438 
   3439 	if (stream->lsep->state > AVDTP_STATE_CONFIGURED)
   3440 		return -EINVAL;
   3441 
   3442 	memset(&req, 0, sizeof(req));
   3443 	req.acp_seid = stream->rseid;
   3444 
   3445 	return send_request(session, FALSE, stream, AVDTP_OPEN,
   3446 							&req, sizeof(req));
   3447 }
   3448 
   3449 int avdtp_start(struct avdtp *session, struct avdtp_stream *stream)
   3450 {
   3451 	struct start_req req;
   3452 
   3453 	if (!g_slist_find(session->streams, stream))
   3454 		return -EINVAL;
   3455 
   3456 	if (stream->lsep->state != AVDTP_STATE_OPEN)
   3457 		return -EINVAL;
   3458 
   3459 	if (stream->close_int == TRUE) {
   3460 		error("avdtp_start: rejecting start since close is initiated");
   3461 		return -EINVAL;
   3462 	}
   3463 
   3464 	memset(&req, 0, sizeof(req));
   3465 	req.first_seid.seid = stream->rseid;
   3466 
   3467 	return send_request(session, FALSE, stream, AVDTP_START,
   3468 							&req, sizeof(req));
   3469 }
   3470 
   3471 int avdtp_close(struct avdtp *session, struct avdtp_stream *stream,
   3472 		gboolean immediate)
   3473 {
   3474 	struct seid_req req;
   3475 	int ret;
   3476 
   3477 	if (!g_slist_find(session->streams, stream))
   3478 		return -EINVAL;
   3479 
   3480 	if (stream->lsep->state < AVDTP_STATE_OPEN)
   3481 		return -EINVAL;
   3482 
   3483 	if (stream->close_int == TRUE) {
   3484 		error("avdtp_close: rejecting since close is already initiated");
   3485 		return -EINVAL;
   3486 	}
   3487 
   3488 	if (immediate && session->req && stream == session->req->stream)
   3489 		return avdtp_abort(session, stream);
   3490 
   3491 	memset(&req, 0, sizeof(req));
   3492 	req.acp_seid = stream->rseid;
   3493 
   3494 	ret = send_request(session, FALSE, stream, AVDTP_CLOSE,
   3495 							&req, sizeof(req));
   3496 	if (ret == 0)
   3497 		stream->close_int = TRUE;
   3498 
   3499 	return ret;
   3500 }
   3501 
   3502 int avdtp_suspend(struct avdtp *session, struct avdtp_stream *stream)
   3503 {
   3504 	struct seid_req req;
   3505 
   3506 	if (!g_slist_find(session->streams, stream))
   3507 		return -EINVAL;
   3508 
   3509 	if (stream->lsep->state <= AVDTP_STATE_OPEN || stream->close_int)
   3510 		return -EINVAL;
   3511 
   3512 	memset(&req, 0, sizeof(req));
   3513 	req.acp_seid = stream->rseid;
   3514 
   3515 	return send_request(session, FALSE, stream, AVDTP_SUSPEND,
   3516 							&req, sizeof(req));
   3517 }
   3518 
   3519 int avdtp_abort(struct avdtp *session, struct avdtp_stream *stream)
   3520 {
   3521 	struct seid_req req;
   3522 	int ret;
   3523 
   3524 	if (!g_slist_find(session->streams, stream))
   3525 		return -EINVAL;
   3526 
   3527 	if (stream->lsep->state == AVDTP_STATE_IDLE ||
   3528 			stream->lsep->state == AVDTP_STATE_ABORTING)
   3529 		return -EINVAL;
   3530 
   3531 	if (session->req && stream == session->req->stream)
   3532 		return cancel_request(session, ECANCELED);
   3533 
   3534 	memset(&req, 0, sizeof(req));
   3535 	req.acp_seid = stream->rseid;
   3536 
   3537 	ret = send_request(session, TRUE, stream, AVDTP_ABORT,
   3538 							&req, sizeof(req));
   3539 	if (ret == 0)
   3540 		stream->abort_int = TRUE;
   3541 
   3542 	return ret;
   3543 }
   3544 
   3545 int avdtp_delay_report(struct avdtp *session, struct avdtp_stream *stream,
   3546 							uint16_t delay)
   3547 {
   3548 	struct delay_req req;
   3549 
   3550 	if (!g_slist_find(session->streams, stream))
   3551 		return -EINVAL;
   3552 
   3553 	if (stream->lsep->state != AVDTP_STATE_CONFIGURED &&
   3554 				stream->lsep->state != AVDTP_STATE_STREAMING)
   3555 		return -EINVAL;
   3556 
   3557 	if (!stream->delay_reporting || session->version < 0x0103 ||
   3558 					session->server->version < 0x0103)
   3559 		return -EINVAL;
   3560 
   3561 	stream->delay = delay;
   3562 
   3563 	memset(&req, 0, sizeof(req));
   3564 	req.acp_seid = stream->rseid;
   3565 	req.delay = htons(delay);
   3566 
   3567 	return send_request(session, TRUE, stream, AVDTP_DELAY_REPORT,
   3568 							&req, sizeof(req));
   3569 }
   3570 
   3571 struct avdtp_local_sep *avdtp_register_sep(const bdaddr_t *src, uint8_t type,
   3572 						uint8_t media_type,
   3573 						uint8_t codec_type,
   3574 						gboolean delay_reporting,
   3575 						struct avdtp_sep_ind *ind,
   3576 						struct avdtp_sep_cfm *cfm,
   3577 						void *user_data)
   3578 {
   3579 	struct avdtp_server *server;
   3580 	struct avdtp_local_sep *sep;
   3581 
   3582 	server = find_server(servers, src);
   3583 	if (!server)
   3584 		return NULL;
   3585 
   3586 	if (g_slist_length(server->seps) > MAX_SEID)
   3587 		return NULL;
   3588 
   3589 	sep = g_new0(struct avdtp_local_sep, 1);
   3590 
   3591 	sep->state = AVDTP_STATE_IDLE;
   3592 	sep->info.seid = g_slist_length(server->seps) + 1;
   3593 	sep->info.type = type;
   3594 	sep->info.media_type = media_type;
   3595 	sep->codec = codec_type;
   3596 	sep->ind = ind;
   3597 	sep->cfm = cfm;
   3598 	sep->user_data = user_data;
   3599 	sep->server = server;
   3600 	sep->delay_reporting = TRUE;
   3601 
   3602 	DBG("SEP %p registered: type:%d codec:%d seid:%d", sep,
   3603 			sep->info.type, sep->codec, sep->info.seid);
   3604 	server->seps = g_slist_append(server->seps, sep);
   3605 
   3606 	return sep;
   3607 }
   3608 
   3609 int avdtp_unregister_sep(struct avdtp_local_sep *sep)
   3610 {
   3611 	struct avdtp_server *server;
   3612 
   3613 	if (!sep)
   3614 		return -EINVAL;
   3615 
   3616 	server = sep->server;
   3617 	server->seps = g_slist_remove(server->seps, sep);
   3618 
   3619 	if (sep->stream)
   3620 		release_stream(sep->stream, sep->stream->session);
   3621 
   3622 	g_free(sep);
   3623 
   3624 	return 0;
   3625 }
   3626 
   3627 static GIOChannel *avdtp_server_socket(const bdaddr_t *src, gboolean master)
   3628 {
   3629 	GError *err = NULL;
   3630 	GIOChannel *io;
   3631 
   3632 	io = bt_io_listen(BT_IO_L2CAP, NULL, avdtp_confirm_cb,
   3633 				NULL, NULL, &err,
   3634 				BT_IO_OPT_SOURCE_BDADDR, src,
   3635 				BT_IO_OPT_PSM, AVDTP_PSM,
   3636 				BT_IO_OPT_SEC_LEVEL, BT_IO_SEC_MEDIUM,
   3637 				BT_IO_OPT_MASTER, master,
   3638 				BT_IO_OPT_INVALID);
   3639 	if (!io) {
   3640 		error("%s", err->message);
   3641 		g_error_free(err);
   3642 	}
   3643 
   3644 	return io;
   3645 }
   3646 
   3647 const char *avdtp_strerror(struct avdtp_error *err)
   3648 {
   3649 	if (err->type == AVDTP_ERROR_ERRNO)
   3650 		return strerror(err->err.posix_errno);
   3651 
   3652 	switch(err->err.error_code) {
   3653 	case AVDTP_BAD_HEADER_FORMAT:
   3654 		return "Bad Header Format";
   3655 	case AVDTP_BAD_LENGTH:
   3656 		return "Bad Packet Lenght";
   3657 	case AVDTP_BAD_ACP_SEID:
   3658 		return "Bad Acceptor SEID";
   3659 	case AVDTP_SEP_IN_USE:
   3660 		return "Stream End Point in Use";
   3661 	case AVDTP_SEP_NOT_IN_USE:
   3662 		return "Stream End Point Not in Use";
   3663 	case AVDTP_BAD_SERV_CATEGORY:
   3664 		return "Bad Service Category";
   3665 	case AVDTP_BAD_PAYLOAD_FORMAT:
   3666 		return "Bad Payload format";
   3667 	case AVDTP_NOT_SUPPORTED_COMMAND:
   3668 		return "Command Not Supported";
   3669 	case AVDTP_INVALID_CAPABILITIES:
   3670 		return "Invalid Capabilities";
   3671 	case AVDTP_BAD_RECOVERY_TYPE:
   3672 		return "Bad Recovery Type";
   3673 	case AVDTP_BAD_MEDIA_TRANSPORT_FORMAT:
   3674 		return "Bad Media Transport Format";
   3675 	case AVDTP_BAD_RECOVERY_FORMAT:
   3676 		return "Bad Recovery Format";
   3677 	case AVDTP_BAD_ROHC_FORMAT:
   3678 		return "Bad Header Compression Format";
   3679 	case AVDTP_BAD_CP_FORMAT:
   3680 		return "Bad Content Protetion Format";
   3681 	case AVDTP_BAD_MULTIPLEXING_FORMAT:
   3682 		return "Bad Multiplexing Format";
   3683 	case AVDTP_UNSUPPORTED_CONFIGURATION:
   3684 		return "Configuration not supported";
   3685 	case AVDTP_BAD_STATE:
   3686 		return "Bad State";
   3687 	default:
   3688 		return "Unknow error";
   3689 	}
   3690 }
   3691 
   3692 avdtp_state_t avdtp_sep_get_state(struct avdtp_local_sep *sep)
   3693 {
   3694 	return sep->state;
   3695 }
   3696 
   3697 void avdtp_get_peers(struct avdtp *session, bdaddr_t *src, bdaddr_t *dst)
   3698 {
   3699 	if (src)
   3700 		bacpy(src, &session->server->src);
   3701 	if (dst)
   3702 		bacpy(dst, &session->dst);
   3703 }
   3704 
   3705 int avdtp_init(const bdaddr_t *src, GKeyFile *config, uint16_t *version)
   3706 {
   3707 	GError *err = NULL;
   3708 	gboolean tmp, master = TRUE;
   3709 	struct avdtp_server *server;
   3710 	uint16_t ver = 0x0102;
   3711 
   3712 	if (!config)
   3713 		goto proceed;
   3714 
   3715 	tmp = g_key_file_get_boolean(config, "General",
   3716 			"Master", &err);
   3717 	if (err) {
   3718 		DBG("audio.conf: %s", err->message);
   3719 		g_clear_error(&err);
   3720 	} else
   3721 		master = tmp;
   3722 
   3723 	tmp = g_key_file_get_boolean(config, "General", "AutoConnect",
   3724 			&err);
   3725 	if (err)
   3726 		g_clear_error(&err);
   3727 	else
   3728 		auto_connect = tmp;
   3729 
   3730 	if (g_key_file_get_boolean(config, "A2DP", "DelayReporting", NULL))
   3731 		ver = 0x0103;
   3732 
   3733 proceed:
   3734 	server = g_new0(struct avdtp_server, 1);
   3735 	if (!server)
   3736 		return -ENOMEM;
   3737 
   3738 	server->version = ver;
   3739 
   3740 	if (version)
   3741 		*version = server->version;
   3742 
   3743 	server->io = avdtp_server_socket(src, master);
   3744 	if (!server->io) {
   3745 		g_free(server);
   3746 		return -1;
   3747 	}
   3748 
   3749 	bacpy(&server->src, src);
   3750 
   3751 	servers = g_slist_append(servers, server);
   3752 
   3753 	return 0;
   3754 }
   3755 
   3756 void avdtp_exit(const bdaddr_t *src)
   3757 {
   3758 	struct avdtp_server *server;
   3759 	GSList *l;
   3760 
   3761 	server = find_server(servers, src);
   3762 	if (!server)
   3763 		return;
   3764 
   3765 	for (l = server->sessions; l; l = l->next) {
   3766 		struct avdtp *session = l->data;
   3767 
   3768 		connection_lost(session, -ECONNABORTED);
   3769 	}
   3770 
   3771 	servers = g_slist_remove(servers, server);
   3772 
   3773 	g_io_channel_shutdown(server->io, TRUE, NULL);
   3774 	g_io_channel_unref(server->io);
   3775 	g_free(server);
   3776 }
   3777 
   3778 gboolean avdtp_has_stream(struct avdtp *session, struct avdtp_stream *stream)
   3779 {
   3780 	return g_slist_find(session->streams, stream) ? TRUE : FALSE;
   3781 }
   3782 
   3783 void avdtp_set_auto_disconnect(struct avdtp *session, gboolean auto_dc)
   3784 {
   3785 	session->auto_dc = auto_dc;
   3786 }
   3787 
   3788 gboolean avdtp_stream_setup_active(struct avdtp *session)
   3789 {
   3790 	return session->stream_setup;
   3791 }
   3792 
   3793 unsigned int avdtp_add_state_cb(avdtp_session_state_cb cb, void *user_data)
   3794 {
   3795 	struct avdtp_state_callback *state_cb;
   3796 	static unsigned int id = 0;
   3797 
   3798 	state_cb = g_new(struct avdtp_state_callback, 1);
   3799 	state_cb->cb = cb;
   3800 	state_cb->user_data = user_data;
   3801 	state_cb->id = ++id;
   3802 
   3803 	avdtp_callbacks = g_slist_append(avdtp_callbacks, state_cb);;
   3804 
   3805 	return state_cb->id;
   3806 }
   3807 
   3808 gboolean avdtp_remove_state_cb(unsigned int id)
   3809 {
   3810 	GSList *l;
   3811 
   3812 	for (l = avdtp_callbacks; l != NULL; l = l->next) {
   3813 		struct avdtp_state_callback *cb = l->data;
   3814 		if (cb && cb->id == id) {
   3815 			avdtp_callbacks = g_slist_remove(avdtp_callbacks, cb);
   3816 			g_free(cb);
   3817 			return TRUE;
   3818 		}
   3819 	}
   3820 
   3821 	return FALSE;
   3822 }
   3823