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