Home | History | Annotate | Download | only in src
      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 #define _GNU_SOURCE
     30 #include <stdio.h>
     31 #include <errno.h>
     32 #include <unistd.h>
     33 #include <stdlib.h>
     34 #include <sys/ioctl.h>
     35 
     36 #include <bluetooth/bluetooth.h>
     37 #include <bluetooth/hci.h>
     38 #include <bluetooth/hci_lib.h>
     39 #include <bluetooth/sdp.h>
     40 #include <bluetooth/sdp_lib.h>
     41 
     42 #include <glib.h>
     43 #include <dbus/dbus.h>
     44 #include <gdbus.h>
     45 
     46 #include "log.h"
     47 #include "textfile.h"
     48 
     49 #include "hcid.h"
     50 #include "sdpd.h"
     51 #include "manager.h"
     52 #include "adapter.h"
     53 #include "device.h"
     54 #include "dbus-common.h"
     55 #include "dbus-hci.h"
     56 #include "error.h"
     57 #include "glib-helper.h"
     58 #include "agent.h"
     59 #include "storage.h"
     60 
     61 #define IO_CAPABILITY_DISPLAYONLY	0x00
     62 #define IO_CAPABILITY_DISPLAYYESNO	0x01
     63 #define IO_CAPABILITY_KEYBOARDONLY	0x02
     64 #define IO_CAPABILITY_NOINPUTNOOUTPUT	0x03
     65 #define IO_CAPABILITY_INVALID		0xFF
     66 
     67 /* Limited Discoverable bit mask in CoD */
     68 #define LIMITED_BIT			0x002000
     69 
     70 #define check_address(address) bachk(address)
     71 
     72 static DBusConnection *connection = NULL;
     73 static GSList *adapter_drivers = NULL;
     74 
     75 const struct btd_adapter_ops *adapter_ops = NULL;
     76 
     77 struct session_req {
     78 	struct btd_adapter	*adapter;
     79 	DBusConnection		*conn;		/* Connection reference */
     80 	DBusMessage		*msg;		/* Unreplied message ref */
     81 	char			*owner;		/* Bus name of the owner */
     82 	guint			id;		/* Listener id */
     83 	uint8_t			mode;		/* Requested mode */
     84 	int			refcount;	/* Session refcount */
     85 };
     86 
     87 struct service_auth {
     88 	service_auth_cb cb;
     89 	void *user_data;
     90 	struct btd_device *device;
     91 	struct btd_adapter *adapter;
     92 };
     93 
     94 struct btd_adapter {
     95 	uint16_t dev_id;
     96 	int up;
     97 	char *path;			/* adapter object path */
     98 	bdaddr_t bdaddr;		/* adapter Bluetooth Address */
     99 	guint discov_timeout_id;	/* discoverable timeout id */
    100 	uint32_t discov_timeout;	/* discoverable time(sec) */
    101 	guint pairable_timeout_id;	/* pairable timeout id */
    102 	uint32_t pairable_timeout;	/* pairable time(sec) */
    103 	uint8_t scan_mode;		/* scan mode: SCAN_DISABLED, SCAN_PAGE,
    104 					 * SCAN_INQUIRY */
    105 	uint8_t mode;			/* off, connectable, discoverable,
    106 					 * limited */
    107 	uint8_t global_mode;		/* last valid global mode */
    108 	struct session_req *pending_mode;
    109 	int state;			/* standard inq, periodic inq, name
    110 					 * resloving */
    111 	GSList *found_devices;
    112 	GSList *oor_devices;		/* out of range device list */
    113 	struct agent *agent;		/* For the new API */
    114 	guint auth_idle_id;		/* Ongoing authorization */
    115 	GSList *connections;		/* Connected devices */
    116 	GSList *devices;		/* Devices structure pointers */
    117 	GSList *mode_sessions;		/* Request Mode sessions */
    118 	GSList *disc_sessions;		/* Discovery sessions */
    119 	guint scheduler_id;		/* Scheduler handle */
    120 	sdp_list_t *services;		/* Services associated to adapter */
    121 
    122 	struct hci_dev dev;		/* hci info */
    123 	int8_t tx_power;		/* inq response tx power level */
    124 	gboolean pairable;		/* pairable state */
    125 
    126 	gboolean initialized;
    127 	gboolean already_up;		/* adapter was already up on init */
    128 
    129 	gboolean off_requested;		/* DEVDOWN ioctl was called */
    130 
    131 	uint32_t current_cod;		/* Adapter's current class */
    132 	uint32_t pending_cod;
    133 	uint32_t wanted_cod;		/* CoD cache */
    134 
    135 	gboolean cache_enable;
    136 
    137 	gint ref;
    138 };
    139 
    140 static void adapter_set_pairable_timeout(struct btd_adapter *adapter,
    141 					guint interval);
    142 
    143 static inline DBusMessage *invalid_args(DBusMessage *msg)
    144 {
    145 	return g_dbus_create_error(msg, ERROR_INTERFACE ".InvalidArguments",
    146 			"Invalid arguments in method call");
    147 }
    148 
    149 static inline DBusMessage *adapter_not_ready(DBusMessage *msg)
    150 {
    151 	return g_dbus_create_error(msg, ERROR_INTERFACE ".NotReady",
    152 			"Adapter is not ready");
    153 }
    154 
    155 static inline DBusMessage *failed_strerror(DBusMessage *msg, int err)
    156 {
    157 	return g_dbus_create_error(msg, ERROR_INTERFACE ".Failed",
    158 							strerror(err));
    159 }
    160 
    161 static inline DBusMessage *not_in_progress(DBusMessage *msg, const char *str)
    162 {
    163 	return g_dbus_create_error(msg, ERROR_INTERFACE ".NotInProgress", str);
    164 }
    165 
    166 static inline DBusMessage *not_authorized(DBusMessage *msg)
    167 {
    168 	return g_dbus_create_error(msg, ERROR_INTERFACE ".NotAuthorized",
    169 			"Not authorized");
    170 }
    171 
    172 static int found_device_cmp(const struct remote_dev_info *d1,
    173 			const struct remote_dev_info *d2)
    174 {
    175 	int ret;
    176 
    177 	if (bacmp(&d2->bdaddr, BDADDR_ANY)) {
    178 		ret = bacmp(&d1->bdaddr, &d2->bdaddr);
    179 		if (ret)
    180 			return ret;
    181 	}
    182 
    183 	if (d2->name_status != NAME_ANY) {
    184 		ret = (d1->name_status - d2->name_status);
    185 		if (ret)
    186 			return ret;
    187 	}
    188 
    189 	return 0;
    190 }
    191 
    192 static void dev_info_free(struct remote_dev_info *dev)
    193 {
    194 	g_free(dev->name);
    195 	g_free(dev->alias);
    196 	g_free(dev);
    197 }
    198 
    199 void clear_found_devices_list(struct btd_adapter *adapter)
    200 {
    201 	if (!adapter->found_devices)
    202 		return;
    203 
    204 	g_slist_foreach(adapter->found_devices, (GFunc) dev_info_free, NULL);
    205 	g_slist_free(adapter->found_devices);
    206 	adapter->found_devices = NULL;
    207 }
    208 
    209 static int adapter_set_service_classes(struct btd_adapter *adapter,
    210 							uint8_t value)
    211 {
    212 	int err;
    213 
    214 	/* Update only the service class, keep the limited bit,
    215 	 * major/minor class bits intact */
    216 	adapter->wanted_cod &= 0x00ffff;
    217 	adapter->wanted_cod |= (value << 16);
    218 
    219 	/* If we already have the CoD we want or the cache is enabled or an
    220 	 * existing CoD write is in progress just bail out */
    221 	if (adapter->current_cod == adapter->wanted_cod ||
    222 			adapter->cache_enable || adapter->pending_cod)
    223 		return 0;
    224 
    225 	DBG("Changing service classes to 0x%06x", adapter->wanted_cod);
    226 
    227 	err = adapter_ops->set_class(adapter->dev_id, adapter->wanted_cod);
    228 	if (err < 0)
    229 		error("Adapter class update failed: %s(%d)",
    230 						strerror(err), err);
    231 	else
    232 		adapter->pending_cod = adapter->wanted_cod;
    233 
    234 	return err;
    235 }
    236 
    237 int btd_adapter_set_class(struct btd_adapter *adapter, uint8_t major,
    238 								uint8_t minor)
    239 {
    240 	int err;
    241 
    242 	/* Update only the major and minor class bits keeping remaining bits
    243 	 * intact*/
    244 	adapter->wanted_cod &= 0xffe000;
    245 	adapter->wanted_cod |= ((major & 0x1f) << 8) | minor;
    246 
    247 	if (adapter->wanted_cod == adapter->current_cod ||
    248 			adapter->cache_enable || adapter->pending_cod)
    249 		return 0;
    250 
    251 	DBG("Changing Major/Minor class to 0x%06x", adapter->wanted_cod);
    252 
    253 	err = adapter_ops->set_class(adapter->dev_id, adapter->wanted_cod);
    254 	if (err < 0)
    255 		error("Adapter class update failed: %s(%d)",
    256 						strerror(err), err);
    257 	else
    258 		adapter->pending_cod = adapter->wanted_cod;
    259 
    260 	return err;
    261 }
    262 
    263 int pending_remote_name_cancel(struct btd_adapter *adapter)
    264 {
    265 	struct remote_dev_info *dev, match;
    266 	int err = 0;
    267 
    268 	/* find the pending remote name request */
    269 	memset(&match, 0, sizeof(struct remote_dev_info));
    270 	bacpy(&match.bdaddr, BDADDR_ANY);
    271 	match.name_status = NAME_REQUESTED;
    272 
    273 	dev = adapter_search_found_devices(adapter, &match);
    274 	if (!dev) /* no pending request */
    275 		return -ENODATA;
    276 
    277 	err = adapter_ops->cancel_resolve_name(adapter->dev_id, &dev->bdaddr);
    278 	if (err < 0)
    279 		error("Remote name cancel failed: %s(%d)",
    280 						strerror(errno), errno);
    281 	return err;
    282 }
    283 
    284 int adapter_resolve_names(struct btd_adapter *adapter)
    285 {
    286 	struct remote_dev_info *dev, match;
    287 	int err;
    288 
    289 	memset(&match, 0, sizeof(struct remote_dev_info));
    290 	bacpy(&match.bdaddr, BDADDR_ANY);
    291 	match.name_status = NAME_REQUIRED;
    292 
    293 	dev = adapter_search_found_devices(adapter, &match);
    294 	if (!dev)
    295 		return -ENODATA;
    296 
    297 	/* send at least one request or return failed if the list is empty */
    298 	do {
    299 		/* flag to indicate the current remote name requested */
    300 		dev->name_status = NAME_REQUESTED;
    301 
    302 		err = adapter_ops->resolve_name(adapter->dev_id, &dev->bdaddr);
    303 
    304 		if (!err)
    305 			break;
    306 
    307 		error("Unable to send HCI remote name req: %s (%d)",
    308 						strerror(errno), errno);
    309 
    310 		/* if failed, request the next element */
    311 		/* remove the element from the list */
    312 		adapter_remove_found_device(adapter, &dev->bdaddr);
    313 
    314 		/* get the next element */
    315 		dev = adapter_search_found_devices(adapter, &match);
    316 	} while (dev);
    317 
    318 	return err;
    319 }
    320 
    321 static const char *mode2str(uint8_t mode)
    322 {
    323 	switch(mode) {
    324 	case MODE_OFF:
    325 		return "off";
    326 	case MODE_CONNECTABLE:
    327 		return "connectable";
    328 	case MODE_DISCOVERABLE:
    329 	case MODE_LIMITED:
    330 		return "discoverable";
    331 	default:
    332 		return "unknown";
    333 	}
    334 }
    335 
    336 static uint8_t get_mode(const bdaddr_t *bdaddr, const char *mode)
    337 {
    338 	if (strcasecmp("off", mode) == 0)
    339 		return MODE_OFF;
    340 	else if (strcasecmp("connectable", mode) == 0)
    341 		return MODE_CONNECTABLE;
    342 	else if (strcasecmp("discoverable", mode) == 0)
    343 		return MODE_DISCOVERABLE;
    344 	else if (strcasecmp("limited", mode) == 0)
    345 		return MODE_LIMITED;
    346 	else if (strcasecmp("on", mode) == 0) {
    347 		char onmode[14], srcaddr[18];
    348 
    349 		ba2str(bdaddr, srcaddr);
    350 		if (read_on_mode(srcaddr, onmode, sizeof(onmode)) < 0)
    351 			return MODE_CONNECTABLE;
    352 
    353 		return get_mode(bdaddr, onmode);
    354 	} else
    355 		return MODE_UNKNOWN;
    356 }
    357 
    358 static void adapter_remove_discov_timeout(struct btd_adapter *adapter)
    359 {
    360 	if (!adapter)
    361 		return;
    362 
    363 	if(adapter->discov_timeout_id == 0)
    364 		return;
    365 
    366 	g_source_remove(adapter->discov_timeout_id);
    367 	adapter->discov_timeout_id = 0;
    368 }
    369 
    370 static gboolean discov_timeout_handler(gpointer user_data)
    371 {
    372 	struct btd_adapter *adapter = user_data;
    373 
    374 	adapter->discov_timeout_id = 0;
    375 
    376 	adapter_ops->set_connectable(adapter->dev_id);
    377 
    378 	return FALSE;
    379 }
    380 
    381 static void adapter_set_discov_timeout(struct btd_adapter *adapter,
    382 					guint interval)
    383 {
    384 	if (adapter->discov_timeout_id) {
    385 		g_source_remove(adapter->discov_timeout_id);
    386 		adapter->discov_timeout_id = 0;
    387 	}
    388 
    389 	if (interval == 0)
    390 		return;
    391 
    392 	adapter->discov_timeout_id = g_timeout_add_seconds(interval,
    393 							discov_timeout_handler,
    394 							adapter);
    395 }
    396 
    397 static void adapter_set_limited_discoverable(struct btd_adapter *adapter,
    398 							gboolean limited)
    399 {
    400 	/* Check if limited bit needs to be set/reset */
    401 	if (limited)
    402 		adapter->wanted_cod |= LIMITED_BIT;
    403 	else
    404 		adapter->wanted_cod &= ~LIMITED_BIT;
    405 
    406 	/* If we dont need the toggling, save an unnecessary CoD write */
    407 	if (adapter->pending_cod ||
    408 			adapter->wanted_cod == adapter->current_cod)
    409 		return;
    410 
    411 	if (adapter_ops->set_limited_discoverable(adapter->dev_id,
    412 					adapter->wanted_cod, limited) == 0)
    413 		adapter->pending_cod = adapter->wanted_cod;
    414 }
    415 
    416 static struct session_req *session_ref(struct session_req *req)
    417 {
    418 	req->refcount++;
    419 
    420 	DBG("%p: ref=%d", req, req->refcount);
    421 
    422 	return req;
    423 }
    424 
    425 static struct session_req *create_session(struct btd_adapter *adapter,
    426 					DBusConnection *conn, DBusMessage *msg,
    427 					uint8_t mode, GDBusWatchFunction cb)
    428 {
    429 	const char *sender = dbus_message_get_sender(msg);
    430 	struct session_req *req;
    431 
    432 	req = g_new0(struct session_req, 1);
    433 	req->adapter = adapter;
    434 	req->conn = dbus_connection_ref(conn);
    435 	req->msg = dbus_message_ref(msg);
    436 	req->mode = mode;
    437 
    438 	if (cb == NULL)
    439 		return session_ref(req);
    440 
    441 	req->owner = g_strdup(sender);
    442 	req->id = g_dbus_add_disconnect_watch(conn, sender, cb, req, NULL);
    443 
    444 	info("%s session %p with %s activated",
    445 		req->mode ? "Mode" : "Discovery", req, sender);
    446 
    447 	return session_ref(req);
    448 }
    449 
    450 static int set_mode(struct btd_adapter *adapter, uint8_t new_mode,
    451 			DBusMessage *msg)
    452 {
    453 	int err;
    454 
    455 	if (adapter->pending_mode != NULL)
    456 		return -EALREADY;
    457 
    458 	if (!adapter->up && new_mode != MODE_OFF) {
    459 		err = adapter_ops->set_powered(adapter->dev_id, TRUE);
    460 		if (err < 0)
    461 			return err;
    462 	}
    463 
    464 	if (adapter->up && new_mode == MODE_OFF) {
    465 		err = adapter_ops->set_powered(adapter->dev_id, FALSE);
    466 		if (err < 0)
    467 			return err;
    468 
    469 		adapter->off_requested = TRUE;
    470 
    471 		goto done;
    472 	}
    473 
    474 	if (new_mode == adapter->mode)
    475 		return 0;
    476 
    477 	if (new_mode == MODE_CONNECTABLE)
    478 		err = adapter_ops->set_connectable(adapter->dev_id);
    479 	else
    480 		err = adapter_ops->set_discoverable(adapter->dev_id);
    481 
    482 	if (err < 0)
    483 		return err;
    484 
    485 	if (new_mode > MODE_CONNECTABLE) {
    486 		adapter_remove_discov_timeout(adapter);
    487 
    488 		if (adapter->discov_timeout)
    489 			adapter_set_discov_timeout(adapter,
    490 						adapter->discov_timeout);
    491 
    492 		if (new_mode != MODE_LIMITED && adapter->mode == MODE_LIMITED)
    493 			adapter_set_limited_discoverable(adapter, FALSE);
    494 	}
    495 
    496 done:
    497 	DBG("%s", mode2str(new_mode));
    498 
    499 	if (msg != NULL)
    500 		/* Wait for mode change to reply */
    501 		adapter->pending_mode = create_session(adapter, connection,
    502 							msg, new_mode, NULL);
    503 	else {
    504 		/* Nothing to reply just write the new mode */
    505 		const char *modestr = mode2str(new_mode);
    506 		adapter->mode = new_mode;
    507 		write_device_mode(&adapter->bdaddr, modestr);
    508 	}
    509 
    510 	return 0;
    511 }
    512 
    513 static DBusMessage *set_powered(DBusConnection *conn, DBusMessage *msg,
    514 				gboolean powered, void *data)
    515 {
    516 	struct btd_adapter *adapter = data;
    517 	uint8_t mode;
    518 	int err;
    519 
    520 	mode = powered ? get_mode(&adapter->bdaddr, "on") : MODE_OFF;
    521 
    522 	if (mode == adapter->mode)
    523 		return dbus_message_new_method_return(msg);
    524 
    525 	err = set_mode(adapter, mode, NULL);
    526 	if (err < 0)
    527 		return failed_strerror(msg, -err);
    528 
    529 	return dbus_message_new_method_return(msg);
    530 }
    531 
    532 static DBusMessage *set_discoverable(DBusConnection *conn, DBusMessage *msg,
    533 				gboolean discoverable, void *data)
    534 {
    535 	struct btd_adapter *adapter = data;
    536 	uint8_t mode;
    537 	int err;
    538 
    539 	mode = discoverable ? MODE_DISCOVERABLE : MODE_CONNECTABLE;
    540 
    541 	if (mode == MODE_DISCOVERABLE && adapter->pairable &&
    542 					adapter->discov_timeout > 0 &&
    543 					adapter->discov_timeout <= 60)
    544 		mode = MODE_LIMITED;
    545 
    546 	if (mode == adapter->mode)
    547 		return dbus_message_new_method_return(msg);
    548 
    549 	err = set_mode(adapter, mode, msg);
    550 	if (err < 0)
    551 		return failed_strerror(msg, -err);
    552 
    553 	return 0;
    554 }
    555 
    556 static DBusMessage *set_pairable(DBusConnection *conn, DBusMessage *msg,
    557 				gboolean pairable, void *data)
    558 {
    559 	struct btd_adapter *adapter = data;
    560 	uint8_t mode;
    561 	int err;
    562 
    563 	if (adapter->scan_mode == SCAN_DISABLED)
    564 		return adapter_not_ready(msg);
    565 
    566 	if (pairable == adapter->pairable)
    567 		goto done;
    568 
    569 	if (!(adapter->scan_mode & SCAN_INQUIRY))
    570 		goto store;
    571 
    572 	mode = (pairable && adapter->discov_timeout > 0 &&
    573 				adapter->discov_timeout <= 60) ?
    574 					MODE_LIMITED : MODE_DISCOVERABLE;
    575 
    576 	err = set_mode(adapter, mode, NULL);
    577 	if (err < 0 && msg)
    578 		return failed_strerror(msg, -err);
    579 
    580 store:
    581 
    582 	adapter->pairable = pairable;
    583 
    584 	write_device_pairable(&adapter->bdaddr, pairable);
    585 
    586 	emit_property_changed(connection, adapter->path,
    587 				ADAPTER_INTERFACE, "Pairable",
    588 				DBUS_TYPE_BOOLEAN, &pairable);
    589 
    590 	if (pairable && adapter->pairable_timeout)
    591 		adapter_set_pairable_timeout(adapter,
    592 						adapter->pairable_timeout);
    593 
    594 done:
    595 	return msg ? dbus_message_new_method_return(msg) : NULL;
    596 }
    597 
    598 static gboolean pairable_timeout_handler(void *data)
    599 {
    600 	set_pairable(NULL, NULL, FALSE, data);
    601 
    602 	return FALSE;
    603 }
    604 
    605 static void adapter_set_pairable_timeout(struct btd_adapter *adapter,
    606 					guint interval)
    607 {
    608 	if (adapter->pairable_timeout_id) {
    609 		g_source_remove(adapter->pairable_timeout_id);
    610 		adapter->pairable_timeout_id = 0;
    611 	}
    612 
    613 	if (interval == 0)
    614 		return;
    615 
    616 	adapter->pairable_timeout_id = g_timeout_add_seconds(interval,
    617 						pairable_timeout_handler,
    618 						adapter);
    619 }
    620 
    621 static struct session_req *find_session(GSList *list, const char *sender)
    622 {
    623 	GSList *l;
    624 
    625 	for (l = list; l; l = l->next) {
    626 		struct session_req *req = l->data;
    627 
    628 		if (g_str_equal(req->owner, sender))
    629 			return req;
    630 	}
    631 
    632 	return NULL;
    633 }
    634 
    635 static uint8_t get_needed_mode(struct btd_adapter *adapter, uint8_t mode)
    636 {
    637 	GSList *l;
    638 
    639 	if (adapter->global_mode > mode)
    640 		mode = adapter->global_mode;
    641 
    642 	for (l = adapter->mode_sessions; l; l = l->next) {
    643 		struct session_req *req = l->data;
    644 
    645 		if (req->mode > mode)
    646 			mode = req->mode;
    647 	}
    648 
    649 	return mode;
    650 }
    651 
    652 static void session_remove(struct session_req *req)
    653 {
    654 	struct btd_adapter *adapter = req->adapter;
    655 
    656 	/* Ignore set_mode session */
    657 	if (req->owner == NULL)
    658 		return;
    659 
    660 	DBG("%s session %p with %s deactivated",
    661 		req->mode ? "Mode" : "Discovery", req, req->owner);
    662 
    663 	if (req->mode) {
    664 		uint8_t mode;
    665 
    666 		adapter->mode_sessions = g_slist_remove(adapter->mode_sessions,
    667 							req);
    668 
    669 		mode = get_needed_mode(adapter, adapter->global_mode);
    670 
    671 		if (mode == adapter->mode)
    672 			return;
    673 
    674 		DBG("Switching to '%s' mode", mode2str(mode));
    675 
    676 		set_mode(adapter, mode, NULL);
    677 	} else {
    678 		adapter->disc_sessions = g_slist_remove(adapter->disc_sessions,
    679 							req);
    680 
    681 		if (adapter->disc_sessions)
    682 			return;
    683 
    684 		DBG("Stopping discovery");
    685 
    686 		pending_remote_name_cancel(adapter);
    687 
    688 		clear_found_devices_list(adapter);
    689 
    690 		g_slist_free(adapter->oor_devices);
    691 		adapter->oor_devices = NULL;
    692 
    693 		if (adapter->scheduler_id) {
    694 			g_source_remove(adapter->scheduler_id);
    695 			adapter->scheduler_id = 0;
    696 		}
    697 
    698 		adapter_ops->stop_discovery(adapter->dev_id);
    699 	}
    700 }
    701 
    702 static void session_free(struct session_req *req)
    703 {
    704 	if (req->id)
    705 		g_dbus_remove_watch(req->conn, req->id);
    706 
    707 	session_remove(req);
    708 
    709 	if (req->msg)
    710 		dbus_message_unref(req->msg);
    711 	if (req->conn)
    712 		dbus_connection_unref(req->conn);
    713 	g_free(req->owner);
    714 	g_free(req);
    715 }
    716 
    717 static void session_owner_exit(DBusConnection *conn, void *user_data)
    718 {
    719 	struct session_req *req = user_data;
    720 
    721 	req->id = 0;
    722 
    723 	session_free(req);
    724 }
    725 
    726 static void session_unref(struct session_req *req)
    727 {
    728 	req->refcount--;
    729 
    730 	DBG("%p: ref=%d", req, req->refcount);
    731 
    732 	if (req->refcount)
    733 		return;
    734 
    735 	session_free(req);
    736 }
    737 
    738 static void confirm_mode_cb(struct agent *agent, DBusError *derr, void *data)
    739 {
    740 	struct session_req *req = data;
    741 	int err;
    742 	DBusMessage *reply;
    743 
    744 	if (derr && dbus_error_is_set(derr)) {
    745 		reply = dbus_message_new_error(req->msg, derr->name,
    746 						derr->message);
    747 		g_dbus_send_message(req->conn, reply);
    748 		session_unref(req);
    749 		return;
    750 	}
    751 
    752 	err = set_mode(req->adapter, req->mode, NULL);
    753 	if (err < 0)
    754 		reply = failed_strerror(req->msg, -err);
    755 	else
    756 		reply = dbus_message_new_method_return(req->msg);
    757 
    758 	g_dbus_send_message(req->conn, reply);
    759 
    760 	dbus_message_unref(req->msg);
    761 	req->msg = NULL;
    762 
    763 	if (!find_session(req->adapter->mode_sessions, req->owner))
    764 		session_unref(req);
    765 }
    766 
    767 static DBusMessage *set_discoverable_timeout(DBusConnection *conn,
    768 							DBusMessage *msg,
    769 							uint32_t timeout,
    770 							void *data)
    771 {
    772 	struct btd_adapter *adapter = data;
    773 	const char *path;
    774 
    775 	if (adapter->discov_timeout == timeout && timeout == 0)
    776 		return dbus_message_new_method_return(msg);
    777 
    778 	if (adapter->scan_mode & SCAN_INQUIRY)
    779 		adapter_set_discov_timeout(adapter, timeout);
    780 
    781 	adapter->discov_timeout = timeout;
    782 
    783 	write_discoverable_timeout(&adapter->bdaddr, timeout);
    784 
    785 	path = dbus_message_get_path(msg);
    786 
    787 	emit_property_changed(conn, path,
    788 				ADAPTER_INTERFACE, "DiscoverableTimeout",
    789 				DBUS_TYPE_UINT32, &timeout);
    790 
    791 	return dbus_message_new_method_return(msg);
    792 }
    793 
    794 static DBusMessage *set_pairable_timeout(DBusConnection *conn,
    795 						DBusMessage *msg,
    796 						uint32_t timeout,
    797 						void *data)
    798 {
    799 	struct btd_adapter *adapter = data;
    800 	const char *path;
    801 
    802 	if (adapter->pairable_timeout == timeout && timeout == 0)
    803 		return dbus_message_new_method_return(msg);
    804 
    805 	if (adapter->pairable)
    806 		adapter_set_pairable_timeout(adapter, timeout);
    807 
    808 	adapter->pairable_timeout = timeout;
    809 
    810 	write_pairable_timeout(&adapter->bdaddr, timeout);
    811 
    812 	path = dbus_message_get_path(msg);
    813 
    814 	emit_property_changed(conn, path,
    815 				ADAPTER_INTERFACE, "PairableTimeout",
    816 				DBUS_TYPE_UINT32, &timeout);
    817 
    818 	return dbus_message_new_method_return(msg);
    819 }
    820 
    821 static void update_ext_inquiry_response(struct btd_adapter *adapter)
    822 {
    823 	uint8_t fec = 0, data[240];
    824 	struct hci_dev *dev = &adapter->dev;
    825 	int dd;
    826 
    827 	if (!(dev->features[6] & LMP_EXT_INQ))
    828 		return;
    829 
    830 	memset(data, 0, sizeof(data));
    831 
    832 	dd = hci_open_dev(adapter->dev_id);
    833 	if (dd < 0)
    834 		return;
    835 
    836 	if (dev->ssp_mode > 0)
    837 		create_ext_inquiry_response((char *) dev->name,
    838 						adapter->tx_power,
    839 						adapter->services, data);
    840 
    841 	if (hci_write_ext_inquiry_response(dd, fec, data,
    842 						HCI_REQ_TIMEOUT) < 0)
    843 		error("Can't write extended inquiry response: %s (%d)",
    844 						strerror(errno), errno);
    845 
    846 	hci_close_dev(dd);
    847 }
    848 
    849 void adapter_set_class_complete(bdaddr_t *bdaddr, uint8_t status)
    850 {
    851 	uint8_t class[3];
    852 	struct btd_adapter *adapter;
    853 	int err;
    854 
    855 	if (status)
    856 		return;
    857 
    858 	adapter = manager_find_adapter(bdaddr);
    859 	if (!adapter) {
    860 		error("Unable to find matching adapter");
    861 		return;
    862 	}
    863 
    864 	if (adapter->pending_cod == 0)
    865 		return;
    866 
    867 	adapter->current_cod = adapter->pending_cod;
    868 	adapter->pending_cod = 0;
    869 
    870 	class[2] = (adapter->current_cod >> 16) & 0xff;
    871 	class[1] = (adapter->current_cod >> 8) & 0xff;
    872 	class[0] = adapter->current_cod & 0xff;
    873 
    874 	write_local_class(&adapter->bdaddr, class);
    875 
    876 	emit_property_changed(connection, adapter->path,
    877 				ADAPTER_INTERFACE, "Class",
    878 				DBUS_TYPE_UINT32, &adapter->current_cod);
    879 
    880 	update_ext_inquiry_response(adapter);
    881 
    882 	if (adapter->wanted_cod == adapter->current_cod)
    883 		return;
    884 
    885 	if (adapter->wanted_cod & LIMITED_BIT &&
    886 			!(adapter->current_cod & LIMITED_BIT))
    887 		err = adapter_ops->set_limited_discoverable(adapter->dev_id,
    888 						adapter->wanted_cod, TRUE);
    889 	else if (!(adapter->wanted_cod & LIMITED_BIT) &&
    890 					adapter->current_cod & LIMITED_BIT)
    891 		err = adapter_ops->set_limited_discoverable(adapter->dev_id,
    892 						adapter->wanted_cod, FALSE);
    893 	else
    894 		err = adapter_ops->set_class(adapter->dev_id,
    895 							adapter->wanted_cod);
    896 
    897 	if (err == 0)
    898 		adapter->pending_cod = adapter->wanted_cod;
    899 }
    900 
    901 void adapter_update_tx_power(bdaddr_t *bdaddr, uint8_t status, void *ptr)
    902 {
    903 	struct btd_adapter *adapter;
    904 
    905 	if (status)
    906 		return;
    907 
    908 	adapter = manager_find_adapter(bdaddr);
    909 	if (!adapter) {
    910 		error("Unable to find matching adapter");
    911 		return;
    912 	}
    913 
    914 	adapter->tx_power = *((int8_t *) ptr);
    915 
    916 	DBG("inquiry respone tx power level is %d", adapter->tx_power);
    917 
    918 	update_ext_inquiry_response(adapter);
    919 }
    920 
    921 void adapter_update_local_name(bdaddr_t *bdaddr, uint8_t status, void *ptr)
    922 {
    923 	read_local_name_rp rp;
    924 	struct hci_dev *dev;
    925 	struct btd_adapter *adapter;
    926 	gchar *name;
    927 
    928 	if (status)
    929 		return;
    930 
    931 	adapter = manager_find_adapter(bdaddr);
    932 	if (!adapter) {
    933 		error("Unable to find matching adapter");
    934 		return;
    935 	}
    936 
    937 	dev = &adapter->dev;
    938 
    939 	memcpy(&rp, ptr, MAX_NAME_LENGTH);
    940 	if (strncmp((char *) rp.name, (char *) dev->name, MAX_NAME_LENGTH) == 0)
    941 		return;
    942 
    943 	strncpy((char *) dev->name, (char *) rp.name, MAX_NAME_LENGTH);
    944 
    945 	write_local_name(bdaddr, (char *) dev->name);
    946 
    947 	update_ext_inquiry_response(adapter);
    948 
    949 	name = g_strdup((char *) dev->name);
    950 
    951 	if (connection)
    952 		emit_property_changed(connection, adapter->path,
    953 					ADAPTER_INTERFACE, "Name",
    954 					DBUS_TYPE_STRING, &name);
    955 	g_free(name);
    956 }
    957 
    958 void adapter_setname_complete(bdaddr_t *local, uint8_t status)
    959 {
    960 	struct btd_adapter *adapter;
    961 	int err;
    962 
    963 	if (status)
    964 		return;
    965 
    966 	adapter = manager_find_adapter(local);
    967 	if (!adapter) {
    968 		error("No matching adapter found");
    969 		return;
    970 	}
    971 
    972 	err = adapter_ops->read_name(adapter->dev_id);
    973 	if (err < 0)
    974 		error("Sending getting name command failed: %s (%d)",
    975 						strerror(errno), errno);
    976 
    977 }
    978 
    979 static DBusMessage *set_name(DBusConnection *conn, DBusMessage *msg,
    980 					const char *name, void *data)
    981 {
    982 	struct btd_adapter *adapter = data;
    983 	struct hci_dev *dev = &adapter->dev;
    984 
    985 	if (!g_utf8_validate(name, -1, NULL)) {
    986 		error("Name change failed: supplied name isn't valid UTF-8");
    987 		return invalid_args(msg);
    988 	}
    989 
    990 	if (strncmp(name, (char *) dev->name, MAX_NAME_LENGTH) == 0)
    991 		goto done;
    992 
    993 	if (!adapter->up) {
    994 		strncpy((char *) adapter->dev.name, name, MAX_NAME_LENGTH);
    995 		write_local_name(&adapter->bdaddr, name);
    996 	} else {
    997 		int err = adapter_ops->set_name(adapter->dev_id, name);
    998 		if (err < 0)
    999 			return failed_strerror(msg, err);
   1000 	}
   1001 
   1002 done:
   1003 	return dbus_message_new_method_return(msg);
   1004 }
   1005 
   1006 struct btd_device *adapter_find_device(struct btd_adapter *adapter,
   1007 							const char *dest)
   1008 {
   1009 	struct btd_device *device;
   1010 	GSList *l;
   1011 
   1012 	if (!adapter)
   1013 		return NULL;
   1014 
   1015 	l = g_slist_find_custom(adapter->devices, dest,
   1016 					(GCompareFunc) device_address_cmp);
   1017 	if (!l)
   1018 		return NULL;
   1019 
   1020 	device = l->data;
   1021 
   1022 	return device;
   1023 }
   1024 
   1025 struct btd_device *adapter_find_connection(struct btd_adapter *adapter,
   1026 						uint16_t handle)
   1027 {
   1028 	GSList *l;
   1029 
   1030 	for (l = adapter->connections; l; l = l->next) {
   1031 		struct btd_device *device = l->data;
   1032 
   1033 		if (device_has_connection(device, handle))
   1034 			return device;
   1035 	}
   1036 
   1037 	return NULL;
   1038 }
   1039 
   1040 static void adapter_update_devices(struct btd_adapter *adapter)
   1041 {
   1042 	char **devices;
   1043 	int i;
   1044 	GSList *l;
   1045 
   1046 	/* Devices */
   1047 	devices = g_new0(char *, g_slist_length(adapter->devices) + 1);
   1048 	for (i = 0, l = adapter->devices; l; l = l->next, i++) {
   1049 		struct btd_device *dev = l->data;
   1050 		devices[i] = (char *) device_get_path(dev);
   1051 	}
   1052 
   1053 	emit_array_property_changed(connection, adapter->path,
   1054 					ADAPTER_INTERFACE, "Devices",
   1055 					DBUS_TYPE_OBJECT_PATH, &devices);
   1056 	g_free(devices);
   1057 }
   1058 
   1059 static void adapter_emit_uuids_updated(struct btd_adapter *adapter)
   1060 {
   1061 	char **uuids;
   1062 	int i;
   1063 	sdp_list_t *list;
   1064 
   1065 	uuids = g_new0(char *, sdp_list_len(adapter->services) + 1);
   1066 
   1067 	for (i = 0, list = adapter->services; list; list = list->next, i++) {
   1068 		sdp_record_t *rec = list->data;
   1069 		uuids[i] = bt_uuid2string(&rec->svclass);
   1070 	}
   1071 
   1072 	emit_array_property_changed(connection, adapter->path,
   1073 			ADAPTER_INTERFACE, "UUIDs", DBUS_TYPE_STRING, &uuids);
   1074 
   1075 	g_strfreev(uuids);
   1076 }
   1077 
   1078 /*
   1079  * adapter_services_inc_rem - Insert or remove UUID from adapter
   1080  */
   1081 static void adapter_service_ins_rem(const bdaddr_t *bdaddr, void *rec,
   1082 							gboolean insert)
   1083 {
   1084 	struct btd_adapter *adapter;
   1085 	GSList *adapters;
   1086 
   1087 	adapters = NULL;
   1088 
   1089 	if (bacmp(bdaddr, BDADDR_ANY) != 0) {
   1090 		/* Only one adapter */
   1091 		adapter = manager_find_adapter(bdaddr);
   1092 		if (!adapter)
   1093 			return;
   1094 
   1095 		adapters = g_slist_append(adapters, adapter);
   1096 	} else
   1097 		/* Emit D-Bus msg to all adapters */
   1098 		adapters = manager_get_adapters();
   1099 
   1100 	for (; adapters; adapters = adapters->next) {
   1101 		adapter = adapters->data;
   1102 
   1103 		if (insert == TRUE)
   1104 			adapter->services = sdp_list_insert_sorted(
   1105 							adapter->services, rec,
   1106 							record_sort);
   1107 		else
   1108 			adapter->services = sdp_list_remove(adapter->services,
   1109 									rec);
   1110 
   1111 		adapter_emit_uuids_updated(adapter);
   1112 	}
   1113 }
   1114 
   1115 void adapter_service_insert(const bdaddr_t *bdaddr, void *rec)
   1116 {
   1117 	/* TRUE to include service*/
   1118 	adapter_service_ins_rem(bdaddr, rec, TRUE);
   1119 }
   1120 
   1121 void adapter_service_remove(const bdaddr_t *bdaddr, void *rec)
   1122 {
   1123 	/* FALSE to remove service*/
   1124 	adapter_service_ins_rem(bdaddr, rec, FALSE);
   1125 }
   1126 
   1127 sdp_list_t *adapter_get_services(struct btd_adapter *adapter)
   1128 {
   1129 	return adapter->services;
   1130 }
   1131 
   1132 struct btd_device *adapter_create_device(DBusConnection *conn,
   1133 						struct btd_adapter *adapter,
   1134 						const char *address)
   1135 {
   1136 	struct btd_device *device;
   1137 	const char *path;
   1138 
   1139 	DBG("%s", address);
   1140 
   1141 	device = device_create(conn, adapter, address);
   1142 	if (!device)
   1143 		return NULL;
   1144 
   1145 	device_set_temporary(device, TRUE);
   1146 
   1147 	adapter->devices = g_slist_append(adapter->devices, device);
   1148 
   1149 	path = device_get_path(device);
   1150 	g_dbus_emit_signal(conn, adapter->path,
   1151 			ADAPTER_INTERFACE, "DeviceCreated",
   1152 			DBUS_TYPE_OBJECT_PATH, &path,
   1153 			DBUS_TYPE_INVALID);
   1154 
   1155 	adapter_update_devices(adapter);
   1156 
   1157 	return device;
   1158 }
   1159 
   1160 void adapter_remove_device(DBusConnection *conn, struct btd_adapter *adapter,
   1161 						struct btd_device *device,
   1162 						gboolean remove_storage)
   1163 {
   1164 	const gchar *dev_path = device_get_path(device);
   1165 	struct agent *agent;
   1166 
   1167 	adapter->devices = g_slist_remove(adapter->devices, device);
   1168 	adapter->connections = g_slist_remove(adapter->connections, device);
   1169 
   1170 	adapter_update_devices(adapter);
   1171 
   1172 	g_dbus_emit_signal(conn, adapter->path,
   1173 			ADAPTER_INTERFACE, "DeviceRemoved",
   1174 			DBUS_TYPE_OBJECT_PATH, &dev_path,
   1175 			DBUS_TYPE_INVALID);
   1176 
   1177 	agent = device_get_agent(device);
   1178 
   1179 	if (agent && device_is_authorizing(device))
   1180 		agent_cancel(agent);
   1181 
   1182 	device_remove(device, remove_storage);
   1183 }
   1184 
   1185 struct btd_device *adapter_get_device(DBusConnection *conn,
   1186 						struct btd_adapter *adapter,
   1187 						const gchar *address)
   1188 {
   1189 	struct btd_device *device;
   1190 
   1191 	DBG("%s", address);
   1192 
   1193 	if (!adapter)
   1194 		return NULL;
   1195 
   1196 	device = adapter_find_device(adapter, address);
   1197 	if (device)
   1198 		return device;
   1199 
   1200 	return adapter_create_device(conn, adapter, address);
   1201 }
   1202 
   1203 static int adapter_start_inquiry(struct btd_adapter *adapter)
   1204 {
   1205 	gboolean periodic = TRUE;
   1206 
   1207 	if (main_opts.discov_interval)
   1208 		periodic = FALSE;
   1209 
   1210 	pending_remote_name_cancel(adapter);
   1211 
   1212 	return adapter_ops->start_discovery(adapter->dev_id, periodic);
   1213 }
   1214 
   1215 static DBusMessage *adapter_start_discovery(DBusConnection *conn,
   1216 						DBusMessage *msg, void *data)
   1217 {
   1218 	struct session_req *req;
   1219 	struct btd_adapter *adapter = data;
   1220 	const char *sender = dbus_message_get_sender(msg);
   1221 	int err;
   1222 
   1223 	if (!adapter->up)
   1224 		return adapter_not_ready(msg);
   1225 
   1226 	req = find_session(adapter->disc_sessions, sender);
   1227 	if (req) {
   1228 		session_ref(req);
   1229 		return dbus_message_new_method_return(msg);
   1230 	}
   1231 
   1232 	if (adapter->disc_sessions)
   1233 		goto done;
   1234 
   1235 	if (main_opts.name_resolv)
   1236 		adapter->state |= RESOLVE_NAME;
   1237 
   1238 	err = adapter_start_inquiry(adapter);
   1239 	if (err < 0)
   1240 		return failed_strerror(msg, -err);
   1241 
   1242 done:
   1243 	req = create_session(adapter, conn, msg, 0,
   1244 				session_owner_exit);
   1245 
   1246 	adapter->disc_sessions = g_slist_append(adapter->disc_sessions, req);
   1247 
   1248 	return dbus_message_new_method_return(msg);
   1249 }
   1250 
   1251 static DBusMessage *adapter_stop_discovery(DBusConnection *conn,
   1252 						DBusMessage *msg, void *data)
   1253 {
   1254 	struct btd_adapter *adapter = data;
   1255 	struct session_req *req;
   1256 	const char *sender = dbus_message_get_sender(msg);
   1257 
   1258 	if (!adapter->up)
   1259 		return adapter_not_ready(msg);
   1260 
   1261 	req = find_session(adapter->disc_sessions, sender);
   1262 	if (!req)
   1263 		return g_dbus_create_error(msg, ERROR_INTERFACE ".Failed",
   1264 				"Invalid discovery session");
   1265 
   1266 	session_unref(req);
   1267 	info("Stopping discovery");
   1268 	return dbus_message_new_method_return(msg);
   1269 }
   1270 
   1271 struct remote_device_list_t {
   1272 	GSList *list;
   1273 	time_t time;
   1274 };
   1275 
   1276 static DBusMessage *get_properties(DBusConnection *conn,
   1277 					DBusMessage *msg, void *data)
   1278 {
   1279 	struct btd_adapter *adapter = data;
   1280 	const char *property;
   1281 	DBusMessage *reply;
   1282 	DBusMessageIter iter;
   1283 	DBusMessageIter dict;
   1284 	char str[MAX_NAME_LENGTH + 1], srcaddr[18];
   1285 	gboolean value;
   1286 	char **devices, **uuids;
   1287 	int i;
   1288 	GSList *l;
   1289 	sdp_list_t *list;
   1290 
   1291 	ba2str(&adapter->bdaddr, srcaddr);
   1292 
   1293 	if (check_address(srcaddr) < 0)
   1294 		return adapter_not_ready(msg);
   1295 
   1296 	reply = dbus_message_new_method_return(msg);
   1297 	if (!reply)
   1298 		return NULL;
   1299 
   1300 	dbus_message_iter_init_append(reply, &iter);
   1301 
   1302 	dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
   1303 			DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
   1304 			DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
   1305 			DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict);
   1306 
   1307 	/* Address */
   1308 	property = srcaddr;
   1309 	dict_append_entry(&dict, "Address", DBUS_TYPE_STRING, &property);
   1310 
   1311 	/* Name */
   1312 	memset(str, 0, sizeof(str));
   1313 	strncpy(str, (char *) adapter->dev.name, MAX_NAME_LENGTH);
   1314 	property = str;
   1315 
   1316 	dict_append_entry(&dict, "Name", DBUS_TYPE_STRING, &property);
   1317 
   1318 	/* Class */
   1319 	dict_append_entry(&dict, "Class",
   1320 				DBUS_TYPE_UINT32, &adapter->current_cod);
   1321 
   1322 	/* Powered */
   1323 	value = (adapter->up && !adapter->off_requested) ? TRUE : FALSE;
   1324 	dict_append_entry(&dict, "Powered", DBUS_TYPE_BOOLEAN, &value);
   1325 
   1326 	/* Discoverable */
   1327 	value = adapter->scan_mode & SCAN_INQUIRY ? TRUE : FALSE;
   1328 	dict_append_entry(&dict, "Discoverable", DBUS_TYPE_BOOLEAN, &value);
   1329 
   1330 	/* Pairable */
   1331 	dict_append_entry(&dict, "Pairable", DBUS_TYPE_BOOLEAN,
   1332 				&adapter->pairable);
   1333 
   1334 	/* DiscoverableTimeout */
   1335 	dict_append_entry(&dict, "DiscoverableTimeout",
   1336 				DBUS_TYPE_UINT32, &adapter->discov_timeout);
   1337 
   1338 	/* PairableTimeout */
   1339 	dict_append_entry(&dict, "PairableTimeout",
   1340 				DBUS_TYPE_UINT32, &adapter->pairable_timeout);
   1341 
   1342 
   1343 	if (adapter->state & PERIODIC_INQUIRY || adapter->state & STD_INQUIRY)
   1344 		value = TRUE;
   1345 	else
   1346 		value = FALSE;
   1347 
   1348 	/* Discovering */
   1349 	dict_append_entry(&dict, "Discovering", DBUS_TYPE_BOOLEAN, &value);
   1350 
   1351 	/* Devices */
   1352 	devices = g_new0(char *, g_slist_length(adapter->devices) + 1);
   1353 	for (i = 0, l = adapter->devices; l; l = l->next, i++) {
   1354 		struct btd_device *dev = l->data;
   1355 		devices[i] = (char *) device_get_path(dev);
   1356 	}
   1357 	dict_append_array(&dict, "Devices", DBUS_TYPE_OBJECT_PATH,
   1358 								&devices, i);
   1359 	g_free(devices);
   1360 
   1361 	/* UUIDs */
   1362 	uuids = g_new0(char *, sdp_list_len(adapter->services) + 1);
   1363 
   1364 	for (i = 0, list = adapter->services; list; list = list->next, i++) {
   1365 		sdp_record_t *rec = list->data;
   1366 		uuids[i] = bt_uuid2string(&rec->svclass);
   1367 	}
   1368 
   1369 	dict_append_array(&dict, "UUIDs", DBUS_TYPE_STRING, &uuids, i);
   1370 
   1371 	g_strfreev(uuids);
   1372 
   1373 	dbus_message_iter_close_container(&iter, &dict);
   1374 
   1375 	return reply;
   1376 }
   1377 
   1378 static DBusMessage *set_property(DBusConnection *conn,
   1379 					DBusMessage *msg, void *data)
   1380 {
   1381 	struct btd_adapter *adapter = data;
   1382 	DBusMessageIter iter;
   1383 	DBusMessageIter sub;
   1384 	const char *property;
   1385 	char srcaddr[18];
   1386 
   1387 	ba2str(&adapter->bdaddr, srcaddr);
   1388 
   1389 	if (!dbus_message_iter_init(msg, &iter))
   1390 		return invalid_args(msg);
   1391 
   1392 	if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
   1393 		return invalid_args(msg);
   1394 
   1395 	dbus_message_iter_get_basic(&iter, &property);
   1396 	dbus_message_iter_next(&iter);
   1397 
   1398 	if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
   1399 		return invalid_args(msg);
   1400 	dbus_message_iter_recurse(&iter, &sub);
   1401 
   1402 	if (g_str_equal("Name", property)) {
   1403 		const char *name;
   1404 
   1405 		if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)
   1406 			return invalid_args(msg);
   1407 		dbus_message_iter_get_basic(&sub, &name);
   1408 
   1409 		return set_name(conn, msg, name, data);
   1410 	} else if (g_str_equal("Powered", property)) {
   1411 		gboolean powered;
   1412 
   1413 		if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
   1414 			return invalid_args(msg);
   1415 
   1416 		dbus_message_iter_get_basic(&sub, &powered);
   1417 
   1418 		return set_powered(conn, msg, powered, data);
   1419 	} else if (g_str_equal("Discoverable", property)) {
   1420 		gboolean discoverable;
   1421 
   1422 		if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
   1423 			return invalid_args(msg);
   1424 
   1425 		dbus_message_iter_get_basic(&sub, &discoverable);
   1426 
   1427 		return set_discoverable(conn, msg, discoverable, data);
   1428 	} else if (g_str_equal("DiscoverableTimeout", property)) {
   1429 		uint32_t timeout;
   1430 
   1431 		if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32)
   1432 			return invalid_args(msg);
   1433 
   1434 		dbus_message_iter_get_basic(&sub, &timeout);
   1435 
   1436 		return set_discoverable_timeout(conn, msg, timeout, data);
   1437 	} else if (g_str_equal("Pairable", property)) {
   1438 		gboolean pairable;
   1439 
   1440 		if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
   1441 			return invalid_args(msg);
   1442 
   1443 		dbus_message_iter_get_basic(&sub, &pairable);
   1444 
   1445 		return set_pairable(conn, msg, pairable, data);
   1446 	} else if (g_str_equal("PairableTimeout", property)) {
   1447 		uint32_t timeout;
   1448 
   1449 		if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32)
   1450 			return invalid_args(msg);
   1451 
   1452 		dbus_message_iter_get_basic(&sub, &timeout);
   1453 
   1454 		return set_pairable_timeout(conn, msg, timeout, data);
   1455 	}
   1456 
   1457 	return invalid_args(msg);
   1458 }
   1459 
   1460 static DBusMessage *request_session(DBusConnection *conn,
   1461 					DBusMessage *msg, void *data)
   1462 {
   1463 	struct btd_adapter *adapter = data;
   1464 	struct session_req *req;
   1465 	const char *sender = dbus_message_get_sender(msg);
   1466 	uint8_t new_mode;
   1467 	int err;
   1468 
   1469 	if (!adapter->agent)
   1470 		return g_dbus_create_error(msg, ERROR_INTERFACE ".Failed",
   1471 						"No agent registered");
   1472 
   1473 	if (!adapter->mode_sessions)
   1474 		adapter->global_mode = adapter->mode;
   1475 
   1476 	new_mode = get_mode(&adapter->bdaddr, "on");
   1477 
   1478 	req = find_session(adapter->mode_sessions, sender);
   1479 	if (req) {
   1480 		session_ref(req);
   1481 		return dbus_message_new_method_return(msg);
   1482 	} else {
   1483 		req = create_session(adapter, conn, msg, new_mode,
   1484 					session_owner_exit);
   1485 		adapter->mode_sessions = g_slist_append(adapter->mode_sessions,
   1486 							req);
   1487 	}
   1488 
   1489 	/* No need to change mode */
   1490 	if (adapter->mode >= new_mode)
   1491 		return dbus_message_new_method_return(msg);
   1492 
   1493 	err = agent_confirm_mode_change(adapter->agent, mode2str(new_mode),
   1494 					confirm_mode_cb, req, NULL);
   1495 	if (err < 0) {
   1496 		session_unref(req);
   1497 		return failed_strerror(msg, -err);
   1498 	}
   1499 
   1500 	return NULL;
   1501 }
   1502 
   1503 static DBusMessage *release_session(DBusConnection *conn,
   1504 					DBusMessage *msg, void *data)
   1505 {
   1506 	struct btd_adapter *adapter = data;
   1507 	struct session_req *req;
   1508 	const char *sender = dbus_message_get_sender(msg);
   1509 
   1510 	req = find_session(adapter->mode_sessions, sender);
   1511 	if (!req)
   1512 		return g_dbus_create_error(msg, ERROR_INTERFACE ".Failed",
   1513 				"No Mode to release");
   1514 
   1515 	session_unref(req);
   1516 
   1517 	return dbus_message_new_method_return(msg);
   1518 }
   1519 
   1520 static DBusMessage *list_devices(DBusConnection *conn,
   1521 						DBusMessage *msg, void *data)
   1522 {
   1523 	struct btd_adapter *adapter = data;
   1524 	DBusMessage *reply;
   1525 	GSList *l;
   1526 	DBusMessageIter iter;
   1527 	DBusMessageIter array_iter;
   1528 	const gchar *dev_path;
   1529 
   1530 	if (!dbus_message_has_signature(msg, DBUS_TYPE_INVALID_AS_STRING))
   1531 		return invalid_args(msg);
   1532 
   1533 	reply = dbus_message_new_method_return(msg);
   1534 	if (!reply)
   1535 		return NULL;
   1536 
   1537 	dbus_message_iter_init_append(reply, &iter);
   1538 	dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
   1539 				DBUS_TYPE_OBJECT_PATH_AS_STRING, &array_iter);
   1540 
   1541 	for (l = adapter->devices; l; l = l->next) {
   1542 		struct btd_device *device = l->data;
   1543 
   1544 		dev_path = device_get_path(device);
   1545 
   1546 		dbus_message_iter_append_basic(&array_iter,
   1547 				DBUS_TYPE_OBJECT_PATH, &dev_path);
   1548 	}
   1549 
   1550 	dbus_message_iter_close_container(&iter, &array_iter);
   1551 
   1552 	return reply;
   1553 }
   1554 
   1555 static DBusMessage *cancel_device_creation(DBusConnection *conn,
   1556 						DBusMessage *msg, void *data)
   1557 {
   1558 	struct btd_adapter *adapter = data;
   1559 	const gchar *address, *sender = dbus_message_get_sender(msg);
   1560 	struct btd_device *device;
   1561 
   1562 	if (dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &address,
   1563 						DBUS_TYPE_INVALID) == FALSE)
   1564 		return invalid_args(msg);
   1565 
   1566 	if (check_address(address) < 0)
   1567 		return invalid_args(msg);
   1568 
   1569 	device = adapter_find_device(adapter, address);
   1570 	if (!device || !device_is_creating(device, NULL))
   1571 		return not_in_progress(msg, "Device creation not in progress");
   1572 
   1573 	if (!device_is_creating(device, sender))
   1574 		return not_authorized(msg);
   1575 
   1576 	device_set_temporary(device, TRUE);
   1577 
   1578 	if (device_is_connected(device)) {
   1579 		device_request_disconnect(device, msg);
   1580 		return NULL;
   1581 	}
   1582 
   1583 	adapter_remove_device(conn, adapter, device, TRUE);
   1584 
   1585 	return dbus_message_new_method_return(msg);
   1586 }
   1587 
   1588 static DBusMessage *create_device(DBusConnection *conn,
   1589 					DBusMessage *msg, void *data)
   1590 {
   1591 	struct btd_adapter *adapter = data;
   1592 	struct btd_device *device;
   1593 	const gchar *address;
   1594 
   1595 	if (dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &address,
   1596 						DBUS_TYPE_INVALID) == FALSE)
   1597 		return invalid_args(msg);
   1598 
   1599 	if (check_address(address) < 0)
   1600 		return invalid_args(msg);
   1601 
   1602 	if (adapter_find_device(adapter, address))
   1603 		return g_dbus_create_error(msg,
   1604 				ERROR_INTERFACE ".AlreadyExists",
   1605 				"Device already exists");
   1606 
   1607 	DBG("%s", address);
   1608 
   1609 	device = adapter_create_device(conn, adapter, address);
   1610 	if (!device)
   1611 		return NULL;
   1612 
   1613 	device_browse(device, conn, msg, NULL, FALSE);
   1614 
   1615 	return NULL;
   1616 }
   1617 
   1618 static uint8_t parse_io_capability(const char *capability)
   1619 {
   1620 	if (g_str_equal(capability, ""))
   1621 		return IO_CAPABILITY_DISPLAYYESNO;
   1622 	if (g_str_equal(capability, "DisplayOnly"))
   1623 		return IO_CAPABILITY_DISPLAYONLY;
   1624 	if (g_str_equal(capability, "DisplayYesNo"))
   1625 		return IO_CAPABILITY_DISPLAYYESNO;
   1626 	if (g_str_equal(capability, "KeyboardOnly"))
   1627 		return IO_CAPABILITY_KEYBOARDONLY;
   1628 	if (g_str_equal(capability, "NoInputNoOutput"))
   1629 		return IO_CAPABILITY_NOINPUTNOOUTPUT;
   1630 	return IO_CAPABILITY_INVALID;
   1631 }
   1632 
   1633 static DBusMessage *create_paired_device_generic(DBusConnection *conn,
   1634 						DBusMessage *msg, void *data, const gboolean oob)
   1635 {
   1636 	struct btd_adapter *adapter = data;
   1637 	struct btd_device *device;
   1638 	const gchar *address, *agent_path, *capability, *sender;
   1639 	uint8_t cap;
   1640 
   1641 	if (dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &address,
   1642 					DBUS_TYPE_OBJECT_PATH, &agent_path,
   1643 					DBUS_TYPE_STRING, &capability,
   1644 					DBUS_TYPE_INVALID) == FALSE)
   1645 		return invalid_args(msg);
   1646 
   1647 	if (check_address(address) < 0)
   1648 		return invalid_args(msg);
   1649 
   1650 	sender = dbus_message_get_sender(msg);
   1651 	if (adapter->agent &&
   1652 			agent_matches(adapter->agent, sender, agent_path)) {
   1653 		error("Refusing adapter agent usage as device specific one");
   1654 		return invalid_args(msg);
   1655 	}
   1656 
   1657 	cap = parse_io_capability(capability);
   1658 	if (cap == IO_CAPABILITY_INVALID)
   1659 		return invalid_args(msg);
   1660 
   1661 	device = adapter_get_device(conn, adapter, address);
   1662 	if (!device)
   1663 		return g_dbus_create_error(msg,
   1664 				ERROR_INTERFACE ".Failed",
   1665 				"Unable to create a new device object");
   1666 
   1667 	return device_create_bonding(device, conn, msg, agent_path, cap, oob);
   1668 }
   1669 
   1670 static DBusMessage *create_paired_device_oob(DBusConnection *conn,
   1671 					DBusMessage *msg, void *data)
   1672 {
   1673 	return create_paired_device_generic(conn, msg, data, TRUE);
   1674 }
   1675 
   1676 static DBusMessage *create_paired_device(DBusConnection *conn,
   1677 					DBusMessage *msg, void *data)
   1678 {
   1679 	return create_paired_device_generic(conn, msg, data, FALSE);
   1680 }
   1681 
   1682 static gint device_path_cmp(struct btd_device *device, const gchar *path)
   1683 {
   1684 	const gchar *dev_path = device_get_path(device);
   1685 
   1686 	return strcasecmp(dev_path, path);
   1687 }
   1688 
   1689 static DBusMessage *remove_device(DBusConnection *conn, DBusMessage *msg,
   1690 								void *data)
   1691 {
   1692 	struct btd_adapter *adapter = data;
   1693 	struct btd_device *device;
   1694 	const char *path;
   1695 	GSList *l;
   1696 
   1697 	if (dbus_message_get_args(msg, NULL, DBUS_TYPE_OBJECT_PATH, &path,
   1698 						DBUS_TYPE_INVALID) == FALSE)
   1699 		return invalid_args(msg);
   1700 
   1701 	l = g_slist_find_custom(adapter->devices,
   1702 			path, (GCompareFunc) device_path_cmp);
   1703 	if (!l)
   1704 		return g_dbus_create_error(msg,
   1705 				ERROR_INTERFACE ".DoesNotExist",
   1706 				"Device does not exist");
   1707 	device = l->data;
   1708 
   1709 	if (device_is_temporary(device) || device_is_busy(device))
   1710 		return g_dbus_create_error(msg,
   1711 				ERROR_INTERFACE ".DoesNotExist",
   1712 				"Device creation in progress");
   1713 
   1714 	device_set_temporary(device, TRUE);
   1715 
   1716 	if (!device_is_connected(device)) {
   1717 		adapter_remove_device(conn, adapter, device, TRUE);
   1718 		return dbus_message_new_method_return(msg);
   1719 	}
   1720 
   1721 	device_request_disconnect(device, msg);
   1722 	return NULL;
   1723 }
   1724 
   1725 static DBusMessage *find_device(DBusConnection *conn, DBusMessage *msg,
   1726 								void *data)
   1727 {
   1728 	struct btd_adapter *adapter = data;
   1729 	struct btd_device *device;
   1730 	DBusMessage *reply;
   1731 	const gchar *address;
   1732 	GSList *l;
   1733 	const gchar *dev_path;
   1734 
   1735 	if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &address,
   1736 						DBUS_TYPE_INVALID))
   1737 		return invalid_args(msg);
   1738 
   1739 	l = g_slist_find_custom(adapter->devices,
   1740 			address, (GCompareFunc) device_address_cmp);
   1741 	if (!l)
   1742 		return g_dbus_create_error(msg,
   1743 				ERROR_INTERFACE ".DoesNotExist",
   1744 				"Device does not exist");
   1745 
   1746 	device = l->data;
   1747 
   1748 	reply = dbus_message_new_method_return(msg);
   1749 	if (!reply)
   1750 		return NULL;
   1751 
   1752 	dev_path = device_get_path(device);
   1753 
   1754 	dbus_message_append_args(reply,
   1755 				DBUS_TYPE_OBJECT_PATH, &dev_path,
   1756 				DBUS_TYPE_INVALID);
   1757 
   1758 	return reply;
   1759 }
   1760 
   1761 static void agent_removed(struct agent *agent, struct btd_adapter *adapter)
   1762 {
   1763 	adapter->agent = NULL;
   1764 }
   1765 
   1766 
   1767 static DBusMessage *register_agent_generic(DBusConnection *conn, DBusMessage *msg,
   1768 					void *data, const char *path, const char *capability,
   1769 					const gboolean oob)
   1770 {
   1771 	const char *name;
   1772 	struct agent *agent;
   1773 	struct btd_adapter *adapter = data;
   1774 	uint8_t cap;
   1775 
   1776 	if (adapter->agent)
   1777 		return g_dbus_create_error(msg,
   1778 				ERROR_INTERFACE ".AlreadyExists",
   1779 				"Agent already exists");
   1780 
   1781 	cap = parse_io_capability(capability);
   1782 	if (cap == IO_CAPABILITY_INVALID)
   1783 		return invalid_args(msg);
   1784 
   1785 	name = dbus_message_get_sender(msg);
   1786 
   1787 	agent = agent_create(adapter, name, path, cap, oob,
   1788 				(agent_remove_cb) agent_removed, adapter);
   1789 	if (!agent)
   1790 		return g_dbus_create_error(msg,
   1791 				ERROR_INTERFACE ".Failed",
   1792 				"Failed to create a new agent");
   1793 
   1794 	adapter->agent = agent;
   1795 
   1796 	DBG("Agent registered for hci%d at %s:%s", adapter->dev_id, name,
   1797 			path);
   1798 
   1799 	return dbus_message_new_method_return(msg);
   1800 }
   1801 
   1802 static DBusMessage *register_agent_oob(DBusConnection *conn, DBusMessage *msg,
   1803 					 void *data)
   1804 {
   1805 	const char *path, *capability;
   1806 	gboolean oob;
   1807 
   1808 	if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_OBJECT_PATH, &path,
   1809 					DBUS_TYPE_STRING, &capability,
   1810 					DBUS_TYPE_BOOLEAN, &oob, DBUS_TYPE_INVALID))
   1811 		return NULL;
   1812 
   1813 	return register_agent_generic(conn, msg, data, path, capability, oob);
   1814 }
   1815 
   1816 static DBusMessage *register_agent(DBusConnection *conn, DBusMessage *msg,
   1817 					 void *data)
   1818 {
   1819 	const char *path, *capability;
   1820 
   1821 	if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_OBJECT_PATH, &path,
   1822 					DBUS_TYPE_STRING, &capability, DBUS_TYPE_INVALID))
   1823 		return NULL;
   1824 
   1825 	return register_agent_generic(conn, msg, data, path, capability, FALSE);
   1826 }
   1827 
   1828 static DBusMessage *unregister_agent(DBusConnection *conn, DBusMessage *msg,
   1829 								void *data)
   1830 {
   1831 	const char *path, *name;
   1832 	struct btd_adapter *adapter = data;
   1833 
   1834 	if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_OBJECT_PATH, &path,
   1835 						DBUS_TYPE_INVALID))
   1836 		return NULL;
   1837 
   1838 	name = dbus_message_get_sender(msg);
   1839 
   1840 	if (!adapter->agent || !agent_matches(adapter->agent, name, path))
   1841 		return g_dbus_create_error(msg,
   1842 					ERROR_INTERFACE ".DoesNotExist",
   1843 					"No such agent");
   1844 
   1845 	agent_free(adapter->agent);
   1846 	adapter->agent = NULL;
   1847 
   1848 	return dbus_message_new_method_return(msg);
   1849 }
   1850 
   1851 static sdp_record_t *create_rfcomm_record(struct btd_adapter *adapter,
   1852 					const char *name, uuid_t uuid, uint8_t channel)
   1853 {
   1854 	uuid_t root_uuid, l2cap_uuid, rfcomm_uuid;
   1855 	sdp_list_t *svclass, *root, *proto;
   1856 	sdp_record_t *record;
   1857 
   1858 	record = sdp_record_alloc();
   1859 	if (!record)
   1860 		return NULL;
   1861 
   1862 	sdp_uuid16_create(&root_uuid, PUBLIC_BROWSE_GROUP);
   1863 	root = sdp_list_append(NULL, &root_uuid);
   1864 	sdp_set_browse_groups(record, root);
   1865 
   1866 	sdp_uuid16_create(&l2cap_uuid, L2CAP_UUID);
   1867 	proto = sdp_list_append(NULL, sdp_list_append(NULL, &l2cap_uuid));
   1868 
   1869 	sdp_uuid16_create(&rfcomm_uuid, RFCOMM_UUID);
   1870 	proto = sdp_list_append(proto, sdp_list_append(
   1871 			sdp_list_append(NULL, &rfcomm_uuid),
   1872 			sdp_data_alloc(SDP_UINT8, &channel)));
   1873 
   1874 	sdp_set_access_protos(record, sdp_list_append(NULL, proto));
   1875 
   1876 	svclass = sdp_list_append(NULL, &uuid);
   1877 	sdp_set_service_classes(record, svclass);
   1878 
   1879 	sdp_set_info_attr(record, name, NULL, NULL);
   1880 
   1881 	return record;
   1882 }
   1883 
   1884 static DBusMessage *add_rfcomm_service_record(DBusConnection *conn,
   1885 					DBusMessage *msg, void *data)
   1886 {
   1887 	uuid_t uuid;
   1888 	const char *name;
   1889 	uint8_t channel;
   1890 	uint32_t *uuid_p;
   1891 	uint32_t uuid_net[4];   // network order
   1892 	uint64_t uuid_host[2];  // host
   1893 	sdp_record_t *record;
   1894 	struct btd_adapter *adapter = data;
   1895 
   1896 	DBusMessage *reply;
   1897 
   1898 	if (!dbus_message_get_args(msg, NULL,
   1899 			DBUS_TYPE_STRING, &name,
   1900 			DBUS_TYPE_UINT64, &uuid_host[0],
   1901 			DBUS_TYPE_UINT64, &uuid_host[1],
   1902 			DBUS_TYPE_UINT16, &channel,
   1903 			DBUS_TYPE_INVALID))
   1904 		return invalid_args(msg);
   1905 
   1906 	uuid_p = (uint32_t *)uuid_host;
   1907 	uuid_net[1] = htonl(*uuid_p++);
   1908 	uuid_net[0] = htonl(*uuid_p++);
   1909 	uuid_net[3] = htonl(*uuid_p++);
   1910 	uuid_net[2] = htonl(*uuid_p++);
   1911 
   1912 	sdp_uuid128_create(&uuid, (void *)uuid_net);
   1913 
   1914 	record = create_rfcomm_record(adapter, name, uuid, channel);
   1915 
   1916 	if (!record)
   1917 		return g_dbus_create_error(msg,
   1918 				ERROR_INTERFACE ".Failed",
   1919 				"Failed to create sdp record");
   1920 
   1921 	if (add_record_to_server(&adapter->bdaddr, record))
   1922 		return g_dbus_create_error(msg,
   1923 				ERROR_INTERFACE ".Failed",
   1924 				"Failed to register sdp record");
   1925 
   1926 	reply = dbus_message_new_method_return(msg);
   1927 	dbus_message_append_args(reply,
   1928 			DBUS_TYPE_UINT32, &record->handle,
   1929 			DBUS_TYPE_INVALID);
   1930 
   1931 	return reply;
   1932 }
   1933 
   1934 static DBusMessage *remove_service_record(DBusConnection *conn,
   1935 					DBusMessage *msg, void *data)
   1936 {
   1937 	struct btd_adapter *adapter = data;
   1938 	dbus_uint32_t handle;
   1939 
   1940 	if (!dbus_message_get_args(msg, NULL,
   1941 			DBUS_TYPE_UINT32, &handle,
   1942 			DBUS_TYPE_INVALID))
   1943 		return invalid_args(msg);
   1944 
   1945 	if (remove_record_from_server(handle))
   1946 		return g_dbus_create_error(msg,
   1947 				ERROR_INTERFACE ".Failed",
   1948 				"Failed to remove sdp record");
   1949 
   1950 	return dbus_message_new_method_return(msg);
   1951 }
   1952 
   1953 static DBusMessage *read_local_oob_data(DBusConnection *conn,
   1954 					DBusMessage *msg, void *data)
   1955 {
   1956 	struct btd_adapter *adapter = data;
   1957 	DBusMessage *reply;
   1958 
   1959 	uint8_t hash[16], randomizer[16];
   1960 	uint8_t *hash_ptr = hash;
   1961 	uint8_t *r_ptr = randomizer;
   1962 	int dd, err;
   1963 
   1964 	dd = hci_open_dev(adapter->dev_id);
   1965 
   1966 	if (dd < 0) {
   1967 		err = -errno;
   1968 		goto fail;
   1969 	}
   1970 
   1971 	err = hci_read_local_oob_data(dd, hash, randomizer, HCI_REQ_TIMEOUT);
   1972 
   1973 	hci_close_dev(dd);
   1974 
   1975 	if (err < 0) {
   1976 		err = -errno;
   1977 		goto fail;
   1978 	}
   1979 
   1980 	reply = dbus_message_new_method_return(msg);
   1981 	dbus_message_append_args(reply,
   1982 				DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &hash_ptr, 16,
   1983 				DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &r_ptr, 16,
   1984 				DBUS_TYPE_INVALID);
   1985 
   1986 	return reply;
   1987 fail:
   1988 	return failed_strerror(msg, errno);
   1989 }
   1990 
   1991 static DBusMessage *set_link_timeout(DBusConnection *conn,
   1992 					DBusMessage *msg, void *data)
   1993 {
   1994 	struct btd_adapter *adapter = data;
   1995         struct btd_device *device;
   1996 	const char *path;
   1997 	GSList *l;
   1998 	uint32_t num_slots;
   1999         int dd, err;
   2000 
   2001 	if (!dbus_message_get_args(msg, NULL,
   2002 			DBUS_TYPE_OBJECT_PATH, &path,
   2003 			DBUS_TYPE_UINT32, &num_slots,
   2004 			DBUS_TYPE_INVALID))
   2005 		return invalid_args(msg);
   2006 
   2007         l = g_slist_find_custom(adapter->devices,
   2008                         path, (GCompareFunc) device_path_cmp);
   2009         if (!l)
   2010                 return g_dbus_create_error(msg,
   2011                                 ERROR_INTERFACE ".DoesNotExist",
   2012                                 "Device does not exist");
   2013 	device = l->data;
   2014 	dd = hci_open_dev(adapter->dev_id);
   2015 
   2016 	if (dd < 0) {
   2017 		err = -errno;
   2018 		goto fail;
   2019 	}
   2020 
   2021 	err = hci_write_link_supervision_timeout(dd,
   2022 			htobs(device_get_handle(device)), htobs(num_slots), 1000);
   2023 	hci_close_dev(dd);
   2024 
   2025 	if (err < 0) {
   2026 		err = -errno;
   2027 		goto fail;
   2028 	}
   2029 	return dbus_message_new_method_return(msg);
   2030 fail:
   2031 	return failed_strerror(msg, errno);
   2032 }
   2033 
   2034 static GDBusMethodTable adapter_methods[] = {
   2035 	{ "GetProperties",	"",	"a{sv}",get_properties		},
   2036 	{ "SetProperty",	"sv",	"",	set_property,
   2037 						G_DBUS_METHOD_FLAG_ASYNC},
   2038 	{ "RequestSession",	"",	"",	request_session,
   2039 						G_DBUS_METHOD_FLAG_ASYNC},
   2040 	{ "ReleaseSession",	"",	"",	release_session		},
   2041 	{ "StartDiscovery",	"",	"",	adapter_start_discovery },
   2042 	{ "StopDiscovery",	"",	"",	adapter_stop_discovery,
   2043 						G_DBUS_METHOD_FLAG_ASYNC},
   2044 	{ "ListDevices",	"",	"ao",	list_devices,
   2045 						G_DBUS_METHOD_FLAG_DEPRECATED},
   2046 	{ "CreateDevice",	"s",	"o",	create_device,
   2047 						G_DBUS_METHOD_FLAG_ASYNC},
   2048 	{ "CreatePairedDevice",	"sos",	"o",	create_paired_device,
   2049 						G_DBUS_METHOD_FLAG_ASYNC},
   2050 	{ "CreatePairedDeviceOutOfBand",	"sos",	"o",	create_paired_device_oob,
   2051 						G_DBUS_METHOD_FLAG_ASYNC},
   2052 	{ "CancelDeviceCreation","s",	"",	cancel_device_creation,
   2053 						G_DBUS_METHOD_FLAG_ASYNC},
   2054 	{ "RemoveDevice",	"o",	"",	remove_device,
   2055 						G_DBUS_METHOD_FLAG_ASYNC},
   2056 	{ "FindDevice",		"s",	"o",	find_device		},
   2057 	{ "ReadLocalOutOfBandData", "", "ayay",	read_local_oob_data},
   2058 	{ "RegisterAgent",	"os",	"",	register_agent		},
   2059 	{ "RegisterAgent",	"osb",	"",	register_agent_oob	},
   2060 	{ "UnregisterAgent",	"o",	"",	unregister_agent	},
   2061 	{ "AddRfcommServiceRecord",	"sttq",	"u",	add_rfcomm_service_record },
   2062 	{ "RemoveServiceRecord",	"u",	"",	remove_service_record },
   2063 	{ "SetLinkTimeout",	"ou",	"",	set_link_timeout	},
   2064 	{ }
   2065 };
   2066 
   2067 static GDBusSignalTable adapter_signals[] = {
   2068 	{ "PropertyChanged",		"sv"		},
   2069 	{ "DeviceCreated",		"o"		},
   2070 	{ "DeviceRemoved",		"o"		},
   2071 	{ "DeviceFound",		"sa{sv}"	},
   2072 	{ "DeviceDisappeared",		"s"		},
   2073 	{ }
   2074 };
   2075 
   2076 static inline uint8_t get_inquiry_mode(struct hci_dev *dev)
   2077 {
   2078 	if (dev->features[6] & LMP_EXT_INQ)
   2079 		return 2;
   2080 
   2081 	if (dev->features[3] & LMP_RSSI_INQ)
   2082 		return 1;
   2083 
   2084 	if (dev->manufacturer == 11 &&
   2085 			dev->hci_rev == 0x00 && dev->lmp_subver == 0x0757)
   2086 		return 1;
   2087 
   2088 	if (dev->manufacturer == 15) {
   2089 		if (dev->hci_rev == 0x03 && dev->lmp_subver == 0x6963)
   2090 			return 1;
   2091 		if (dev->hci_rev == 0x09 && dev->lmp_subver == 0x6963)
   2092 			return 1;
   2093 		if (dev->hci_rev == 0x00 && dev->lmp_subver == 0x6965)
   2094 			return 1;
   2095 	}
   2096 
   2097 	if (dev->manufacturer == 31 &&
   2098 			dev->hci_rev == 0x2005 && dev->lmp_subver == 0x1805)
   2099 		return 1;
   2100 
   2101 	return 0;
   2102 }
   2103 
   2104 static int adapter_read_bdaddr(uint16_t dev_id, bdaddr_t *bdaddr)
   2105 {
   2106 	int dd, err;
   2107 
   2108 	dd = hci_open_dev(dev_id);
   2109 	if (dd < 0) {
   2110 		err = -errno;
   2111 		error("Can't open device hci%d: %s (%d)",
   2112 					dev_id, strerror(errno), errno);
   2113 		return err;
   2114 	}
   2115 
   2116 	if (hci_read_bd_addr(dd, bdaddr, HCI_REQ_TIMEOUT) < 0) {
   2117 		err = -errno;
   2118 		error("Can't read address for hci%d: %s (%d)",
   2119 					dev_id, strerror(errno), errno);
   2120 		hci_close_dev(dd);
   2121 		return err;
   2122 	}
   2123 
   2124 	hci_close_dev(dd);
   2125 
   2126 	return 0;
   2127 }
   2128 
   2129 static int adapter_setup(struct btd_adapter *adapter, const char *mode)
   2130 {
   2131 	struct hci_dev *dev = &adapter->dev;
   2132 	uint8_t events[8] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00, 0x00 };
   2133 	uint8_t inqmode;
   2134 	int err , dd;
   2135 	char name[MAX_NAME_LENGTH + 1];
   2136 	uint8_t cls[3];
   2137 
   2138 	dd = hci_open_dev(adapter->dev_id);
   2139 	if (dd < 0) {
   2140 		err = -errno;
   2141 		error("Can't open device hci%d: %s (%d)", adapter->dev_id,
   2142 						strerror(errno), errno);
   2143 		return err;
   2144 	}
   2145 
   2146 	if (dev->lmp_ver > 1) {
   2147 		if (dev->features[5] & LMP_SNIFF_SUBR)
   2148 			events[5] |= 0x20;
   2149 
   2150 		if (dev->features[5] & LMP_PAUSE_ENC)
   2151 			events[5] |= 0x80;
   2152 
   2153 		if (dev->features[6] & LMP_EXT_INQ)
   2154 			events[5] |= 0x40;
   2155 
   2156 		if (dev->features[6] & LMP_NFLUSH_PKTS)
   2157 			events[7] |= 0x01;
   2158 
   2159 		if (dev->features[7] & LMP_LSTO)
   2160 			events[6] |= 0x80;
   2161 
   2162 		if (dev->features[6] & LMP_SIMPLE_PAIR) {
   2163 			events[6] |= 0x01;	/* IO Capability Request */
   2164 			events[6] |= 0x02;	/* IO Capability Response */
   2165 			events[6] |= 0x04;	/* User Confirmation Request */
   2166 			events[6] |= 0x08;	/* User Passkey Request */
   2167 			events[6] |= 0x10;	/* Remote OOB Data Request */
   2168 			events[6] |= 0x20;	/* Simple Pairing Complete */
   2169 			events[7] |= 0x04;	/* User Passkey Notification */
   2170 			events[7] |= 0x08;	/* Keypress Notification */
   2171 			events[7] |= 0x10;	/* Remote Host Supported
   2172 						 * Features Notification */
   2173 		}
   2174 
   2175 		hci_send_cmd(dd, OGF_HOST_CTL, OCF_SET_EVENT_MASK,
   2176 						sizeof(events), events);
   2177 	}
   2178 
   2179 	inqmode = get_inquiry_mode(dev);
   2180 	if (inqmode < 1)
   2181 		goto done;
   2182 
   2183 	if (hci_write_inquiry_mode(dd, inqmode, HCI_REQ_TIMEOUT) < 0) {
   2184 		err = -errno;
   2185 		error("Can't write inquiry mode for %s: %s (%d)",
   2186 					adapter->path, strerror(errno), errno);
   2187 		hci_close_dev(dd);
   2188 		return err;
   2189 	}
   2190 
   2191 	if (dev->features[7] & LMP_INQ_TX_PWR)
   2192 		hci_send_cmd(dd, OGF_HOST_CTL,
   2193 				OCF_READ_INQ_RESPONSE_TX_POWER_LEVEL, 0, NULL);
   2194 
   2195 	if (read_local_name(&adapter->bdaddr, name) < 0)
   2196 		expand_name(name, MAX_NAME_LENGTH, main_opts.name,
   2197 							adapter->dev_id);
   2198 
   2199 	adapter_ops->set_name(adapter->dev_id, name);
   2200 	if (g_str_equal(mode, "off"))
   2201 		strncpy((char *) adapter->dev.name, name, MAX_NAME_LENGTH);
   2202 
   2203 	/* Set device class */
   2204 	if (adapter->initialized && adapter->wanted_cod) {
   2205 		cls[1] = (adapter->wanted_cod >> 8) & 0xff;
   2206 		cls[0] = adapter->wanted_cod & 0xff;
   2207 	} else if (read_local_class(&adapter->bdaddr, cls) < 0) {
   2208 		uint32_t class = htobl(main_opts.class);
   2209 		if (class)
   2210 			memcpy(cls, &class, 3);
   2211 		else
   2212 			goto done;
   2213 	}
   2214 
   2215 	btd_adapter_set_class(adapter, cls[1], cls[0]);
   2216 done:
   2217 	hci_close_dev(dd);
   2218 	return 0;
   2219 }
   2220 
   2221 static void create_stored_device_from_profiles(char *key, char *value,
   2222 						void *user_data)
   2223 {
   2224 	struct btd_adapter *adapter = user_data;
   2225 	GSList *uuids = bt_string2list(value);
   2226 	struct btd_device *device;
   2227 
   2228 	if (g_slist_find_custom(adapter->devices,
   2229 				key, (GCompareFunc) device_address_cmp))
   2230 		return;
   2231 
   2232 	device = device_create(connection, adapter, key);
   2233 	if (!device)
   2234 		return;
   2235 
   2236 	device_set_temporary(device, FALSE);
   2237 	adapter->devices = g_slist_append(adapter->devices, device);
   2238 
   2239 	device_probe_drivers(device, uuids);
   2240 
   2241 	g_slist_foreach(uuids, (GFunc) g_free, NULL);
   2242 	g_slist_free(uuids);
   2243 }
   2244 
   2245 static void create_stored_device_from_linkkeys(char *key, char *value,
   2246 							void *user_data)
   2247 {
   2248 	struct btd_adapter *adapter = user_data;
   2249 	struct btd_device *device;
   2250 
   2251 	if (g_slist_find_custom(adapter->devices, key,
   2252 					(GCompareFunc) device_address_cmp))
   2253 		return;
   2254 
   2255 	device = device_create(connection, adapter, key);
   2256 	if (device) {
   2257 		device_set_temporary(device, FALSE);
   2258 		adapter->devices = g_slist_append(adapter->devices, device);
   2259 	}
   2260 }
   2261 
   2262 static void create_stored_device_from_blocked(char *key, char *value,
   2263 							void *user_data)
   2264 {
   2265 	struct btd_adapter *adapter = user_data;
   2266 	struct btd_device *device;
   2267 
   2268 	if (g_slist_find_custom(adapter->devices,
   2269 				key, (GCompareFunc) device_address_cmp))
   2270 		return;
   2271 
   2272 	device = device_create(connection, adapter, key);
   2273 	if (device) {
   2274 		device_set_temporary(device, FALSE);
   2275 		adapter->devices = g_slist_append(adapter->devices, device);
   2276 	}
   2277 }
   2278 
   2279 static void load_devices(struct btd_adapter *adapter)
   2280 {
   2281 	char filename[PATH_MAX + 1];
   2282 	char srcaddr[18];
   2283 
   2284 	ba2str(&adapter->bdaddr, srcaddr);
   2285 
   2286 	create_name(filename, PATH_MAX, STORAGEDIR, srcaddr, "profiles");
   2287 	textfile_foreach(filename, create_stored_device_from_profiles,
   2288 								adapter);
   2289 
   2290 	create_name(filename, PATH_MAX, STORAGEDIR, srcaddr, "linkkeys");
   2291 	textfile_foreach(filename, create_stored_device_from_linkkeys,
   2292 								adapter);
   2293 
   2294 	create_name(filename, PATH_MAX, STORAGEDIR, srcaddr, "blocked");
   2295 	textfile_foreach(filename, create_stored_device_from_blocked, adapter);
   2296 }
   2297 
   2298 static void clear_blocked(struct btd_adapter *adapter)
   2299 {
   2300 	int dd;
   2301 
   2302 	dd = hci_open_dev(adapter->dev_id);
   2303 	if (dd < 0) {
   2304 		error("hci_open_dev(hci%d): %s (%d)", adapter->dev_id,
   2305 						strerror(errno), errno);
   2306 		return;
   2307 	}
   2308 
   2309 	if (ioctl(dd, HCIUNBLOCKADDR, BDADDR_ANY) < 0)
   2310 		error("ioctl(HCIUNBLOCKADDR): %s (%d)", strerror(errno), errno);
   2311 
   2312 	hci_close_dev(dd);
   2313 }
   2314 
   2315 static void probe_driver(gpointer data, gpointer user_data)
   2316 {
   2317 	struct btd_adapter *adapter = data;
   2318 	struct btd_adapter_driver *driver = user_data;
   2319 	int err;
   2320 
   2321 	if (!adapter->up)
   2322 		return;
   2323 
   2324 	err = driver->probe(adapter);
   2325 	if (err < 0)
   2326 		error("%s: %s (%d)", driver->name, strerror(-err), -err);
   2327 }
   2328 
   2329 static void load_drivers(struct btd_adapter *adapter)
   2330 {
   2331 	GSList *l;
   2332 
   2333 	for (l = adapter_drivers; l; l = l->next) {
   2334 		struct btd_adapter_driver *driver = l->data;
   2335 
   2336 		if (driver->probe == NULL)
   2337 			continue;
   2338 
   2339 		probe_driver(adapter, driver);
   2340 	}
   2341 }
   2342 
   2343 static void load_connections(struct btd_adapter *adapter)
   2344 {
   2345 	struct hci_conn_list_req *cl = NULL;
   2346 	struct hci_conn_info *ci;
   2347 	int i, dd;
   2348 
   2349 	dd = hci_open_dev(adapter->dev_id);
   2350 	if (dd < 0)
   2351 		return;
   2352 
   2353 	cl = g_malloc0(10 * sizeof(*ci) + sizeof(*cl));
   2354 
   2355 	cl->dev_id = adapter->dev_id;
   2356 	cl->conn_num = 10;
   2357 	ci = cl->conn_info;
   2358 
   2359 	if (ioctl(dd, HCIGETCONNLIST, cl) != 0) {
   2360 		g_free(cl);
   2361 		hci_close_dev(dd);
   2362 		return;
   2363 	}
   2364 
   2365 	for (i = 0; i < cl->conn_num; i++, ci++) {
   2366 		struct btd_device *device;
   2367 		char address[18];
   2368 
   2369 		ba2str(&ci->bdaddr, address);
   2370 		device = adapter_get_device(connection, adapter, address);
   2371 		if (device)
   2372 			adapter_add_connection(adapter, device, ci->handle);
   2373 	}
   2374 
   2375 	g_free(cl);
   2376 	hci_close_dev(dd);
   2377 }
   2378 
   2379 static int get_discoverable_timeout(const char *src)
   2380 {
   2381 	int timeout;
   2382 
   2383 	if (read_discoverable_timeout(src, &timeout) == 0)
   2384 		return timeout;
   2385 
   2386 	return main_opts.discovto;
   2387 }
   2388 
   2389 static int get_pairable_timeout(const char *src)
   2390 {
   2391 	int timeout;
   2392 
   2393 	if (read_pairable_timeout(src, &timeout) == 0)
   2394 		return timeout;
   2395 
   2396 	return main_opts.pairto;
   2397 }
   2398 
   2399 static void adapter_disable_cod_cache(struct btd_adapter *adapter)
   2400 {
   2401 	int err;
   2402 
   2403 	if (!adapter)
   2404 		return;
   2405 
   2406 	if (!adapter->cache_enable)
   2407 		return;
   2408 
   2409 	/* Disable and flush svc cache. All successive service class updates
   2410 	   will be written to the device */
   2411 	adapter->cache_enable = FALSE;
   2412 
   2413 	if (adapter->current_cod == adapter->wanted_cod)
   2414 		return;
   2415 
   2416 	err = adapter_ops->set_class(adapter->dev_id, adapter->wanted_cod);
   2417 	if (err < 0)
   2418 		error("Adapter class update failed: %s(%d)",
   2419 						strerror(err), err);
   2420 	else
   2421 		adapter->pending_cod = adapter->wanted_cod;
   2422 }
   2423 
   2424 static int adapter_up(struct btd_adapter *adapter, const char *mode)
   2425 {
   2426 	char srcaddr[18];
   2427 	uint8_t scan_mode;
   2428 	gboolean powered, dev_down = FALSE;
   2429 	int err;
   2430 
   2431 	ba2str(&adapter->bdaddr, srcaddr);
   2432 
   2433 	adapter->off_requested = FALSE;
   2434 	adapter->up = 1;
   2435 	adapter->discov_timeout = get_discoverable_timeout(srcaddr);
   2436 	adapter->pairable_timeout = get_pairable_timeout(srcaddr);
   2437 	adapter->state = DISCOVER_TYPE_NONE;
   2438 	adapter->mode = MODE_CONNECTABLE;
   2439 	adapter->cache_enable = TRUE;
   2440 	scan_mode = SCAN_PAGE;
   2441 	powered = TRUE;
   2442 
   2443 	/* Set pairable mode */
   2444 	if (read_device_pairable(&adapter->bdaddr, &adapter->pairable) < 0)
   2445 		adapter->pairable = TRUE;
   2446 
   2447 	if (g_str_equal(mode, "off")) {
   2448 		char onmode[14];
   2449 
   2450 		powered = FALSE;
   2451 
   2452 		if (!adapter->initialized) {
   2453 			dev_down = TRUE;
   2454 			goto proceed;
   2455 		}
   2456 
   2457 		if (read_on_mode(srcaddr, onmode, sizeof(onmode)) < 0 ||
   2458 						g_str_equal(onmode, "off"))
   2459 			strcpy(onmode, "connectable");
   2460 
   2461 		write_device_mode(&adapter->bdaddr, onmode);
   2462 
   2463 		return adapter_up(adapter, onmode);
   2464 	} else if (!g_str_equal(mode, "connectable") &&
   2465 			adapter->discov_timeout == 0) {
   2466 		/* Set discoverable only if timeout is 0 */
   2467 		adapter->mode = MODE_DISCOVERABLE;
   2468 		scan_mode = SCAN_PAGE | SCAN_INQUIRY;
   2469 	}
   2470 
   2471 proceed:
   2472 	if (scan_mode == SCAN_PAGE)
   2473 		err = adapter_ops->set_connectable(adapter->dev_id);
   2474 	else
   2475 		err = adapter_ops->set_discoverable(adapter->dev_id);
   2476 
   2477 	if (err < 0)
   2478 		return err;
   2479 
   2480 	if (adapter->initialized == FALSE) {
   2481 		load_drivers(adapter);
   2482 		clear_blocked(adapter);
   2483 		load_devices(adapter);
   2484 
   2485 		/* retrieve the active connections: address the scenario where
   2486 		 * the are active connections before the daemon've started */
   2487 		load_connections(adapter);
   2488 
   2489 		adapter->initialized = TRUE;
   2490 
   2491 		manager_add_adapter(adapter->path);
   2492 
   2493 	}
   2494 
   2495 	if (dev_down) {
   2496 		adapter_ops->stop(adapter->dev_id);
   2497 		adapter->off_requested = TRUE;
   2498 		return 1;
   2499 	} else
   2500 		emit_property_changed(connection, adapter->path,
   2501 					ADAPTER_INTERFACE, "Powered",
   2502 					DBUS_TYPE_BOOLEAN, &powered);
   2503 
   2504 	adapter_disable_cod_cache(adapter);
   2505 
   2506 	return 0;
   2507 }
   2508 
   2509 int adapter_start(struct btd_adapter *adapter)
   2510 {
   2511 	struct hci_dev *dev = &adapter->dev;
   2512 	struct hci_dev_info di;
   2513 	struct hci_version ver;
   2514 	uint8_t features[8];
   2515 	int dd, err;
   2516 	char mode[14], address[18];
   2517 
   2518 	if (hci_devinfo(adapter->dev_id, &di) < 0)
   2519 		return -errno;
   2520 
   2521 	if (hci_test_bit(HCI_RAW, &di.flags)) {
   2522 		dev->ignore = 1;
   2523 		return -1;
   2524 	}
   2525 
   2526 	if (!bacmp(&di.bdaddr, BDADDR_ANY)) {
   2527 		int err;
   2528 
   2529 		DBG("Adapter %s without an address", adapter->path);
   2530 
   2531 		err = adapter_read_bdaddr(adapter->dev_id, &di.bdaddr);
   2532 		if (err < 0)
   2533 			return err;
   2534 	}
   2535 
   2536 	bacpy(&adapter->bdaddr, &di.bdaddr);
   2537 	memcpy(dev->features, di.features, 8);
   2538 	ba2str(&adapter->bdaddr, address);
   2539 
   2540 	err = read_device_mode(address, mode, sizeof(mode));
   2541 
   2542 	if ((!adapter->initialized && !main_opts.remember_powered) || err < 0) {
   2543 		if (!adapter->initialized && main_opts.mode == MODE_OFF)
   2544 			strcpy(mode, "off");
   2545 		else
   2546 			strcpy(mode, "connectable");
   2547 	}
   2548 
   2549 	dd = hci_open_dev(adapter->dev_id);
   2550 	if (dd < 0) {
   2551 		err = -errno;
   2552 		error("Can't open adapter %s: %s (%d)",
   2553 					adapter->path, strerror(errno), errno);
   2554 		return err;
   2555 	}
   2556 
   2557 	if (hci_read_local_version(dd, &ver, HCI_REQ_TIMEOUT) < 0) {
   2558 		err = -errno;
   2559 		error("Can't read version info for %s: %s (%d)",
   2560 					adapter->path, strerror(errno), errno);
   2561 		hci_close_dev(dd);
   2562 		return err;
   2563 	}
   2564 
   2565 	dev->hci_rev = ver.hci_rev;
   2566 	dev->lmp_ver = ver.lmp_ver;
   2567 	dev->lmp_subver = ver.lmp_subver;
   2568 	dev->manufacturer = ver.manufacturer;
   2569 
   2570 	if (hci_read_local_features(dd, features, HCI_REQ_TIMEOUT) < 0) {
   2571 		err = -errno;
   2572 		error("Can't read features for %s: %s (%d)",
   2573 					adapter->path, strerror(errno), errno);
   2574 		hci_close_dev(dd);
   2575 		return err;
   2576 	}
   2577 
   2578 	memcpy(dev->features, features, 8);
   2579 
   2580 	adapter_ops->read_name(adapter->dev_id);
   2581 
   2582 	if (!(features[6] & LMP_SIMPLE_PAIR))
   2583 		goto setup;
   2584 
   2585 	if (ioctl(dd, HCIGETAUTHINFO, NULL) < 0 && errno != EINVAL)
   2586 		hci_write_simple_pairing_mode(dd, 0x01, HCI_REQ_TIMEOUT);
   2587 
   2588 	if (hci_read_simple_pairing_mode(dd, &dev->ssp_mode,
   2589 						HCI_REQ_TIMEOUT) < 0) {
   2590 		err = -errno;
   2591 		error("Can't read simple pairing mode on %s: %s (%d)",
   2592 					adapter->path, strerror(errno), errno);
   2593 		/* Fall through since some chips have broken
   2594 		 * read_simple_pairing_mode behavior */
   2595 	}
   2596 
   2597 setup:
   2598 	hci_send_cmd(dd, OGF_LINK_POLICY, OCF_READ_DEFAULT_LINK_POLICY,
   2599 								0, NULL);
   2600 	hci_close_dev(dd);
   2601 
   2602 	adapter->current_cod = 0;
   2603 
   2604 	adapter_setup(adapter, mode);
   2605 
   2606 	if (!adapter->initialized && adapter->already_up) {
   2607 		DBG("Stopping Inquiry at adapter startup");
   2608 		adapter_ops->stop_discovery(adapter->dev_id);
   2609 	}
   2610 
   2611 	err = adapter_up(adapter, mode);
   2612 
   2613 	info("Adapter %s has been enabled", adapter->path);
   2614 
   2615 	return err;
   2616 }
   2617 
   2618 static void reply_pending_requests(struct btd_adapter *adapter)
   2619 {
   2620 	GSList *l;
   2621 
   2622 	if (!adapter)
   2623 		return;
   2624 
   2625 	/* pending bonding */
   2626 	for (l = adapter->devices; l; l = l->next) {
   2627 		struct btd_device *device = l->data;
   2628 
   2629 		if (device_is_bonding(device, NULL))
   2630 			device_cancel_bonding(device,
   2631 						HCI_OE_USER_ENDED_CONNECTION);
   2632 	}
   2633 
   2634 	if (adapter->state & STD_INQUIRY || adapter->state & PERIODIC_INQUIRY) {
   2635 		/* Cancel inquiry initiated by D-Bus client */
   2636 		if (adapter->disc_sessions)
   2637 			adapter_ops->stop_discovery(adapter->dev_id);
   2638 	}
   2639 }
   2640 
   2641 static void unload_drivers(struct btd_adapter *adapter)
   2642 {
   2643 	GSList *l;
   2644 
   2645 	for (l = adapter_drivers; l; l = l->next) {
   2646 		struct btd_adapter_driver *driver = l->data;
   2647 
   2648 		if (driver->remove)
   2649 			driver->remove(adapter);
   2650 	}
   2651 }
   2652 
   2653 int adapter_stop(struct btd_adapter *adapter)
   2654 {
   2655 	gboolean powered, discoverable, pairable;
   2656 
   2657 	/* cancel pending timeout */
   2658 	if (adapter->discov_timeout_id) {
   2659 		g_source_remove(adapter->discov_timeout_id);
   2660 		adapter->discov_timeout_id = 0;
   2661 	}
   2662 
   2663 	/* check pending requests */
   2664 	reply_pending_requests(adapter);
   2665 
   2666 	if (adapter->disc_sessions) {
   2667 		g_slist_foreach(adapter->disc_sessions, (GFunc) session_free,
   2668 				NULL);
   2669 		g_slist_free(adapter->disc_sessions);
   2670 		adapter->disc_sessions = NULL;
   2671 	}
   2672 
   2673 	clear_found_devices_list(adapter);
   2674 
   2675 	if (adapter->oor_devices) {
   2676 		g_slist_free(adapter->oor_devices);
   2677 		adapter->oor_devices = NULL;
   2678 	}
   2679 
   2680 	while (adapter->connections) {
   2681 		struct btd_device *device = adapter->connections->data;
   2682 		adapter_remove_connection(adapter, device, 0);
   2683 	}
   2684 
   2685 	if (adapter->scan_mode == (SCAN_PAGE | SCAN_INQUIRY)) {
   2686 		discoverable = FALSE;
   2687 		emit_property_changed(connection, adapter->path,
   2688 					ADAPTER_INTERFACE, "Discoverable",
   2689 					DBUS_TYPE_BOOLEAN, &discoverable);
   2690 	}
   2691 
   2692 	if ((adapter->scan_mode & SCAN_PAGE) && adapter->pairable == TRUE) {
   2693 		pairable = FALSE;
   2694 		emit_property_changed(connection, adapter->path,
   2695 					ADAPTER_INTERFACE, "Pairable",
   2696 					DBUS_TYPE_BOOLEAN, &pairable);
   2697 	}
   2698 
   2699 	powered = FALSE;
   2700 	emit_property_changed(connection, adapter->path, ADAPTER_INTERFACE,
   2701 				"Powered", DBUS_TYPE_BOOLEAN, &powered);
   2702 
   2703 	adapter->up = 0;
   2704 	adapter->scan_mode = SCAN_DISABLED;
   2705 	adapter->mode = MODE_OFF;
   2706 	adapter->state = DISCOVER_TYPE_NONE;
   2707 	adapter->cache_enable = TRUE;
   2708 	adapter->pending_cod = 0;
   2709 
   2710 	info("Adapter %s has been disabled", adapter->path);
   2711 
   2712 	return 0;
   2713 }
   2714 
   2715 int adapter_update(struct btd_adapter *adapter, uint8_t new_svc)
   2716 {
   2717 	struct hci_dev *dev = &adapter->dev;
   2718 
   2719 	if (dev->ignore)
   2720 		return 0;
   2721 
   2722 	adapter_set_service_classes(adapter, new_svc);
   2723 
   2724 	return 0;
   2725 }
   2726 
   2727 int adapter_update_ssp_mode(struct btd_adapter *adapter, uint8_t mode)
   2728 {
   2729 	struct hci_dev *dev = &adapter->dev;
   2730 
   2731 	dev->ssp_mode = mode;
   2732 
   2733 	update_ext_inquiry_response(adapter);
   2734 
   2735 	return 0;
   2736 }
   2737 
   2738 static void adapter_free(gpointer user_data)
   2739 {
   2740 	struct btd_adapter *adapter = user_data;
   2741 
   2742 	agent_free(adapter->agent);
   2743 	adapter->agent = NULL;
   2744 
   2745 	DBG("%p", adapter);
   2746 
   2747 	if (adapter->auth_idle_id)
   2748 		g_source_remove(adapter->auth_idle_id);
   2749 
   2750 	g_free(adapter->path);
   2751 	g_free(adapter);
   2752 }
   2753 
   2754 struct btd_adapter *btd_adapter_ref(struct btd_adapter *adapter)
   2755 {
   2756 	adapter->ref++;
   2757 
   2758 	DBG("%p: ref=%d", adapter, adapter->ref);
   2759 
   2760 	return adapter;
   2761 }
   2762 
   2763 void btd_adapter_unref(struct btd_adapter *adapter)
   2764 {
   2765 	gchar *path;
   2766 
   2767 	adapter->ref--;
   2768 
   2769 	DBG("%p: ref=%d", adapter, adapter->ref);
   2770 
   2771 	if (adapter->ref > 0)
   2772 		return;
   2773 
   2774 	path = g_strdup(adapter->path);
   2775 
   2776 	g_dbus_unregister_interface(connection, path, ADAPTER_INTERFACE);
   2777 
   2778 	g_free(path);
   2779 }
   2780 
   2781 struct btd_adapter *adapter_create(DBusConnection *conn, int id,
   2782 				gboolean devup)
   2783 {
   2784 	char path[MAX_PATH_LENGTH];
   2785 	struct btd_adapter *adapter;
   2786 	const char *base_path = manager_get_base_path();
   2787 
   2788 	if (!connection)
   2789 		connection = conn;
   2790 
   2791 	snprintf(path, sizeof(path), "%s/hci%d", base_path, id);
   2792 
   2793 	adapter = g_try_new0(struct btd_adapter, 1);
   2794 	if (!adapter) {
   2795 		error("adapter_create: failed to alloc memory for %s", path);
   2796 		return NULL;
   2797 	}
   2798 
   2799 	adapter->dev_id = id;
   2800 	if (main_opts.name_resolv)
   2801 		adapter->state |= RESOLVE_NAME;
   2802 	adapter->path = g_strdup(path);
   2803 	adapter->already_up = devup;
   2804 
   2805 	adapter->tx_power = 0;
   2806 
   2807 	if (!g_dbus_register_interface(conn, path, ADAPTER_INTERFACE,
   2808 			adapter_methods, adapter_signals, NULL,
   2809 			adapter, adapter_free)) {
   2810 		error("Adapter interface init failed on path %s", path);
   2811 		adapter_free(adapter);
   2812 		return NULL;
   2813 	}
   2814 
   2815 	return btd_adapter_ref(adapter);
   2816 }
   2817 
   2818 void adapter_remove(struct btd_adapter *adapter)
   2819 {
   2820 	GSList *l;
   2821 
   2822 	DBG("Removing adapter %s", adapter->path);
   2823 
   2824 	for (l = adapter->devices; l; l = l->next)
   2825 		device_remove(l->data, FALSE);
   2826 	g_slist_free(adapter->devices);
   2827 
   2828 	if (adapter->initialized)
   2829 		unload_drivers(adapter);
   2830 
   2831 	/* Return adapter to down state if it was not up on init */
   2832 	if (adapter->up && !adapter->already_up)
   2833 		adapter_ops->stop(adapter->dev_id);
   2834 
   2835 	btd_adapter_unref(adapter);
   2836 }
   2837 
   2838 uint16_t adapter_get_dev_id(struct btd_adapter *adapter)
   2839 {
   2840 	return adapter->dev_id;
   2841 }
   2842 
   2843 const gchar *adapter_get_path(struct btd_adapter *adapter)
   2844 {
   2845 	if (!adapter)
   2846 		return NULL;
   2847 
   2848 	return adapter->path;
   2849 }
   2850 
   2851 void adapter_get_address(struct btd_adapter *adapter, bdaddr_t *bdaddr)
   2852 {
   2853 	bacpy(bdaddr, &adapter->bdaddr);
   2854 }
   2855 
   2856 void adapter_set_state(struct btd_adapter *adapter, int state)
   2857 {
   2858 	gboolean discov_active = FALSE;
   2859 	const char *path = adapter->path;
   2860 
   2861 	if (adapter->state == state)
   2862 		return;
   2863 
   2864 	if (state & PERIODIC_INQUIRY || state & STD_INQUIRY)
   2865 		discov_active = TRUE;
   2866 	else if (adapter->disc_sessions && main_opts.discov_interval)
   2867 		adapter->scheduler_id = g_timeout_add_seconds(
   2868 						main_opts.discov_interval,
   2869 						(GSourceFunc) adapter_start_inquiry,
   2870 						adapter);
   2871 
   2872 	/* Send out of range */
   2873 	if (!discov_active)
   2874 		adapter_update_oor_devices(adapter);
   2875 
   2876 	emit_property_changed(connection, path,
   2877 				ADAPTER_INTERFACE, "Discovering",
   2878 				DBUS_TYPE_BOOLEAN, &discov_active);
   2879 
   2880 	adapter->state = state;
   2881 }
   2882 
   2883 int adapter_get_state(struct btd_adapter *adapter)
   2884 {
   2885 	return adapter->state;
   2886 }
   2887 
   2888 gboolean adapter_is_ready(struct btd_adapter *adapter)
   2889 {
   2890 	return adapter->initialized;
   2891 }
   2892 
   2893 struct remote_dev_info *adapter_search_found_devices(struct btd_adapter *adapter,
   2894 						struct remote_dev_info *match)
   2895 {
   2896 	GSList *l;
   2897 
   2898 	l = g_slist_find_custom(adapter->found_devices, match,
   2899 					(GCompareFunc) found_device_cmp);
   2900 	if (l)
   2901 		return l->data;
   2902 
   2903 	return NULL;
   2904 }
   2905 
   2906 static int dev_rssi_cmp(struct remote_dev_info *d1, struct remote_dev_info *d2)
   2907 {
   2908 	int rssi1, rssi2;
   2909 
   2910 	rssi1 = d1->rssi < 0 ? -d1->rssi : d1->rssi;
   2911 	rssi2 = d2->rssi < 0 ? -d2->rssi : d2->rssi;
   2912 
   2913 	return rssi1 - rssi2;
   2914 }
   2915 
   2916 static void append_dict_valist(DBusMessageIter *iter,
   2917 					const char *first_key,
   2918 					va_list var_args)
   2919 {
   2920 	DBusMessageIter dict;
   2921 	const char *key;
   2922 	int type;
   2923 	void *val;
   2924 
   2925 	dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY,
   2926 			DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
   2927 			DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
   2928 			DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict);
   2929 
   2930 	key = first_key;
   2931 	while (key) {
   2932 		type = va_arg(var_args, int);
   2933 		val = va_arg(var_args, void *);
   2934 		dict_append_entry(&dict, key, type, val);
   2935 		key = va_arg(var_args, char *);
   2936 	}
   2937 
   2938 	dbus_message_iter_close_container(iter, &dict);
   2939 }
   2940 
   2941 static void emit_device_found(const char *path, const char *address,
   2942 				const char *first_key, ...)
   2943 {
   2944 	DBusMessage *signal;
   2945 	DBusMessageIter iter;
   2946 	va_list var_args;
   2947 
   2948 	signal = dbus_message_new_signal(path, ADAPTER_INTERFACE,
   2949 					"DeviceFound");
   2950 	if (!signal) {
   2951 		error("Unable to allocate new %s.DeviceFound signal",
   2952 				ADAPTER_INTERFACE);
   2953 		return;
   2954 	}
   2955 	dbus_message_iter_init_append(signal, &iter);
   2956 	dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &address);
   2957 
   2958 	va_start(var_args, first_key);
   2959 	append_dict_valist(&iter, first_key, var_args);
   2960 	va_end(var_args);
   2961 
   2962 	g_dbus_send_message(connection, signal);
   2963 }
   2964 
   2965 void adapter_emit_device_found(struct btd_adapter *adapter,
   2966 				struct remote_dev_info *dev)
   2967 {
   2968 	struct btd_device *device;
   2969 	char peer_addr[18], local_addr[18];
   2970 	const char *icon, *paddr = peer_addr;
   2971 	dbus_bool_t paired = FALSE;
   2972 	dbus_int16_t rssi = dev->rssi;
   2973 	char *alias;
   2974 
   2975 	ba2str(&dev->bdaddr, peer_addr);
   2976 	ba2str(&adapter->bdaddr, local_addr);
   2977 
   2978 	device = adapter_find_device(adapter, paddr);
   2979 	if (device)
   2980 		paired = device_is_paired(device);
   2981 
   2982 	icon = class_to_icon(dev->class);
   2983 
   2984 	if (!dev->alias) {
   2985 		if (!dev->name) {
   2986 			alias = g_strdup(peer_addr);
   2987 			g_strdelimit(alias, ":", '-');
   2988 		} else
   2989 			alias = g_strdup(dev->name);
   2990 	} else
   2991 		alias = g_strdup(dev->alias);
   2992 
   2993 	emit_device_found(adapter->path, paddr,
   2994 			"Address", DBUS_TYPE_STRING, &paddr,
   2995 			"Class", DBUS_TYPE_UINT32, &dev->class,
   2996 			"Icon", DBUS_TYPE_STRING, &icon,
   2997 			"RSSI", DBUS_TYPE_INT16, &rssi,
   2998 			"Name", DBUS_TYPE_STRING, &dev->name,
   2999 			"Alias", DBUS_TYPE_STRING, &alias,
   3000 			"LegacyPairing", DBUS_TYPE_BOOLEAN, &dev->legacy,
   3001 			"Paired", DBUS_TYPE_BOOLEAN, &paired,
   3002 			NULL);
   3003 
   3004 	g_free(alias);
   3005 }
   3006 
   3007 void adapter_update_found_devices(struct btd_adapter *adapter, bdaddr_t *bdaddr,
   3008 				int8_t rssi, uint32_t class, const char *name,
   3009 				const char *alias, gboolean legacy,
   3010 				name_status_t name_status)
   3011 {
   3012 	struct remote_dev_info *dev, match;
   3013 
   3014 	memset(&match, 0, sizeof(struct remote_dev_info));
   3015 	bacpy(&match.bdaddr, bdaddr);
   3016 	match.name_status = NAME_ANY;
   3017 
   3018 	dev = adapter_search_found_devices(adapter, &match);
   3019 	if (dev) {
   3020 		/* Out of range list update */
   3021 		adapter->oor_devices = g_slist_remove(adapter->oor_devices,
   3022 							dev);
   3023 
   3024 		if (rssi == dev->rssi)
   3025 			return;
   3026 
   3027 		goto done;
   3028 	}
   3029 
   3030 	dev = g_new0(struct remote_dev_info, 1);
   3031 
   3032 	bacpy(&dev->bdaddr, bdaddr);
   3033 	dev->class = class;
   3034 	if (name)
   3035 		dev->name = g_strdup(name);
   3036 	if (alias)
   3037 		dev->alias = g_strdup(alias);
   3038 	dev->legacy = legacy;
   3039 	dev->name_status = name_status;
   3040 
   3041 	adapter->found_devices = g_slist_prepend(adapter->found_devices, dev);
   3042 
   3043 done:
   3044 	dev->rssi = rssi;
   3045 
   3046 	adapter->found_devices = g_slist_sort(adapter->found_devices,
   3047 						(GCompareFunc) dev_rssi_cmp);
   3048 
   3049 	adapter_emit_device_found(adapter, dev);
   3050 }
   3051 
   3052 int adapter_remove_found_device(struct btd_adapter *adapter, bdaddr_t *bdaddr)
   3053 {
   3054 	struct remote_dev_info *dev, match;
   3055 
   3056 	memset(&match, 0, sizeof(struct remote_dev_info));
   3057 	bacpy(&match.bdaddr, bdaddr);
   3058 
   3059 	dev = adapter_search_found_devices(adapter, &match);
   3060 	if (!dev)
   3061 		return -1;
   3062 
   3063 	dev->name_status = NAME_NOT_REQUIRED;
   3064 
   3065 	return 0;
   3066 }
   3067 
   3068 void adapter_update_oor_devices(struct btd_adapter *adapter)
   3069 {
   3070 	GSList *l;
   3071 
   3072 	for (l = adapter->oor_devices; l; l = l->next) {
   3073 		char address[18];
   3074 		const char *paddr = address;
   3075 		struct remote_dev_info *dev = l->data;
   3076 
   3077 		ba2str(&dev->bdaddr, address);
   3078 
   3079 		g_dbus_emit_signal(connection, adapter->path,
   3080 				ADAPTER_INTERFACE, "DeviceDisappeared",
   3081 				DBUS_TYPE_STRING, &paddr,
   3082 				DBUS_TYPE_INVALID);
   3083 
   3084 		adapter->found_devices = g_slist_remove(adapter->found_devices,
   3085 							dev);
   3086 		dev_info_free(dev);
   3087 	}
   3088 
   3089 	g_slist_free(adapter->oor_devices);
   3090 	adapter->oor_devices = NULL;
   3091 
   3092 	adapter->oor_devices = g_slist_copy(adapter->found_devices);
   3093 }
   3094 
   3095 static void set_mode_complete(struct btd_adapter *adapter)
   3096 {
   3097 	struct session_req *pending;
   3098 	const char *modestr;
   3099 	int err;
   3100 
   3101 	if (adapter->pending_mode == NULL)
   3102 		return;
   3103 
   3104 	pending = adapter->pending_mode;
   3105 	adapter->pending_mode = NULL;
   3106 
   3107 	err = (pending->mode != adapter->mode) ? -EINVAL : 0;
   3108 
   3109 	if (pending->msg != NULL) {
   3110 		DBusMessage *msg = pending->msg;
   3111 		DBusMessage *reply;
   3112 
   3113 		if (err < 0)
   3114 			reply = failed_strerror(msg, -err);
   3115 		else
   3116 			reply = g_dbus_create_reply(msg, DBUS_TYPE_INVALID);
   3117 
   3118 		g_dbus_send_message(connection, reply);
   3119 	}
   3120 
   3121 	modestr = mode2str(adapter->mode);
   3122 
   3123 	DBG("%s", modestr);
   3124 
   3125 	/* Only store if the mode matches the pending */
   3126 	if (err == 0)
   3127 		write_device_mode(&adapter->bdaddr, modestr);
   3128 	else
   3129 		error("unable to set mode: %s", mode2str(pending->mode));
   3130 
   3131 	session_unref(pending);
   3132 }
   3133 
   3134 void adapter_mode_changed(struct btd_adapter *adapter, uint8_t scan_mode)
   3135 {
   3136 	const gchar *path = adapter_get_path(adapter);
   3137 	gboolean discoverable, pairable;
   3138 
   3139 	if (adapter->scan_mode == scan_mode)
   3140 		return;
   3141 
   3142 	adapter_remove_discov_timeout(adapter);
   3143 
   3144 	switch (scan_mode) {
   3145 	case SCAN_DISABLED:
   3146 		adapter->mode = MODE_OFF;
   3147 		discoverable = FALSE;
   3148 		pairable = FALSE;
   3149 		break;
   3150 	case SCAN_PAGE:
   3151 		adapter->mode = MODE_CONNECTABLE;
   3152 		discoverable = FALSE;
   3153 		pairable = adapter->pairable;
   3154 		break;
   3155 	case (SCAN_PAGE | SCAN_INQUIRY):
   3156 		adapter->mode = MODE_DISCOVERABLE;
   3157 		discoverable = TRUE;
   3158 		pairable = adapter->pairable;
   3159 		if (adapter->discov_timeout != 0)
   3160 			adapter_set_discov_timeout(adapter,
   3161 						adapter->discov_timeout);
   3162 		break;
   3163 	case SCAN_INQUIRY:
   3164 		/* Address the scenario where a low-level application like
   3165 		 * hciconfig changed the scan mode */
   3166 		if (adapter->discov_timeout != 0)
   3167 			adapter_set_discov_timeout(adapter,
   3168 						adapter->discov_timeout);
   3169 
   3170 		/* ignore, this event should not be sent */
   3171 	default:
   3172 		/* ignore, reserved */
   3173 		return;
   3174 	}
   3175 
   3176 	/* If page scanning gets toggled emit the Pairable property */
   3177 	if ((adapter->scan_mode & SCAN_PAGE) != (scan_mode & SCAN_PAGE))
   3178 		emit_property_changed(connection, adapter->path,
   3179 					ADAPTER_INTERFACE, "Pairable",
   3180 					DBUS_TYPE_BOOLEAN, &pairable);
   3181 
   3182 	if (discoverable && adapter->pairable && adapter->discov_timeout > 0 &&
   3183 						adapter->discov_timeout <= 60)
   3184 		adapter_set_limited_discoverable(adapter, TRUE);
   3185 	else if (!discoverable)
   3186 		adapter_set_limited_discoverable(adapter, FALSE);
   3187 
   3188 	emit_property_changed(connection, path,
   3189 				ADAPTER_INTERFACE, "Discoverable",
   3190 				DBUS_TYPE_BOOLEAN, &discoverable);
   3191 
   3192 	adapter->scan_mode = scan_mode;
   3193 
   3194 	set_mode_complete(adapter);
   3195 }
   3196 
   3197 struct agent *adapter_get_agent(struct btd_adapter *adapter)
   3198 {
   3199 	if (!adapter || !adapter->agent)
   3200 		return NULL;
   3201 
   3202 	return adapter->agent;
   3203 }
   3204 
   3205 void adapter_add_connection(struct btd_adapter *adapter,
   3206 				struct btd_device *device, uint16_t handle)
   3207 {
   3208 	if (g_slist_find(adapter->connections, device)) {
   3209 		error("Unable to add connection %d", handle);
   3210 		return;
   3211 	}
   3212 
   3213 	device_add_connection(device, connection, handle);
   3214 
   3215 	adapter->connections = g_slist_append(adapter->connections, device);
   3216 }
   3217 
   3218 void adapter_remove_connection(struct btd_adapter *adapter,
   3219 				struct btd_device *device, uint16_t handle)
   3220 {
   3221 	bdaddr_t bdaddr;
   3222 
   3223 	if (!g_slist_find(adapter->connections, device)) {
   3224 		error("No matching connection for handle %u", handle);
   3225 		return;
   3226 	}
   3227 
   3228 	device_remove_connection(device, connection, handle);
   3229 
   3230 	adapter->connections = g_slist_remove(adapter->connections, device);
   3231 
   3232 	/* clean pending HCI cmds */
   3233 	device_get_address(device, &bdaddr);
   3234 	hci_req_queue_remove(adapter->dev_id, &bdaddr);
   3235 
   3236 	if (device_is_authenticating(device))
   3237 		device_cancel_authentication(device, TRUE);
   3238 
   3239 	if (device_is_temporary(device)) {
   3240 		const char *path = device_get_path(device);
   3241 
   3242 		DBG("Removing temporary device %s", path);
   3243 		adapter_remove_device(connection, adapter, device, TRUE);
   3244 	}
   3245 }
   3246 
   3247 gboolean adapter_has_discov_sessions(struct btd_adapter *adapter)
   3248 {
   3249 	if (!adapter || !adapter->disc_sessions)
   3250 		return FALSE;
   3251 
   3252 	return TRUE;
   3253 }
   3254 
   3255 int btd_register_adapter_driver(struct btd_adapter_driver *driver)
   3256 {
   3257 	GSList *adapters;
   3258 
   3259 	adapter_drivers = g_slist_append(adapter_drivers, driver);
   3260 
   3261 	if (driver->probe == NULL)
   3262 		return 0;
   3263 
   3264 	adapters = manager_get_adapters();
   3265 	g_slist_foreach(adapters, probe_driver, driver);
   3266 
   3267 	return 0;
   3268 }
   3269 
   3270 void btd_unregister_adapter_driver(struct btd_adapter_driver *driver)
   3271 {
   3272 	adapter_drivers = g_slist_remove(adapter_drivers, driver);
   3273 }
   3274 
   3275 static void agent_auth_cb(struct agent *agent, DBusError *derr,
   3276 							void *user_data)
   3277 {
   3278 	struct service_auth *auth = user_data;
   3279 
   3280 	device_set_authorizing(auth->device, FALSE);
   3281 
   3282 	auth->cb(derr, auth->user_data);
   3283 }
   3284 
   3285 static gboolean auth_idle_cb(gpointer user_data)
   3286 {
   3287 	struct service_auth *auth = user_data;
   3288 	struct btd_adapter *adapter = auth->adapter;
   3289 
   3290 	adapter->auth_idle_id = 0;
   3291 
   3292 	auth->cb(NULL, auth->user_data);
   3293 
   3294 	return FALSE;
   3295 }
   3296 
   3297 static int btd_adapter_authorize(struct btd_adapter *adapter,
   3298 					const bdaddr_t *dst,
   3299 					const char *uuid,
   3300 					service_auth_cb cb, void *user_data)
   3301 {
   3302 	struct service_auth *auth;
   3303 	struct btd_device *device;
   3304 	struct agent *agent;
   3305 	char address[18];
   3306 	const gchar *dev_path;
   3307 	int err;
   3308 
   3309 	ba2str(dst, address);
   3310 	device = adapter_find_device(adapter, address);
   3311 	if (!device)
   3312 		return -EPERM;
   3313 
   3314 	/* Device connected? */
   3315 	if (!g_slist_find(adapter->connections, device))
   3316 		return -ENOTCONN;
   3317 
   3318 	if (adapter->auth_idle_id)
   3319 		return -EBUSY;
   3320 
   3321 	auth = g_try_new0(struct service_auth, 1);
   3322 	if (!auth)
   3323 		return -ENOMEM;
   3324 
   3325 	auth->cb = cb;
   3326 	auth->user_data = user_data;
   3327 	auth->device = device;
   3328 	auth->adapter = adapter;
   3329 
   3330 	if (device_is_trusted(device) == TRUE) {
   3331 		adapter->auth_idle_id = g_idle_add_full(G_PRIORITY_DEFAULT_IDLE,
   3332 							auth_idle_cb, auth,
   3333 							g_free);
   3334 		return 0;
   3335 	}
   3336 
   3337 	agent = device_get_agent(device);
   3338 	if (!agent) {
   3339 		g_free(auth);
   3340 		return -EPERM;
   3341 	}
   3342 
   3343 	dev_path = device_get_path(device);
   3344 
   3345 	err = agent_authorize(agent, dev_path, uuid, agent_auth_cb, auth, g_free);
   3346 	if (err < 0)
   3347 		g_free(auth);
   3348 	else
   3349 		device_set_authorizing(device, TRUE);
   3350 
   3351 	return err;
   3352 }
   3353 
   3354 int btd_request_authorization(const bdaddr_t *src, const bdaddr_t *dst,
   3355 		const char *uuid, service_auth_cb cb, void *user_data)
   3356 {
   3357 	struct btd_adapter *adapter;
   3358 	GSList *adapters;
   3359 
   3360 	if (src == NULL || dst == NULL)
   3361 		return -EINVAL;
   3362 
   3363 	if (bacmp(src, BDADDR_ANY) != 0)
   3364 		goto proceed;
   3365 
   3366 	/* Handle request authorization for ANY adapter */
   3367 	adapters = manager_get_adapters();
   3368 
   3369 	for (; adapters; adapters = adapters->next) {
   3370 		int err;
   3371 		adapter = adapters->data;
   3372 
   3373 		err = btd_adapter_authorize(adapter, dst, uuid, cb, user_data);
   3374 		if (err == 0)
   3375 			return 0;
   3376 	}
   3377 
   3378 	return -EPERM;
   3379 
   3380 proceed:
   3381 	adapter = manager_find_adapter(src);
   3382 	if (!adapter)
   3383 		return -EPERM;
   3384 
   3385 	return btd_adapter_authorize(adapter, dst, uuid, cb, user_data);
   3386 }
   3387 
   3388 int btd_cancel_authorization(const bdaddr_t *src, const bdaddr_t *dst)
   3389 {
   3390 	struct btd_adapter *adapter = manager_find_adapter(src);
   3391 	struct btd_device *device;
   3392 	struct agent *agent;
   3393 	char address[18];
   3394 	int err;
   3395 
   3396 	if (!adapter)
   3397 		return -EPERM;
   3398 
   3399 	ba2str(dst, address);
   3400 	device = adapter_find_device(adapter, address);
   3401 	if (!device)
   3402 		return -EPERM;
   3403 
   3404 	if (adapter->auth_idle_id) {
   3405 		g_source_remove(adapter->auth_idle_id);
   3406 		adapter->auth_idle_id = 0;
   3407 		return 0;
   3408 	}
   3409 
   3410 	/*
   3411 	 * FIXME: Cancel fails if authorization is requested to adapter's
   3412 	 * agent and in the meanwhile CreatePairedDevice is called.
   3413 	 */
   3414 
   3415 	agent = device_get_agent(device);
   3416 	if (!agent)
   3417 		return -EPERM;
   3418 
   3419 	err = agent_cancel(agent);
   3420 
   3421 	if (err == 0)
   3422 		device_set_authorizing(device, FALSE);
   3423 
   3424 	return err;
   3425 }
   3426 
   3427 static gchar *adapter_any_path = NULL;
   3428 static int adapter_any_refcount = 0;
   3429 
   3430 const char *adapter_any_get_path(void)
   3431 {
   3432 	return adapter_any_path;
   3433 }
   3434 
   3435 const char *btd_adapter_any_request_path(void)
   3436 {
   3437 	if (adapter_any_refcount > 0)
   3438 		return adapter_any_path;
   3439 
   3440 	adapter_any_path = g_strdup_printf("%s/any", manager_get_base_path());
   3441 	adapter_any_refcount++;
   3442 
   3443 	return adapter_any_path;
   3444 }
   3445 
   3446 void btd_adapter_any_release_path(void)
   3447 {
   3448 	adapter_any_refcount--;
   3449 
   3450 	if (adapter_any_refcount > 0)
   3451 		return;
   3452 
   3453 	g_free(adapter_any_path);
   3454 	adapter_any_path = NULL;
   3455 }
   3456 
   3457 gboolean adapter_is_pairable(struct btd_adapter *adapter)
   3458 {
   3459 	return adapter->pairable;
   3460 }
   3461 
   3462 gboolean adapter_powering_down(struct btd_adapter *adapter)
   3463 {
   3464 	return adapter->off_requested;
   3465 }
   3466 
   3467 int btd_adapter_restore_powered(struct btd_adapter *adapter)
   3468 {
   3469 	char mode[14], address[18];
   3470 
   3471 	if (!adapter_ops)
   3472 		return -EINVAL;
   3473 
   3474 	if (!main_opts.remember_powered)
   3475 		return -EINVAL;
   3476 
   3477 	if (adapter->up)
   3478 		return 0;
   3479 
   3480 	ba2str(&adapter->bdaddr, address);
   3481 	if (read_device_mode(address, mode, sizeof(mode)) == 0 &&
   3482 						g_str_equal(mode, "off"))
   3483 		return 0;
   3484 
   3485 	return adapter_ops->set_powered(adapter->dev_id, TRUE);
   3486 }
   3487 
   3488 int btd_adapter_switch_online(struct btd_adapter *adapter)
   3489 {
   3490 	if (!adapter_ops)
   3491 		return -EINVAL;
   3492 
   3493 	if (adapter->up)
   3494 		return 0;
   3495 
   3496 	return adapter_ops->set_powered(adapter->dev_id, TRUE);
   3497 }
   3498 
   3499 int btd_adapter_switch_offline(struct btd_adapter *adapter)
   3500 {
   3501 	if (!adapter_ops)
   3502 		return -EINVAL;
   3503 
   3504 	if (!adapter->up)
   3505 		return 0;
   3506 
   3507 	return adapter_ops->set_powered(adapter->dev_id, FALSE);
   3508 }
   3509 
   3510 int btd_register_adapter_ops(struct btd_adapter_ops *btd_adapter_ops)
   3511 {
   3512 	/* Already registered */
   3513 	if (adapter_ops)
   3514 		return -EALREADY;
   3515 
   3516 	if (btd_adapter_ops->setup == NULL)
   3517 		return -EINVAL;
   3518 
   3519 	adapter_ops = btd_adapter_ops;
   3520 
   3521 	return 0;
   3522 }
   3523 
   3524 void btd_adapter_cleanup_ops(struct btd_adapter_ops *btd_adapter_ops)
   3525 {
   3526 	adapter_ops->cleanup();
   3527 }
   3528 
   3529 int adapter_ops_setup(void)
   3530 {
   3531 	if (!adapter_ops)
   3532 		return -EINVAL;
   3533 
   3534 	return adapter_ops->setup();
   3535 }
   3536